repo_name
stringclasses 6
values | pr_number
int64 512
78.9k
| pr_title
stringlengths 3
144
| pr_description
stringlengths 0
30.3k
| author
stringlengths 2
21
| date_created
timestamp[ns, tz=UTC] | date_merged
timestamp[ns, tz=UTC] | previous_commit
stringlengths 40
40
| pr_commit
stringlengths 40
40
| query
stringlengths 17
30.4k
| filepath
stringlengths 9
210
| before_content
stringlengths 0
112M
| after_content
stringlengths 0
112M
| label
int64 -1
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/VisualBasic/Test/Symbol/DocumentationComments/MethodDocumentationCommentTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class MethodDocumentationCommentTests
Inherits BasicTestBase
Private ReadOnly _compilation As VisualBasicCompilation
Private ReadOnly _acmeNamespace As NamespaceSymbol
Private ReadOnly _widgetClass As NamedTypeSymbol
Public Sub New()
_compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MethodDocumentationCommentTests">
<file name="a.vb">
Namespace Acme
Structure ValueType
Public Sub M(i As Integer)
End Sub
Public Shared Widening Operator CType(value As Byte) As ValueType
Return New ValueType
End Operator
End Structure
Class Widget
Public Class NestedClass
Public Sub M(i As Integer)
End Sub
End Class
Public Shared Sub M0()
End Sub
Public Sub M1(c As Char, ByRef f As Single, _
ByRef v As ValueType)
End Sub
Public Sub M2(x1() As Short, x2(,) As Integer, _
x3()() As Long)
End Sub
Public Sub M3(x3()() As Long, x4()(,,) As Widget)
End Sub
Public Sub M4(Optional i As Integer = 1)
End Sub
Public Sub M5(ParamArray args() As Object)
End Sub
Public Sub M7(z As (x1 As Integer, x2 As Integer, x3 As Integer, x4 As Integer, x5 As Integer, x6 As Integer, x7 As Short))
End Sub
Public Sub M10(y As (x1 As Integer, x2 As Short), z As System.Tuple(Of Integer, Short))
End Sub
End Class
Class MyList(Of T)
Public Sub Test(t As T)
End Sub
Public Sub Zip(other As MyList(Of T))
End Sub
Public Sub ReallyZip(other as MyList(Of MyList(Of T)))
End Sub
End Class
Class UseList
Public Sub Process(list As MyList(Of Integer))
End Sub
Public Function GetValues(Of T)(inputValue As T) As MyList(Of T)
Return Nothing
End Function
End Class
End Namespace
</file>
</compilation>)
_acmeNamespace = DirectCast(_compilation.GlobalNamespace.GetMembers("Acme").Single(), NamespaceSymbol)
_widgetClass = DirectCast(_acmeNamespace.GetTypeMembers("Widget").Single(), NamedTypeSymbol)
End Sub
<Fact>
Public Sub TestMethodInStructure()
Assert.Equal("M:Acme.ValueType.M(System.Int32)",
_acmeNamespace.GetTypeMembers("ValueType").Single() _
.GetMembers("M").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethodInNestedClass()
Assert.Equal("M:Acme.Widget.NestedClass.M(System.Int32)",
_widgetClass.GetTypeMembers("NestedClass").Single() _
.GetMembers("M").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethod1()
Assert.Equal("M:Acme.Widget.M0",
_widgetClass.GetMembers("M0").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethod2()
Assert.Equal("M:Acme.Widget.M1(System.Char,System.Single@,Acme.ValueType@)",
_widgetClass.GetMembers("M1").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethod3()
Assert.Equal("M:Acme.Widget.M2(System.Int16[],System.Int32[0:,0:],System.Int64[][])",
_widgetClass.GetMembers("M2").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethod4()
Assert.Equal("M:Acme.Widget.M3(System.Int64[][],Acme.Widget[0:,0:,0:][])",
_widgetClass.GetMembers("M3").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethod5()
Assert.Equal("M:Acme.Widget.M4(System.Int32)",
_widgetClass.GetMembers("M4").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethod6()
Assert.Equal("M:Acme.Widget.M5(System.Object[])",
_widgetClass.GetMembers("M5").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethod7()
Assert.Equal("M:Acme.Widget.M7(System.ValueTuple{System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int16})",
_widgetClass.GetMembers("M7").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethod10()
Assert.Equal("M:Acme.Widget.M10(System.ValueTuple{System.Int32,System.Int16},System.Tuple{System.Int32,System.Int16})",
_widgetClass.GetMembers("M10").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethodInGenericClass()
Assert.Equal("M:Acme.MyList`1.Test(`0)",
_acmeNamespace.GetTypeMembers("MyList", 1).Single() _
.GetMembers("Test").Single().GetDocumentationCommentId())
End Sub
<WorkItem(766313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766313")>
<Fact>
Public Sub TestMethodWithGenericDeclaringTypeAsParameter()
Assert.Equal("M:Acme.MyList`1.Zip(Acme.MyList{`0})",
_acmeNamespace.GetTypeMembers("MyList", 1).Single() _
.GetMembers("Zip").Single().GetDocumentationCommentId())
End Sub
<WorkItem(766313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766313")>
<Fact>
Public Sub TestMethodWithGenericDeclaringTypeAsTypeParameter()
Assert.Equal("M:Acme.MyList`1.ReallyZip(Acme.MyList{Acme.MyList{`0}})",
_acmeNamespace.GetTypeMembers("MyList", 1).Single() _
.GetMembers("ReallyZip").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethodWithClosedGenericParameter()
Assert.Equal("M:Acme.UseList.Process(Acme.MyList{System.Int32})",
_acmeNamespace.GetTypeMembers("UseList").Single() _
.GetMembers("Process").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestGenericMethod()
Assert.Equal("M:Acme.UseList.GetValues``1(``0)",
_acmeNamespace.GetTypeMembers("UseList").Single() _
.GetMembers("GetValues").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethodWithMissingType()
Dim csharpAssemblyReference = TestReferences.SymbolsTests.UseSiteErrors.CSharp
Dim ilAssemblyReference = TestReferences.SymbolsTests.UseSiteErrors.IL
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation>
<file name="a.vb">
Class C
Friend Shared F As CSharpErrors.ClassMethods
End Class
</file>
</compilation>,
{csharpAssemblyReference, ilAssemblyReference})
Dim type = compilation.Assembly.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C")
type = DirectCast(type.GetMember(Of FieldSymbol)("F").Type, NamedTypeSymbol)
Dim members = type.GetMembers()
Assert.InRange(members.Length, 1, Integer.MaxValue)
For Each member In members
Dim docComment = member.GetDocumentationCommentXml()
Assert.NotNull(docComment)
Next
End Sub
<Fact, WorkItem(530924, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530924")>
Public Sub TestConversionOperator()
Assert.Equal("M:Acme.ValueType.op_Implicit(System.Byte)~Acme.ValueType",
_acmeNamespace.GetTypeMembers("ValueType").Single() _
.GetMembers("op_Implicit").Single().GetDocumentationCommentId())
End Sub
<Fact, WorkItem(4699, "https://github.com/dotnet/roslyn/issues/4699")>
Public Sub GetMalformedDocumentationCommentXml()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Class Test
''' <summary>
''' Info
''' <!-- comment
''' </summary
Shared Sub Main()
End Sub
End Class
]]></file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=TestOptions.Regular.WithDocumentationMode(DocumentationMode.Diagnose))
Dim main = compilation.GetTypeByMetadataName("Test").GetMember(Of MethodSymbol)("Main")
Assert.Equal(
"<member name=""M:Test.Main"">
<summary>
Info
<!-- comment
</summary
</member>", main.GetDocumentationCommentXml().Trim())
compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=TestOptions.Regular.WithDocumentationMode(DocumentationMode.Parse))
main = compilation.GetTypeByMetadataName("Test").GetMember(Of MethodSymbol)("Main")
Assert.Equal(
"<member name=""M:Test.Main"">
<summary>
Info
<!-- comment
</summary
</member>", main.GetDocumentationCommentXml().Trim())
compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=TestOptions.Regular.WithDocumentationMode(DocumentationMode.None))
main = compilation.GetTypeByMetadataName("Test").GetMember(Of MethodSymbol)("Main")
Assert.Equal("", main.GetDocumentationCommentXml().Trim())
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class MethodDocumentationCommentTests
Inherits BasicTestBase
Private ReadOnly _compilation As VisualBasicCompilation
Private ReadOnly _acmeNamespace As NamespaceSymbol
Private ReadOnly _widgetClass As NamedTypeSymbol
Public Sub New()
_compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation name="MethodDocumentationCommentTests">
<file name="a.vb">
Namespace Acme
Structure ValueType
Public Sub M(i As Integer)
End Sub
Public Shared Widening Operator CType(value As Byte) As ValueType
Return New ValueType
End Operator
End Structure
Class Widget
Public Class NestedClass
Public Sub M(i As Integer)
End Sub
End Class
Public Shared Sub M0()
End Sub
Public Sub M1(c As Char, ByRef f As Single, _
ByRef v As ValueType)
End Sub
Public Sub M2(x1() As Short, x2(,) As Integer, _
x3()() As Long)
End Sub
Public Sub M3(x3()() As Long, x4()(,,) As Widget)
End Sub
Public Sub M4(Optional i As Integer = 1)
End Sub
Public Sub M5(ParamArray args() As Object)
End Sub
Public Sub M7(z As (x1 As Integer, x2 As Integer, x3 As Integer, x4 As Integer, x5 As Integer, x6 As Integer, x7 As Short))
End Sub
Public Sub M10(y As (x1 As Integer, x2 As Short), z As System.Tuple(Of Integer, Short))
End Sub
End Class
Class MyList(Of T)
Public Sub Test(t As T)
End Sub
Public Sub Zip(other As MyList(Of T))
End Sub
Public Sub ReallyZip(other as MyList(Of MyList(Of T)))
End Sub
End Class
Class UseList
Public Sub Process(list As MyList(Of Integer))
End Sub
Public Function GetValues(Of T)(inputValue As T) As MyList(Of T)
Return Nothing
End Function
End Class
End Namespace
</file>
</compilation>)
_acmeNamespace = DirectCast(_compilation.GlobalNamespace.GetMembers("Acme").Single(), NamespaceSymbol)
_widgetClass = DirectCast(_acmeNamespace.GetTypeMembers("Widget").Single(), NamedTypeSymbol)
End Sub
<Fact>
Public Sub TestMethodInStructure()
Assert.Equal("M:Acme.ValueType.M(System.Int32)",
_acmeNamespace.GetTypeMembers("ValueType").Single() _
.GetMembers("M").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethodInNestedClass()
Assert.Equal("M:Acme.Widget.NestedClass.M(System.Int32)",
_widgetClass.GetTypeMembers("NestedClass").Single() _
.GetMembers("M").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethod1()
Assert.Equal("M:Acme.Widget.M0",
_widgetClass.GetMembers("M0").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethod2()
Assert.Equal("M:Acme.Widget.M1(System.Char,System.Single@,Acme.ValueType@)",
_widgetClass.GetMembers("M1").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethod3()
Assert.Equal("M:Acme.Widget.M2(System.Int16[],System.Int32[0:,0:],System.Int64[][])",
_widgetClass.GetMembers("M2").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethod4()
Assert.Equal("M:Acme.Widget.M3(System.Int64[][],Acme.Widget[0:,0:,0:][])",
_widgetClass.GetMembers("M3").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethod5()
Assert.Equal("M:Acme.Widget.M4(System.Int32)",
_widgetClass.GetMembers("M4").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethod6()
Assert.Equal("M:Acme.Widget.M5(System.Object[])",
_widgetClass.GetMembers("M5").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethod7()
Assert.Equal("M:Acme.Widget.M7(System.ValueTuple{System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int16})",
_widgetClass.GetMembers("M7").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethod10()
Assert.Equal("M:Acme.Widget.M10(System.ValueTuple{System.Int32,System.Int16},System.Tuple{System.Int32,System.Int16})",
_widgetClass.GetMembers("M10").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethodInGenericClass()
Assert.Equal("M:Acme.MyList`1.Test(`0)",
_acmeNamespace.GetTypeMembers("MyList", 1).Single() _
.GetMembers("Test").Single().GetDocumentationCommentId())
End Sub
<WorkItem(766313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766313")>
<Fact>
Public Sub TestMethodWithGenericDeclaringTypeAsParameter()
Assert.Equal("M:Acme.MyList`1.Zip(Acme.MyList{`0})",
_acmeNamespace.GetTypeMembers("MyList", 1).Single() _
.GetMembers("Zip").Single().GetDocumentationCommentId())
End Sub
<WorkItem(766313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766313")>
<Fact>
Public Sub TestMethodWithGenericDeclaringTypeAsTypeParameter()
Assert.Equal("M:Acme.MyList`1.ReallyZip(Acme.MyList{Acme.MyList{`0}})",
_acmeNamespace.GetTypeMembers("MyList", 1).Single() _
.GetMembers("ReallyZip").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethodWithClosedGenericParameter()
Assert.Equal("M:Acme.UseList.Process(Acme.MyList{System.Int32})",
_acmeNamespace.GetTypeMembers("UseList").Single() _
.GetMembers("Process").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestGenericMethod()
Assert.Equal("M:Acme.UseList.GetValues``1(``0)",
_acmeNamespace.GetTypeMembers("UseList").Single() _
.GetMembers("GetValues").Single().GetDocumentationCommentId())
End Sub
<Fact>
Public Sub TestMethodWithMissingType()
Dim csharpAssemblyReference = TestReferences.SymbolsTests.UseSiteErrors.CSharp
Dim ilAssemblyReference = TestReferences.SymbolsTests.UseSiteErrors.IL
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(
<compilation>
<file name="a.vb">
Class C
Friend Shared F As CSharpErrors.ClassMethods
End Class
</file>
</compilation>,
{csharpAssemblyReference, ilAssemblyReference})
Dim type = compilation.Assembly.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C")
type = DirectCast(type.GetMember(Of FieldSymbol)("F").Type, NamedTypeSymbol)
Dim members = type.GetMembers()
Assert.InRange(members.Length, 1, Integer.MaxValue)
For Each member In members
Dim docComment = member.GetDocumentationCommentXml()
Assert.NotNull(docComment)
Next
End Sub
<Fact, WorkItem(530924, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530924")>
Public Sub TestConversionOperator()
Assert.Equal("M:Acme.ValueType.op_Implicit(System.Byte)~Acme.ValueType",
_acmeNamespace.GetTypeMembers("ValueType").Single() _
.GetMembers("op_Implicit").Single().GetDocumentationCommentId())
End Sub
<Fact, WorkItem(4699, "https://github.com/dotnet/roslyn/issues/4699")>
Public Sub GetMalformedDocumentationCommentXml()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Class Test
''' <summary>
''' Info
''' <!-- comment
''' </summary
Shared Sub Main()
End Sub
End Class
]]></file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=TestOptions.Regular.WithDocumentationMode(DocumentationMode.Diagnose))
Dim main = compilation.GetTypeByMetadataName("Test").GetMember(Of MethodSymbol)("Main")
Assert.Equal(
"<member name=""M:Test.Main"">
<summary>
Info
<!-- comment
</summary
</member>", main.GetDocumentationCommentXml().Trim())
compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=TestOptions.Regular.WithDocumentationMode(DocumentationMode.Parse))
main = compilation.GetTypeByMetadataName("Test").GetMember(Of MethodSymbol)("Main")
Assert.Equal(
"<member name=""M:Test.Main"">
<summary>
Info
<!-- comment
</summary
</member>", main.GetDocumentationCommentXml().Trim())
compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, parseOptions:=TestOptions.Regular.WithDocumentationMode(DocumentationMode.None))
main = compilation.GetTypeByMetadataName("Test").GetMember(Of MethodSymbol)("Main")
Assert.Equal("", main.GetDocumentationCommentXml().Trim())
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/Core/Portable/Workspace/Solution/PreservationMode.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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
{
/// <summary>
/// The mode in which value is preserved.
/// </summary>
public enum PreservationMode
{
/// <summary>
/// The value is guaranteed to have the same contents across multiple accesses.
/// </summary>
PreserveValue = 0,
/// <summary>
/// The value is guaranteed to the same instance across multiple accesses.
/// </summary>
PreserveIdentity = 1
}
internal static class PreservationModeExtensions
{
public static bool IsValid(this PreservationMode mode)
=> mode >= PreservationMode.PreserveValue && mode <= PreservationMode.PreserveIdentity;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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
{
/// <summary>
/// The mode in which value is preserved.
/// </summary>
public enum PreservationMode
{
/// <summary>
/// The value is guaranteed to have the same contents across multiple accesses.
/// </summary>
PreserveValue = 0,
/// <summary>
/// The value is guaranteed to the same instance across multiple accesses.
/// </summary>
PreserveIdentity = 1
}
internal static class PreservationModeExtensions
{
public static bool IsValid(this PreservationMode mode)
=> mode >= PreservationMode.PreserveValue && mode <= PreservationMode.PreserveIdentity;
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Analyzers/CSharp/Analyzers/UseImplicitObjectCreation/CSharpUseImplicitObjectCreationDiagnosticAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.UseImplicitObjectCreation
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class CSharpUseImplicitObjectCreationDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
public CSharpUseImplicitObjectCreationDiagnosticAnalyzer()
: base(IDEDiagnosticIds.UseImplicitObjectCreationDiagnosticId,
EnforceOnBuildValues.UseImplicitObjectCreation,
CSharpCodeStyleOptions.ImplicitObjectCreationWhenTypeIsApparent,
LanguageNames.CSharp,
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_new), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)),
new LocalizableResourceString(nameof(CSharpAnalyzersResources.new_expression_can_be_simplified), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)))
{
}
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.ObjectCreationExpression);
private void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
{
var options = context.Options;
var syntaxTree = context.Node.SyntaxTree;
var semanticModel = context.SemanticModel;
var cancellationToken = context.CancellationToken;
// Not available prior to C# 9.
if (((CSharpParseOptions)syntaxTree.Options).LanguageVersion < LanguageVersion.CSharp9)
return;
var optionSet = options.GetAnalyzerOptionSet(syntaxTree, cancellationToken);
var styleOption = options.GetOption(CSharpCodeStyleOptions.ImplicitObjectCreationWhenTypeIsApparent, syntaxTree, cancellationToken);
if (!styleOption.Value)
{
// Bail immediately if the user has disabled this feature.
return;
}
// type is apparent if we the object creation location is closely tied (spatially) to the explicit type. Specifically:
//
// 1. Variable declarations. i.e. `List<int> list = new ...`. Note: we will suppress ourselves if this
// is a field and the 'var' preferences would lead to preferring this as `var list = ...`
// 2. Expression-bodied constructs with an explicit return type. i.e. `List<int> Prop => new ...` or
// `List<int> GetValue(...) => ...` The latter doesn't necessarily have the object creation spatially next to
// the type. However, the type is always in a very easy to ascertain location in C#, so it is treated as
// apparent.
var objectCreation = (ObjectCreationExpressionSyntax)context.Node;
TypeSyntax? typeNode;
if (objectCreation.Parent.IsKind(SyntaxKind.EqualsValueClause) &&
objectCreation.Parent.Parent.IsKind(SyntaxKind.VariableDeclarator) &&
objectCreation.Parent.Parent.Parent is VariableDeclarationSyntax variableDeclaration &&
!variableDeclaration.Type.IsVar)
{
typeNode = variableDeclaration.Type;
var helper = CSharpUseImplicitTypeHelper.Instance;
if (helper.ShouldAnalyzeVariableDeclaration(variableDeclaration, cancellationToken) &&
helper.AnalyzeTypeName(typeNode, semanticModel, optionSet, cancellationToken).IsStylePreferred)
{
// this is a case where the user would prefer 'var'. don't offer to use an implicit object here.
return;
}
}
else if (objectCreation.Parent.IsKind(SyntaxKind.ArrowExpressionClause))
{
typeNode = objectCreation.Parent.Parent switch
{
LocalFunctionStatementSyntax localFunction => localFunction.ReturnType,
MethodDeclarationSyntax method => method.ReturnType,
ConversionOperatorDeclarationSyntax conversion => conversion.Type,
OperatorDeclarationSyntax op => op.ReturnType,
BasePropertyDeclarationSyntax property => property.Type,
AccessorDeclarationSyntax(SyntaxKind.GetAccessorDeclaration) { Parent: AccessorListSyntax { Parent: BasePropertyDeclarationSyntax baseProperty } } accessor => baseProperty.Type,
_ => null,
};
}
else
{
// more cases can be added here if we discover more cases we think the type is readily apparent from context.
return;
}
if (typeNode == null)
return;
// Only offer if the type being constructed is the exact same as the type being assigned into. We don't
// want to change semantics by trying to instantiate something else.
var leftType = semanticModel.GetTypeInfo(typeNode, cancellationToken).Type;
var rightType = semanticModel.GetTypeInfo(objectCreation, cancellationToken).Type;
if (leftType is null || rightType is null)
return;
if (leftType.IsErrorType() || rightType.IsErrorType())
return;
// The default SymbolEquivalenceComparer will ignore tuple name differences, which is advantageous here
if (!SymbolEquivalenceComparer.Instance.Equals(leftType, rightType))
{
return;
}
context.ReportDiagnostic(DiagnosticHelper.Create(
Descriptor,
objectCreation.Type.GetLocation(),
styleOption.Notification.Severity,
ImmutableArray.Create(objectCreation.GetLocation()),
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.Immutable;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.UseImplicitObjectCreation
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class CSharpUseImplicitObjectCreationDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
public CSharpUseImplicitObjectCreationDiagnosticAnalyzer()
: base(IDEDiagnosticIds.UseImplicitObjectCreationDiagnosticId,
EnforceOnBuildValues.UseImplicitObjectCreation,
CSharpCodeStyleOptions.ImplicitObjectCreationWhenTypeIsApparent,
LanguageNames.CSharp,
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_new), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)),
new LocalizableResourceString(nameof(CSharpAnalyzersResources.new_expression_can_be_simplified), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)))
{
}
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.ObjectCreationExpression);
private void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
{
var options = context.Options;
var syntaxTree = context.Node.SyntaxTree;
var semanticModel = context.SemanticModel;
var cancellationToken = context.CancellationToken;
// Not available prior to C# 9.
if (((CSharpParseOptions)syntaxTree.Options).LanguageVersion < LanguageVersion.CSharp9)
return;
var optionSet = options.GetAnalyzerOptionSet(syntaxTree, cancellationToken);
var styleOption = options.GetOption(CSharpCodeStyleOptions.ImplicitObjectCreationWhenTypeIsApparent, syntaxTree, cancellationToken);
if (!styleOption.Value)
{
// Bail immediately if the user has disabled this feature.
return;
}
// type is apparent if we the object creation location is closely tied (spatially) to the explicit type. Specifically:
//
// 1. Variable declarations. i.e. `List<int> list = new ...`. Note: we will suppress ourselves if this
// is a field and the 'var' preferences would lead to preferring this as `var list = ...`
// 2. Expression-bodied constructs with an explicit return type. i.e. `List<int> Prop => new ...` or
// `List<int> GetValue(...) => ...` The latter doesn't necessarily have the object creation spatially next to
// the type. However, the type is always in a very easy to ascertain location in C#, so it is treated as
// apparent.
var objectCreation = (ObjectCreationExpressionSyntax)context.Node;
TypeSyntax? typeNode;
if (objectCreation.Parent.IsKind(SyntaxKind.EqualsValueClause) &&
objectCreation.Parent.Parent.IsKind(SyntaxKind.VariableDeclarator) &&
objectCreation.Parent.Parent.Parent is VariableDeclarationSyntax variableDeclaration &&
!variableDeclaration.Type.IsVar)
{
typeNode = variableDeclaration.Type;
var helper = CSharpUseImplicitTypeHelper.Instance;
if (helper.ShouldAnalyzeVariableDeclaration(variableDeclaration, cancellationToken) &&
helper.AnalyzeTypeName(typeNode, semanticModel, optionSet, cancellationToken).IsStylePreferred)
{
// this is a case where the user would prefer 'var'. don't offer to use an implicit object here.
return;
}
}
else if (objectCreation.Parent.IsKind(SyntaxKind.ArrowExpressionClause))
{
typeNode = objectCreation.Parent.Parent switch
{
LocalFunctionStatementSyntax localFunction => localFunction.ReturnType,
MethodDeclarationSyntax method => method.ReturnType,
ConversionOperatorDeclarationSyntax conversion => conversion.Type,
OperatorDeclarationSyntax op => op.ReturnType,
BasePropertyDeclarationSyntax property => property.Type,
AccessorDeclarationSyntax(SyntaxKind.GetAccessorDeclaration) { Parent: AccessorListSyntax { Parent: BasePropertyDeclarationSyntax baseProperty } } accessor => baseProperty.Type,
_ => null,
};
}
else
{
// more cases can be added here if we discover more cases we think the type is readily apparent from context.
return;
}
if (typeNode == null)
return;
// Only offer if the type being constructed is the exact same as the type being assigned into. We don't
// want to change semantics by trying to instantiate something else.
var leftType = semanticModel.GetTypeInfo(typeNode, cancellationToken).Type;
var rightType = semanticModel.GetTypeInfo(objectCreation, cancellationToken).Type;
if (leftType is null || rightType is null)
return;
if (leftType.IsErrorType() || rightType.IsErrorType())
return;
// The default SymbolEquivalenceComparer will ignore tuple name differences, which is advantageous here
if (!SymbolEquivalenceComparer.Instance.Equals(leftType, rightType))
{
return;
}
context.ReportDiagnostic(DiagnosticHelper.Create(
Descriptor,
objectCreation.Type.GetLocation(),
styleOption.Notification.Severity,
ImmutableArray.Create(objectCreation.GetLocation()),
properties: null));
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/Test/CommentSelection/ToggleBlockCommentCommandHandlerTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Implementation.CommentSelection;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities.CommentSelection;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Composition;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.CommentSelection
{
[UseExportProvider]
public class ToggleBlockCommentCommandHandlerTests : AbstractToggleCommentTestBase
{
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_EmptyCaret()
{
var markup = @"$$";
var expected = @"[|/**/|]";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_EmptySelection()
{
var markup = @"[| |]";
var expected = @"[|/* */|]";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_SingleLineSelected()
{
var markup =
@"
class C
{
void M()
{
[|var i = 1;|]
}
}";
var expected =
@"
class C
{
void M()
{
[|/*var i = 1;*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_SingleLineWithWhitespaceSelected()
{
var markup =
@"
class C
{
void M()
{
[| var i = 1;|]
}
}";
var expected =
@"
class C
{
void M()
{
[|/* var i = 1;*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CaretInsideSingleLine()
{
var markup =
@"
class C
{
void M()
{
var$$ i = 1;
}
}";
var expected =
@"
class C
{
void M()
{
var[|/**/|] i = 1;
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_PartialLineSelected()
{
var markup =
@"
class C
{
void M()
{
var [|i = 1|];
}
}";
var expected =
@"
class C
{
void M()
{
var [|/*i = 1*/|];
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CaretInsideToken()
{
var markup =
@"
class C
{
void M()
{
va$$r i = 1;
}
}";
var expected =
@"
class C
{
void M()
{
var[|/**/|] i = 1;
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CaretInsideOperatorToken()
{
var markup = @"
class C
{
void M()
{
Func<int, bool> myFunc = x =$$> x == 5;
}
}";
var expected =
@"
class C
{
void M()
{
Func<int, bool> myFunc = x =>[|/**/|] x == 5;
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CaretInsideNewline()
{
var markup =
@"
class C
{
void M()
{
var i = 1;$$
}
}";
var expected =
@"
class C
{
void M()
{
var i = 1;[|/**/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_MultiLineSelection()
{
var markup =
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;
var k = 3;|]
}
}";
var expected =
@"
class C
{
void M()
{
[|/*var i = 1;
var j = 2;
var k = 3;*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_MultiLineSelectionWithWhitespace()
{
var markup =
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;
var k = 3;
|]
}
}";
var expected =
@"
class C
{
void M()
{
[|/*var i = 1;
var j = 2;
var k = 3;
*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_SingleLineCommentInSelection()
{
var markup =
@"
class C
{
void M()
{
[|//var i = 1;
var j = 2;|]
}
}";
var expected =
@"
class C
{
void M()
{
[|/*//var i = 1;
var j = 2;*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_BlockCommentBetweenCodeInSelection()
{
var markup =
@"
class C
{
void M()
{
[|var i = 1;
/*var j = 2;
var k = 3;*/
var l = 4;|]
}
}";
var expected =
@"
class C
{
void M()
{
[|/*var i = 1;
*//*var j = 2;
var k = 3;*//*
var l = 4;*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_SequentialBlockCommentBetweenCodeInSelection()
{
var markup =
@"
class C
{
void M()
{
[|var i = 1;
/*var j = 2;
var k = 3;*//*
var l = 4;*/
var m = 5;|]
}
}";
var expected =
@"
class C
{
void M()
{
[|/*var i = 1;
*//*var j = 2;
var k = 3;*//*
var l = 4;*//*
var m = 5;*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_SequentialBlockCommentsAndWhitespaceBetweenCodeInSelection()
{
var markup =
@"
class C
{
void M()
{
[|var i = 1;
/*var j = 2;
var k = 3;*/
/*
var l = 4;*/
var m = 5;|]
}
}";
var expected =
@"
class C
{
void M()
{
[|/*var i = 1;
*//*var j = 2;
var k = 3;*/
/*
var l = 4;*//*
var m = 5;*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CodeBetweenBlockCommentsInSelection()
{
var markup =
@"
class C
{
void M()
{
[|/*var i = 1;
var j = 2;*/
var k = 3;
/*var l = 4;
var m = 5;*/|]
}
}";
var expected =
@"
class C
{
void M()
{
[|/*var i = 1;
var j = 2;*//*
var k = 3;
*//*var l = 4;
var m = 5;*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CodeThenCommentInSelection()
{
var markup =
@"
class C
{
void M()
{
[|var i = 1;
/*var j = 2;
var k = 3;*/|]
}
}";
var expected =
@"
class C
{
void M()
{
[|/*var i = 1;
*//*var j = 2;
var k = 3;*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CodeThenCommentAndWhitespaceInSelection()
{
var markup =
@"
class C
{
void M()
{
[|var i = 1;
/*var j = 2;
var k = 3;*/
|]
}
}";
var expected =
@"
class C
{
void M()
{
[|/*var i = 1;
*//*var j = 2;
var k = 3;*/
|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CloseCommentOnlyInSelection()
{
var markup =
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;*/
var k = 3;|]
}
}";
var expected =
@"
class C
{
void M()
{
[|/*var i = 1;
var j = 2;*/
var k = 3;*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CodeThenPartialCommentInSelection()
{
var markup =
@"
class C
{
void M()
{
[|var i = 1;
/*var j = 2;
var|] k = 3;*/
}
}";
var expected =
@"
class C
{
void M()
{
[|/*var i = 1;
*//*var j = 2;
var*/|]/* k = 3;*/
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CommentThenCodeInSelection()
{
var markup =
@"
class C
{
void M()
{
[|/*var i = 1;
var j = 2;*/
var k = 3;|]
}
}";
var expected =
@"
class C
{
void M()
{
[|/*var i = 1;
var j = 2;*//*
var k = 3;*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CommentAndWhitespaceThenCodeInSelection()
{
var markup =
@"
class C
{
void M()
{
[| /*var i = 1;
var j = 2;*/
var k = 3;
|]
}
}";
var expected =
@"
class C
{
void M()
{
[| /*var i = 1;
var j = 2;*//*
var k = 3;
*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CommentCloseMarkerThenCodeInSelection()
{
var markup =
@"
class C
{
void M()
{
/*var i = 1;
var j = 2;[|*/
var k = 3;|]
}
}";
var expected =
@"
class C
{
void M()
{
/*var i = 1;
var j = 2;[|*//*
var k = 3;*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CodeThenCommentStartMarkerInSelection()
{
var markup =
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;/*|]
var k = 3;*/
}
}";
var expected =
@"
class C
{
void M()
{
[|/*var i = 1;
var j = 2;*//*|]
var k = 3;*/
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_PartialCommentThenCodeInSelection()
{
var markup =
@"
class C
{
void M()
{
/*var i = 1;
var [|j = 2;*/
var k = 3;|]
}
}";
var expected =
@"
class C
{
void M()
{
/*var i = 1;
var */[|/*j = 2;*//*
var k = 3;*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CaretBeforeBlockOnNewLine()
{
var markup =
@"
class C
{
void M()
{$$
/*var i = 1;*/
}
}";
var expected =
@"
class C
{
void M()
{[|/**/|]
/*var i = 1;*/
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CaretBeforeCodeAndBlock()
{
var markup =
@"
class C
{
void M()
{
$$ var /*i*/ = 1;
}
}";
var expected =
@"
class C
{
void M()
{
[|/**/|] var /*i*/ = 1;
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CaretAfterBlockOnNewLine()
{
var markup =
@"
class C
{
void M()
{
/*var i = 1*/
$$
}
}";
var expected =
@"
class C
{
void M()
{
/*var i = 1*/
[|/**/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CaretAfterBlockAndCode()
{
var markup =
@"
class C
{
void M()
{
/*var */i = 1; $$
}
}";
var expected =
@"
class C
{
void M()
{
/*var */i = 1; [|/**/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_BlockSelection()
{
var markup =
@"
class C
{
void M()
{
[|var i = 1;|]
[|var j = 2;|]
[|var k = 3;|]
}
}";
var expected =
@"
class C
{
void M()
{
[|/*var i = 1;*/|]
[|/*var j = 2;*/|]
[|/*var k = 3;*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_BlockSelectionPartiallyCommented()
{
var markup =
@"
class C
{
void M()
{
[|/*var i = 1;|]
[|var j = 2;*/|]
[|var k = 3; |]
}
}";
var expected =
@"
class C
{
void M()
{
[|/*var i = 1;*/|]/*
*/[|/*var j = 2;*/|]
[|/*var k = 3; */|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_DirectiveInsideSelection()
{
var markup =
@"
class C
{
void M()
{
[|var i = 1;
#if false
var j = 2;
#endif
var k = 3;|]
}
}";
var expected =
@"
class C
{
void M()
{
[|/*var i = 1;
#if false
var j = 2;
#endif
var k = 3;*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_WithProjectionBuffer()
{
var surfaceMarkup = @"< html >@{|S1:|}";
var csharpMarkup =
@"
{|S1:class C
{
void M()
{
[|var i = 1;|]
}
}|}";
var expected =
@"< html >@class C
{
void M()
{
[|/*var i = 1;*/|]
}
}";
ToggleCommentWithProjectionBuffer(surfaceMarkup, csharpMarkup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_AtBeginningOfFile()
{
var markup = @"[|/**/|]";
var expected = @"";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_CaretInsideBlock()
{
var markup =
@"
class C
{
void M()
{
/*var i = 1;
var $$j = 2;
var k = 3;*/
}
}";
var expected =
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;
var k = 3;|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_CaretInsideSequentialBlock()
{
var markup =
@"
class C
{
void M()
{
/*var i = 1;
var $$j = 2;*//*
var k = 3;*/
}
}";
var expected =
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;|]/*
var k = 3;*/
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_CaretBeforeBlockOnlyWhitespace()
{
var markup =
@"
class C
{
void M()
{
$$ /*var i = 1;
var*//* j = 2;*/
var k = 3;
}
}";
var expected =
@"
class C
{
void M()
{
[|var i = 1;
var|]/* j = 2;*/
var k = 3;
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_CaretBeforeMultipleBlocksOnlyWhitespace()
{
var markup =
@"
class C
{
void M()
{
$$ /*var*/ i = 1/**/;
var/* j = 2;*/
var k = 3;
}
}";
var expected =
@"
class C
{
void M()
{
[|var|] i = 1/**/;
var/* j = 2;*/
var k = 3;
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_CaretAfterBlockOnlyWhitespace()
{
var markup =
@"
class C
{
void M()
{
/*var i = 1;
var j = 2;*/ $$
}
}";
var expected =
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_CaretAfterMultipleBlocksOnlyWhitespace()
{
var markup =
@"
class C
{
void M()
{
var i = 1;
/*var*/ j /*= 2;*/ $$
}
}";
var expected =
@"
class C
{
void M()
{
var i = 1;
/*var*/ j [|= 2;|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_CaretInsideUnclosedBlock()
{
var markup =
@"
class C
{
void M()
{
/*var i = 1;
var $$j = 2;
var k = 3;
}
}";
var expected =
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;
var k = 3;
}
}|]";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_CommentInsideSelection()
{
var markup =
@"
class C
{
void M()
{
[|/*var i = 1;
var j = 2;
var k = 3;*/|]
}
}";
var expected =
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;
var k = 3;|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_CommentAndWhitespaceInSelection()
{
var markup =
@"
class C
{
void M()
{[|
/*var i = 1;
var j = 2;
var k = 3;*/ |]
}
}";
var expected =
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;
var k = 3;|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_CommentWithSingleLineCommentInSelection()
{
var markup =
@"
class C
{
void M()
{
[|/*var i = 1;
//var j = 2;
var k = 3;*/|]
}
}";
var expected =
@"
class C
{
void M()
{
[|var i = 1;
//var j = 2;
var k = 3;|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_SequentialBlockInSelection()
{
var markup =
@"
class C
{
void M()
{
[|/*var i = 1;
*//*var j = 2;
var k = 3;*/|]
}
}";
var expected =
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;
var k = 3;|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_SequentialBlockAndWhitespaceInSelection()
{
var markup =
@"
class C
{
void M()
{[|
/*var i = 1;
*/
/*var j = 2;
var k = 3;*/ |]
}
}";
var expected =
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;
var k = 3;|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_CommentPartiallyInsideSelection()
{
var markup =
@"
class C
{
void M()
{
/*var [|i = 1;
var j = 2;|]
var k = 3;*/
}
}";
var expected =
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;
var k = 3;|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_PartialSequentialBlockInSelection()
{
var markup =
@"
class C
{
void M()
{
/*var [|i = 1;
*//*var j = 2;
var |]k = 3;*/
}
}";
var expected =
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;
var k = 3;|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_BlockSelectionWithMultipleComments()
{
var markup =
@"
class C
{
void M()
{
[|/*var i = 1;*/|]
[|/*var j = 2;*/|]
[|/*var k = 3;*/|]
}
}";
var expected =
@"
class C
{
void M()
{
[|var i = 1;|]
[|var j = 2;|]
[|var k = 3;|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_BlockSelectionWithOneComment()
{
var markup =
@"
class C
{
void M()
{
[|/*var i = 1;|]
[|var j = 2; |]
[|var k = 3;*/|]
}
}";
var expected =
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;
var k = 3;|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_WithProjectionBuffer()
{
var surfaceMarkup = @"< html >@{|S1:|}";
var csharpMarkup =
@"
{|S1:class C
{
void M()
{
[|/*var i = 1;*/|]
}
}|}";
var expected =
@"< html >@class C
{
void M()
{
[|var i = 1;|]
}
}";
ToggleCommentWithProjectionBuffer(surfaceMarkup, csharpMarkup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void ToggleComment_MultiLineSelection()
{
var markup =
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;
var k = 3;|]
}
}";
var expectedText = new[]
{
@"
class C
{
void M()
{
[|/*var i = 1;
var j = 2;
var k = 3;*/|]
}
}",
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;
var k = 3;|]
}
}"
};
ToggleCommentMultiple(markup, expectedText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void ToggleComment_MultiCommentSelection()
{
var markup =
@"
class C
{
void M()
{
/*var i = 1;
[|var */ j = 2;
var k = 3;|]
}
}";
var expectedText = new[]
{
@"
class C
{
void M()
{
/*var i = 1;
*/[|/*var *//* j = 2;
var k = 3;*/|]
}
}",
@"
class C
{
void M()
{
/*var i = 1;
*/
[|var j = 2;
var k = 3;|]
}
}"
};
ToggleCommentMultiple(markup, expectedText);
}
internal override AbstractCommentSelectionBase<ValueTuple> GetToggleCommentCommandHandler(TestWorkspace workspace)
{
return (AbstractCommentSelectionBase<ValueTuple>)workspace.ExportProvider.GetExportedValues<ICommandHandler>()
.First(export => typeof(ToggleBlockCommentCommandHandler).Equals(export.GetType()));
}
internal override TestWorkspace GetWorkspace(string markup, TestComposition composition)
=> TestWorkspace.CreateCSharp(markup, composition: composition);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Implementation.CommentSelection;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities.CommentSelection;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Composition;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.CommentSelection
{
[UseExportProvider]
public class ToggleBlockCommentCommandHandlerTests : AbstractToggleCommentTestBase
{
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_EmptyCaret()
{
var markup = @"$$";
var expected = @"[|/**/|]";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_EmptySelection()
{
var markup = @"[| |]";
var expected = @"[|/* */|]";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_SingleLineSelected()
{
var markup =
@"
class C
{
void M()
{
[|var i = 1;|]
}
}";
var expected =
@"
class C
{
void M()
{
[|/*var i = 1;*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_SingleLineWithWhitespaceSelected()
{
var markup =
@"
class C
{
void M()
{
[| var i = 1;|]
}
}";
var expected =
@"
class C
{
void M()
{
[|/* var i = 1;*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CaretInsideSingleLine()
{
var markup =
@"
class C
{
void M()
{
var$$ i = 1;
}
}";
var expected =
@"
class C
{
void M()
{
var[|/**/|] i = 1;
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_PartialLineSelected()
{
var markup =
@"
class C
{
void M()
{
var [|i = 1|];
}
}";
var expected =
@"
class C
{
void M()
{
var [|/*i = 1*/|];
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CaretInsideToken()
{
var markup =
@"
class C
{
void M()
{
va$$r i = 1;
}
}";
var expected =
@"
class C
{
void M()
{
var[|/**/|] i = 1;
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CaretInsideOperatorToken()
{
var markup = @"
class C
{
void M()
{
Func<int, bool> myFunc = x =$$> x == 5;
}
}";
var expected =
@"
class C
{
void M()
{
Func<int, bool> myFunc = x =>[|/**/|] x == 5;
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CaretInsideNewline()
{
var markup =
@"
class C
{
void M()
{
var i = 1;$$
}
}";
var expected =
@"
class C
{
void M()
{
var i = 1;[|/**/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_MultiLineSelection()
{
var markup =
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;
var k = 3;|]
}
}";
var expected =
@"
class C
{
void M()
{
[|/*var i = 1;
var j = 2;
var k = 3;*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_MultiLineSelectionWithWhitespace()
{
var markup =
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;
var k = 3;
|]
}
}";
var expected =
@"
class C
{
void M()
{
[|/*var i = 1;
var j = 2;
var k = 3;
*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_SingleLineCommentInSelection()
{
var markup =
@"
class C
{
void M()
{
[|//var i = 1;
var j = 2;|]
}
}";
var expected =
@"
class C
{
void M()
{
[|/*//var i = 1;
var j = 2;*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_BlockCommentBetweenCodeInSelection()
{
var markup =
@"
class C
{
void M()
{
[|var i = 1;
/*var j = 2;
var k = 3;*/
var l = 4;|]
}
}";
var expected =
@"
class C
{
void M()
{
[|/*var i = 1;
*//*var j = 2;
var k = 3;*//*
var l = 4;*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_SequentialBlockCommentBetweenCodeInSelection()
{
var markup =
@"
class C
{
void M()
{
[|var i = 1;
/*var j = 2;
var k = 3;*//*
var l = 4;*/
var m = 5;|]
}
}";
var expected =
@"
class C
{
void M()
{
[|/*var i = 1;
*//*var j = 2;
var k = 3;*//*
var l = 4;*//*
var m = 5;*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_SequentialBlockCommentsAndWhitespaceBetweenCodeInSelection()
{
var markup =
@"
class C
{
void M()
{
[|var i = 1;
/*var j = 2;
var k = 3;*/
/*
var l = 4;*/
var m = 5;|]
}
}";
var expected =
@"
class C
{
void M()
{
[|/*var i = 1;
*//*var j = 2;
var k = 3;*/
/*
var l = 4;*//*
var m = 5;*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CodeBetweenBlockCommentsInSelection()
{
var markup =
@"
class C
{
void M()
{
[|/*var i = 1;
var j = 2;*/
var k = 3;
/*var l = 4;
var m = 5;*/|]
}
}";
var expected =
@"
class C
{
void M()
{
[|/*var i = 1;
var j = 2;*//*
var k = 3;
*//*var l = 4;
var m = 5;*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CodeThenCommentInSelection()
{
var markup =
@"
class C
{
void M()
{
[|var i = 1;
/*var j = 2;
var k = 3;*/|]
}
}";
var expected =
@"
class C
{
void M()
{
[|/*var i = 1;
*//*var j = 2;
var k = 3;*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CodeThenCommentAndWhitespaceInSelection()
{
var markup =
@"
class C
{
void M()
{
[|var i = 1;
/*var j = 2;
var k = 3;*/
|]
}
}";
var expected =
@"
class C
{
void M()
{
[|/*var i = 1;
*//*var j = 2;
var k = 3;*/
|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CloseCommentOnlyInSelection()
{
var markup =
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;*/
var k = 3;|]
}
}";
var expected =
@"
class C
{
void M()
{
[|/*var i = 1;
var j = 2;*/
var k = 3;*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CodeThenPartialCommentInSelection()
{
var markup =
@"
class C
{
void M()
{
[|var i = 1;
/*var j = 2;
var|] k = 3;*/
}
}";
var expected =
@"
class C
{
void M()
{
[|/*var i = 1;
*//*var j = 2;
var*/|]/* k = 3;*/
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CommentThenCodeInSelection()
{
var markup =
@"
class C
{
void M()
{
[|/*var i = 1;
var j = 2;*/
var k = 3;|]
}
}";
var expected =
@"
class C
{
void M()
{
[|/*var i = 1;
var j = 2;*//*
var k = 3;*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CommentAndWhitespaceThenCodeInSelection()
{
var markup =
@"
class C
{
void M()
{
[| /*var i = 1;
var j = 2;*/
var k = 3;
|]
}
}";
var expected =
@"
class C
{
void M()
{
[| /*var i = 1;
var j = 2;*//*
var k = 3;
*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CommentCloseMarkerThenCodeInSelection()
{
var markup =
@"
class C
{
void M()
{
/*var i = 1;
var j = 2;[|*/
var k = 3;|]
}
}";
var expected =
@"
class C
{
void M()
{
/*var i = 1;
var j = 2;[|*//*
var k = 3;*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CodeThenCommentStartMarkerInSelection()
{
var markup =
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;/*|]
var k = 3;*/
}
}";
var expected =
@"
class C
{
void M()
{
[|/*var i = 1;
var j = 2;*//*|]
var k = 3;*/
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_PartialCommentThenCodeInSelection()
{
var markup =
@"
class C
{
void M()
{
/*var i = 1;
var [|j = 2;*/
var k = 3;|]
}
}";
var expected =
@"
class C
{
void M()
{
/*var i = 1;
var */[|/*j = 2;*//*
var k = 3;*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CaretBeforeBlockOnNewLine()
{
var markup =
@"
class C
{
void M()
{$$
/*var i = 1;*/
}
}";
var expected =
@"
class C
{
void M()
{[|/**/|]
/*var i = 1;*/
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CaretBeforeCodeAndBlock()
{
var markup =
@"
class C
{
void M()
{
$$ var /*i*/ = 1;
}
}";
var expected =
@"
class C
{
void M()
{
[|/**/|] var /*i*/ = 1;
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CaretAfterBlockOnNewLine()
{
var markup =
@"
class C
{
void M()
{
/*var i = 1*/
$$
}
}";
var expected =
@"
class C
{
void M()
{
/*var i = 1*/
[|/**/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_CaretAfterBlockAndCode()
{
var markup =
@"
class C
{
void M()
{
/*var */i = 1; $$
}
}";
var expected =
@"
class C
{
void M()
{
/*var */i = 1; [|/**/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_BlockSelection()
{
var markup =
@"
class C
{
void M()
{
[|var i = 1;|]
[|var j = 2;|]
[|var k = 3;|]
}
}";
var expected =
@"
class C
{
void M()
{
[|/*var i = 1;*/|]
[|/*var j = 2;*/|]
[|/*var k = 3;*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_BlockSelectionPartiallyCommented()
{
var markup =
@"
class C
{
void M()
{
[|/*var i = 1;|]
[|var j = 2;*/|]
[|var k = 3; |]
}
}";
var expected =
@"
class C
{
void M()
{
[|/*var i = 1;*/|]/*
*/[|/*var j = 2;*/|]
[|/*var k = 3; */|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_DirectiveInsideSelection()
{
var markup =
@"
class C
{
void M()
{
[|var i = 1;
#if false
var j = 2;
#endif
var k = 3;|]
}
}";
var expected =
@"
class C
{
void M()
{
[|/*var i = 1;
#if false
var j = 2;
#endif
var k = 3;*/|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void AddComment_WithProjectionBuffer()
{
var surfaceMarkup = @"< html >@{|S1:|}";
var csharpMarkup =
@"
{|S1:class C
{
void M()
{
[|var i = 1;|]
}
}|}";
var expected =
@"< html >@class C
{
void M()
{
[|/*var i = 1;*/|]
}
}";
ToggleCommentWithProjectionBuffer(surfaceMarkup, csharpMarkup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_AtBeginningOfFile()
{
var markup = @"[|/**/|]";
var expected = @"";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_CaretInsideBlock()
{
var markup =
@"
class C
{
void M()
{
/*var i = 1;
var $$j = 2;
var k = 3;*/
}
}";
var expected =
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;
var k = 3;|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_CaretInsideSequentialBlock()
{
var markup =
@"
class C
{
void M()
{
/*var i = 1;
var $$j = 2;*//*
var k = 3;*/
}
}";
var expected =
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;|]/*
var k = 3;*/
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_CaretBeforeBlockOnlyWhitespace()
{
var markup =
@"
class C
{
void M()
{
$$ /*var i = 1;
var*//* j = 2;*/
var k = 3;
}
}";
var expected =
@"
class C
{
void M()
{
[|var i = 1;
var|]/* j = 2;*/
var k = 3;
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_CaretBeforeMultipleBlocksOnlyWhitespace()
{
var markup =
@"
class C
{
void M()
{
$$ /*var*/ i = 1/**/;
var/* j = 2;*/
var k = 3;
}
}";
var expected =
@"
class C
{
void M()
{
[|var|] i = 1/**/;
var/* j = 2;*/
var k = 3;
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_CaretAfterBlockOnlyWhitespace()
{
var markup =
@"
class C
{
void M()
{
/*var i = 1;
var j = 2;*/ $$
}
}";
var expected =
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_CaretAfterMultipleBlocksOnlyWhitespace()
{
var markup =
@"
class C
{
void M()
{
var i = 1;
/*var*/ j /*= 2;*/ $$
}
}";
var expected =
@"
class C
{
void M()
{
var i = 1;
/*var*/ j [|= 2;|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_CaretInsideUnclosedBlock()
{
var markup =
@"
class C
{
void M()
{
/*var i = 1;
var $$j = 2;
var k = 3;
}
}";
var expected =
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;
var k = 3;
}
}|]";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_CommentInsideSelection()
{
var markup =
@"
class C
{
void M()
{
[|/*var i = 1;
var j = 2;
var k = 3;*/|]
}
}";
var expected =
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;
var k = 3;|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_CommentAndWhitespaceInSelection()
{
var markup =
@"
class C
{
void M()
{[|
/*var i = 1;
var j = 2;
var k = 3;*/ |]
}
}";
var expected =
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;
var k = 3;|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_CommentWithSingleLineCommentInSelection()
{
var markup =
@"
class C
{
void M()
{
[|/*var i = 1;
//var j = 2;
var k = 3;*/|]
}
}";
var expected =
@"
class C
{
void M()
{
[|var i = 1;
//var j = 2;
var k = 3;|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_SequentialBlockInSelection()
{
var markup =
@"
class C
{
void M()
{
[|/*var i = 1;
*//*var j = 2;
var k = 3;*/|]
}
}";
var expected =
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;
var k = 3;|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_SequentialBlockAndWhitespaceInSelection()
{
var markup =
@"
class C
{
void M()
{[|
/*var i = 1;
*/
/*var j = 2;
var k = 3;*/ |]
}
}";
var expected =
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;
var k = 3;|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_CommentPartiallyInsideSelection()
{
var markup =
@"
class C
{
void M()
{
/*var [|i = 1;
var j = 2;|]
var k = 3;*/
}
}";
var expected =
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;
var k = 3;|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_PartialSequentialBlockInSelection()
{
var markup =
@"
class C
{
void M()
{
/*var [|i = 1;
*//*var j = 2;
var |]k = 3;*/
}
}";
var expected =
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;
var k = 3;|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_BlockSelectionWithMultipleComments()
{
var markup =
@"
class C
{
void M()
{
[|/*var i = 1;*/|]
[|/*var j = 2;*/|]
[|/*var k = 3;*/|]
}
}";
var expected =
@"
class C
{
void M()
{
[|var i = 1;|]
[|var j = 2;|]
[|var k = 3;|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_BlockSelectionWithOneComment()
{
var markup =
@"
class C
{
void M()
{
[|/*var i = 1;|]
[|var j = 2; |]
[|var k = 3;*/|]
}
}";
var expected =
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;
var k = 3;|]
}
}";
ToggleComment(markup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void RemoveComment_WithProjectionBuffer()
{
var surfaceMarkup = @"< html >@{|S1:|}";
var csharpMarkup =
@"
{|S1:class C
{
void M()
{
[|/*var i = 1;*/|]
}
}|}";
var expected =
@"< html >@class C
{
void M()
{
[|var i = 1;|]
}
}";
ToggleCommentWithProjectionBuffer(surfaceMarkup, csharpMarkup, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void ToggleComment_MultiLineSelection()
{
var markup =
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;
var k = 3;|]
}
}";
var expectedText = new[]
{
@"
class C
{
void M()
{
[|/*var i = 1;
var j = 2;
var k = 3;*/|]
}
}",
@"
class C
{
void M()
{
[|var i = 1;
var j = 2;
var k = 3;|]
}
}"
};
ToggleCommentMultiple(markup, expectedText);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.ToggleBlockComment)]
public void ToggleComment_MultiCommentSelection()
{
var markup =
@"
class C
{
void M()
{
/*var i = 1;
[|var */ j = 2;
var k = 3;|]
}
}";
var expectedText = new[]
{
@"
class C
{
void M()
{
/*var i = 1;
*/[|/*var *//* j = 2;
var k = 3;*/|]
}
}",
@"
class C
{
void M()
{
/*var i = 1;
*/
[|var j = 2;
var k = 3;|]
}
}"
};
ToggleCommentMultiple(markup, expectedText);
}
internal override AbstractCommentSelectionBase<ValueTuple> GetToggleCommentCommandHandler(TestWorkspace workspace)
{
return (AbstractCommentSelectionBase<ValueTuple>)workspace.ExportProvider.GetExportedValues<ICommandHandler>()
.First(export => typeof(ToggleBlockCommentCommandHandler).Equals(export.GetType()));
}
internal override TestWorkspace GetWorkspace(string markup, TestComposition composition)
=> TestWorkspace.CreateCSharp(markup, composition: composition);
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/MSBuildTask/GenerateMSBuildEditorConfig.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Text;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.BuildTasks
{
/// <summary>
/// Transforms a set of MSBuild Properties and Metadata into a global analyzer config.
/// </summary>
/// <remarks>
/// This task takes a set of items passed in via <see cref="MetadataItems"/> and <see cref="PropertyItems"/> and transforms
/// them into a global analyzer config.
///
/// <see cref="PropertyItems"/> is expected to be a list of items whose <see cref="ITaskItem.ItemSpec"/> is the property name
/// and have a metadata value called <c>Value</c> that contains the evaluated value of the property. Each of the ]
/// <see cref="PropertyItems"/> will be transformed into an <c>build_property.<em>ItemSpec</em> = <em>Value</em></c> entry in the
/// global section of the generated config file.
///
/// <see cref="MetadataItems"/> is expected to be a list of items whose <see cref="ITaskItem.ItemSpec"/> represents a file in the
/// compilation source tree. It should have two metadata values: <c>ItemType</c> is the name of the MSBuild item that originally
/// included the file (e.g. <c>Compile</c>, <c>AdditionalFile</c> etc.); <c>MetadataName</c> is expected to contain the name of
/// another piece of metadata that should be retrieved and used as the output value in the file. It is expected that a given
/// file can have multiple entries in the <see cref="MetadataItems" /> differing by its <c>ItemType</c>.
///
/// Each of the <see cref="MetadataItems"/> will be transformed into a new section in the generated config file. The section
/// header will be the full path of the item (generated via its<see cref="ITaskItem.ItemSpec"/>), and each section will have a
/// set of <c>build_metadata.<em>ItemType</em>.<em>MetadataName</em> = <em>RetrievedMetadataValue</em></c>, one per <c>ItemType</c>
///
/// The Microsoft.Managed.Core.targets calls this task with the collected results of the <c>AnalyzerProperty</c> and
/// <c>AnalyzerItemMetadata</c> item groups.
/// </remarks>
public sealed class GenerateMSBuildEditorConfig : Task
{
[Output]
public string ConfigFileContents { get; set; }
[Required]
public ITaskItem[] MetadataItems { get; set; }
[Required]
public ITaskItem[] PropertyItems { get; set; }
public GenerateMSBuildEditorConfig()
{
ConfigFileContents = string.Empty;
MetadataItems = Array.Empty<ITaskItem>();
PropertyItems = Array.Empty<ITaskItem>();
}
public override bool Execute()
{
StringBuilder builder = new StringBuilder();
// we always generate global configs
builder.AppendLine("is_global = true");
// collect the properties into a global section
foreach (var prop in PropertyItems)
{
builder.Append("build_property.")
.Append(prop.ItemSpec)
.Append(" = ")
.AppendLine(prop.GetMetadata("Value"));
}
// group the metadata items by their full path
var groupedItems = MetadataItems.GroupBy(i => NormalizeWithForwardSlash(i.GetMetadata("FullPath")));
foreach (var group in groupedItems)
{
// write the section for this item
builder.AppendLine()
.Append("[");
EncodeString(builder, group.Key);
builder.AppendLine("]");
foreach (var item in group)
{
string itemType = item.GetMetadata("ItemType");
string metadataName = item.GetMetadata("MetadataName");
if (!string.IsNullOrWhiteSpace(itemType) && !string.IsNullOrWhiteSpace(metadataName))
{
builder.Append("build_metadata.")
.Append(itemType)
.Append(".")
.Append(metadataName)
.Append(" = ")
.AppendLine(item.GetMetadata(metadataName));
}
}
}
ConfigFileContents = builder.ToString();
return true;
}
/// <remarks>
/// Filenames with special characters like '#' and'{' get written
/// into the section names in the resulting .editorconfig file. Later,
/// when the file is parsed in configuration options these special
/// characters are interpretted as invalid values and ignored by the
/// processor. We encode the special characters in these strings
/// before writing them here.
/// </remarks>
private static void EncodeString(StringBuilder builder, string value)
{
foreach (var c in value)
{
if (c is '*' or '?' or '{' or ',' or ';' or '}' or '[' or ']' or '#' or '!')
{
builder.Append("\\");
}
builder.Append(c);
}
}
/// <remarks>
/// Equivalent to Roslyn.Utilities.PathUtilities.NormalizeWithForwardSlash
/// Both methods should be kept in sync.
/// </remarks>
private static string NormalizeWithForwardSlash(string p)
=> PlatformInformation.IsUnix ? p : p.Replace('\\', '/');
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Text;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.BuildTasks
{
/// <summary>
/// Transforms a set of MSBuild Properties and Metadata into a global analyzer config.
/// </summary>
/// <remarks>
/// This task takes a set of items passed in via <see cref="MetadataItems"/> and <see cref="PropertyItems"/> and transforms
/// them into a global analyzer config.
///
/// <see cref="PropertyItems"/> is expected to be a list of items whose <see cref="ITaskItem.ItemSpec"/> is the property name
/// and have a metadata value called <c>Value</c> that contains the evaluated value of the property. Each of the ]
/// <see cref="PropertyItems"/> will be transformed into an <c>build_property.<em>ItemSpec</em> = <em>Value</em></c> entry in the
/// global section of the generated config file.
///
/// <see cref="MetadataItems"/> is expected to be a list of items whose <see cref="ITaskItem.ItemSpec"/> represents a file in the
/// compilation source tree. It should have two metadata values: <c>ItemType</c> is the name of the MSBuild item that originally
/// included the file (e.g. <c>Compile</c>, <c>AdditionalFile</c> etc.); <c>MetadataName</c> is expected to contain the name of
/// another piece of metadata that should be retrieved and used as the output value in the file. It is expected that a given
/// file can have multiple entries in the <see cref="MetadataItems" /> differing by its <c>ItemType</c>.
///
/// Each of the <see cref="MetadataItems"/> will be transformed into a new section in the generated config file. The section
/// header will be the full path of the item (generated via its<see cref="ITaskItem.ItemSpec"/>), and each section will have a
/// set of <c>build_metadata.<em>ItemType</em>.<em>MetadataName</em> = <em>RetrievedMetadataValue</em></c>, one per <c>ItemType</c>
///
/// The Microsoft.Managed.Core.targets calls this task with the collected results of the <c>AnalyzerProperty</c> and
/// <c>AnalyzerItemMetadata</c> item groups.
/// </remarks>
public sealed class GenerateMSBuildEditorConfig : Task
{
[Output]
public string ConfigFileContents { get; set; }
[Required]
public ITaskItem[] MetadataItems { get; set; }
[Required]
public ITaskItem[] PropertyItems { get; set; }
public GenerateMSBuildEditorConfig()
{
ConfigFileContents = string.Empty;
MetadataItems = Array.Empty<ITaskItem>();
PropertyItems = Array.Empty<ITaskItem>();
}
public override bool Execute()
{
StringBuilder builder = new StringBuilder();
// we always generate global configs
builder.AppendLine("is_global = true");
// collect the properties into a global section
foreach (var prop in PropertyItems)
{
builder.Append("build_property.")
.Append(prop.ItemSpec)
.Append(" = ")
.AppendLine(prop.GetMetadata("Value"));
}
// group the metadata items by their full path
var groupedItems = MetadataItems.GroupBy(i => NormalizeWithForwardSlash(i.GetMetadata("FullPath")));
foreach (var group in groupedItems)
{
// write the section for this item
builder.AppendLine()
.Append("[");
EncodeString(builder, group.Key);
builder.AppendLine("]");
foreach (var item in group)
{
string itemType = item.GetMetadata("ItemType");
string metadataName = item.GetMetadata("MetadataName");
if (!string.IsNullOrWhiteSpace(itemType) && !string.IsNullOrWhiteSpace(metadataName))
{
builder.Append("build_metadata.")
.Append(itemType)
.Append(".")
.Append(metadataName)
.Append(" = ")
.AppendLine(item.GetMetadata(metadataName));
}
}
}
ConfigFileContents = builder.ToString();
return true;
}
/// <remarks>
/// Filenames with special characters like '#' and'{' get written
/// into the section names in the resulting .editorconfig file. Later,
/// when the file is parsed in configuration options these special
/// characters are interpretted as invalid values and ignored by the
/// processor. We encode the special characters in these strings
/// before writing them here.
/// </remarks>
private static void EncodeString(StringBuilder builder, string value)
{
foreach (var c in value)
{
if (c is '*' or '?' or '{' or ',' or ';' or '}' or '[' or ']' or '#' or '!')
{
builder.Append("\\");
}
builder.Append(c);
}
}
/// <remarks>
/// Equivalent to Roslyn.Utilities.PathUtilities.NormalizeWithForwardSlash
/// Both methods should be kept in sync.
/// </remarks>
private static string NormalizeWithForwardSlash(string p)
=> PlatformInformation.IsUnix ? p : p.Replace('\\', '/');
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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 System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.GenerateFromMembers;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PickMembers;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, LanguageNames.VisualBasic,
Name = PredefinedCodeRefactoringProviderNames.GenerateEqualsAndGetHashCodeFromMembers), Shared]
[ExtensionOrder(After = PredefinedCodeRefactoringProviderNames.GenerateConstructorFromMembers,
Before = PredefinedCodeRefactoringProviderNames.AddConstructorParametersFromMembers)]
internal partial class GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider : AbstractGenerateFromMembersCodeRefactoringProvider
{
public const string GenerateOperatorsId = nameof(GenerateOperatorsId);
public const string ImplementIEquatableId = nameof(ImplementIEquatableId);
private const string EqualsName = nameof(object.Equals);
private const string GetHashCodeName = nameof(object.GetHashCode);
private readonly IPickMembersService? _pickMembersService_forTestingPurposes;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider()
: this(pickMembersService: null)
{
}
[SuppressMessage("RoslynDiagnosticsReliability", "RS0034:Exported parts should have [ImportingConstructor]", Justification = "Used incorrectly by tests")]
public GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider(IPickMembersService? pickMembersService)
=> _pickMembersService_forTestingPurposes = pickMembersService;
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var (document, textSpan, cancellationToken) = context;
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
{
return;
}
var actions = await GenerateEqualsAndGetHashCodeFromMembersAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
context.RegisterRefactorings(actions);
if (actions.IsDefaultOrEmpty && textSpan.IsEmpty)
{
await HandleNonSelectionAsync(context).ConfigureAwait(false);
}
}
private async Task HandleNonSelectionAsync(CodeRefactoringContext context)
{
var (document, textSpan, cancellationToken) = context;
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
// We offer the refactoring when the user is either on the header of a class/struct,
// or if they're between any members of a class/struct and are on a blank line.
if (!syntaxFacts.IsOnTypeHeader(root, textSpan.Start, out var typeDeclaration) &&
!syntaxFacts.IsBetweenTypeMembers(sourceText, root, textSpan.Start, out typeDeclaration))
{
return;
}
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
// Only supported on classes/structs.
var containingType = semanticModel.GetDeclaredSymbol(typeDeclaration) as INamedTypeSymbol;
if (containingType?.TypeKind is not TypeKind.Class and not TypeKind.Struct)
{
return;
}
// No overrides in static classes.
if (containingType.IsStatic)
{
return;
}
// Find all the possible instance fields/properties. If there are any, then
// show a dialog to the user to select the ones they want.
var viableMembers = containingType
.GetBaseTypesAndThis()
.Reverse()
.SelectAccessibleMembers<ISymbol>(containingType)
.Where(IsReadableInstanceFieldOrProperty)
.ToImmutableArray();
if (viableMembers.Length == 0)
{
return;
}
GetExistingMemberInfo(
containingType, out var hasEquals, out var hasGetHashCode);
var actions = await CreateActionsAsync(
document, typeDeclaration, containingType, viableMembers,
hasEquals, hasGetHashCode, withDialog: true, cancellationToken).ConfigureAwait(false);
context.RegisterRefactorings(actions);
}
private static bool HasOperators(INamedTypeSymbol containingType)
=> HasOperator(containingType, WellKnownMemberNames.EqualityOperatorName) ||
HasOperator(containingType, WellKnownMemberNames.InequalityOperatorName);
private static bool HasOperator(INamedTypeSymbol containingType, string operatorName)
=> containingType.GetMembers(operatorName)
.OfType<IMethodSymbol>()
.Any(m => m.MethodKind == MethodKind.UserDefinedOperator &&
m.Parameters.Length == 2 &&
containingType.Equals(m.Parameters[0].Type) &&
containingType.Equals(m.Parameters[1].Type));
private static bool CanImplementIEquatable(
SemanticModel semanticModel, INamedTypeSymbol containingType,
[NotNullWhen(true)] out INamedTypeSymbol? constructedType)
{
// A ref struct can never implement an interface, therefore never add IEquatable to the selection
// options if the type is a ref struct.
if (!containingType.IsRefLikeType)
{
var equatableTypeOpt = semanticModel.Compilation.GetTypeByMetadataName(typeof(IEquatable<>).FullName!);
if (equatableTypeOpt != null)
{
constructedType = equatableTypeOpt.Construct(containingType);
// A ref struct can never implement an interface, therefore never add IEquatable to the selection
// options if the type is a ref struct.
return !containingType.AllInterfaces.Contains(constructedType);
}
}
constructedType = null;
return false;
}
private static void GetExistingMemberInfo(INamedTypeSymbol containingType, out bool hasEquals, out bool hasGetHashCode)
{
hasEquals = containingType.GetMembers(EqualsName)
.OfType<IMethodSymbol>()
.Any(m => m.Parameters.Length == 1 && !m.IsStatic);
hasGetHashCode = containingType.GetMembers(GetHashCodeName)
.OfType<IMethodSymbol>()
.Any(m => m.Parameters.Length == 0 && !m.IsStatic);
}
public async Task<ImmutableArray<CodeAction>> GenerateEqualsAndGetHashCodeFromMembersAsync(
Document document,
TextSpan textSpan,
CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Refactoring_GenerateFromMembers_GenerateEqualsAndGetHashCode, cancellationToken))
{
var info = await GetSelectedMemberInfoAsync(document, textSpan, allowPartialSelection: false, cancellationToken).ConfigureAwait(false);
if (info != null &&
info.SelectedMembers.All(IsReadableInstanceFieldOrProperty))
{
if (info.ContainingType != null && info.ContainingType.TypeKind != TypeKind.Interface)
{
GetExistingMemberInfo(
info.ContainingType, out var hasEquals, out var hasGetHashCode);
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var typeDeclaration = syntaxFacts.GetContainingTypeDeclaration(root, textSpan.Start);
RoslynDebug.AssertNotNull(typeDeclaration);
return await CreateActionsAsync(
document, typeDeclaration, info.ContainingType, info.SelectedMembers,
hasEquals, hasGetHashCode, withDialog: false, cancellationToken).ConfigureAwait(false);
}
}
return default;
}
}
private async Task<ImmutableArray<CodeAction>> CreateActionsAsync(
Document document, SyntaxNode typeDeclaration, INamedTypeSymbol containingType, ImmutableArray<ISymbol> selectedMembers,
bool hasEquals, bool hasGetHashCode, bool withDialog, CancellationToken cancellationToken)
{
using var _ = ArrayBuilder<Task<CodeAction>>.GetInstance(out var tasks);
if (!hasEquals && !hasGetHashCode)
{
// if we don't have either Equals or GetHashCode then offer:
// "Generate Equals" and
// "Generate Equals and GethashCode"
//
// Don't bother offering to just "Generate GetHashCode" as it's very unlikely
// the user would need to bother just generating that member without also
// generating 'Equals' as well.
tasks.Add(CreateCodeActionAsync(
document, typeDeclaration, containingType, selectedMembers,
generateEquals: true, generateGetHashCode: false, withDialog, cancellationToken));
tasks.Add(CreateCodeActionAsync(
document, typeDeclaration, containingType, selectedMembers,
generateEquals: true, generateGetHashCode: true, withDialog, cancellationToken));
}
else if (!hasEquals)
{
tasks.Add(CreateCodeActionAsync(
document, typeDeclaration, containingType, selectedMembers,
generateEquals: true, generateGetHashCode: false, withDialog, cancellationToken));
}
else if (!hasGetHashCode)
{
tasks.Add(CreateCodeActionAsync(
document, typeDeclaration, containingType, selectedMembers,
generateEquals: false, generateGetHashCode: true, withDialog, cancellationToken));
}
var codeActions = await Task.WhenAll(tasks).ConfigureAwait(false);
return codeActions.ToImmutableArray();
}
private Task<CodeAction> CreateCodeActionAsync(
Document document, SyntaxNode typeDeclaration, INamedTypeSymbol containingType, ImmutableArray<ISymbol> members,
bool generateEquals, bool generateGetHashCode, bool withDialog, CancellationToken cancellationToken)
{
return withDialog
? CreateCodeActionWithDialogAsync(document, typeDeclaration, containingType, members, generateEquals, generateGetHashCode, cancellationToken)
: CreateCodeActionWithoutDialogAsync(document, typeDeclaration, containingType, members, generateEquals, generateGetHashCode, cancellationToken);
}
private async Task<CodeAction> CreateCodeActionWithDialogAsync(
Document document, SyntaxNode typeDeclaration, INamedTypeSymbol containingType, ImmutableArray<ISymbol> members,
bool generateEquals, bool generateGetHashCode, CancellationToken cancellationToken)
{
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
using var _ = ArrayBuilder<PickMembersOption>.GetInstance(out var pickMembersOptions);
if (CanImplementIEquatable(semanticModel, containingType, out var equatableTypeOpt))
{
var value = options.GetOption(GenerateEqualsAndGetHashCodeFromMembersOptions.ImplementIEquatable);
var displayName = equatableTypeOpt.ToDisplayString(new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters));
pickMembersOptions.Add(new PickMembersOption(
ImplementIEquatableId,
string.Format(FeaturesResources.Implement_0, displayName),
value));
}
if (!HasOperators(containingType))
{
var value = options.GetOption(GenerateEqualsAndGetHashCodeFromMembersOptions.GenerateOperators);
pickMembersOptions.Add(new PickMembersOption(
GenerateOperatorsId,
FeaturesResources.Generate_operators,
value));
}
return new GenerateEqualsAndGetHashCodeWithDialogCodeAction(
this, document, typeDeclaration, containingType, members,
pickMembersOptions.ToImmutable(), generateEquals, generateGetHashCode);
}
private static async Task<CodeAction> CreateCodeActionWithoutDialogAsync(
Document document, SyntaxNode typeDeclaration, INamedTypeSymbol containingType, ImmutableArray<ISymbol> members,
bool generateEquals, bool generateGetHashCode, CancellationToken cancellationToken)
{
var implementIEquatable = false;
var generateOperators = false;
if (generateEquals && containingType.TypeKind == TypeKind.Struct)
{
// if we're generating equals for a struct, then also add IEquatable<S> support as
// well as operators (as long as the struct does not already have them).
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
implementIEquatable = CanImplementIEquatable(semanticModel, containingType, out _);
generateOperators = !HasOperators(containingType);
}
return new GenerateEqualsAndGetHashCodeAction(
document, typeDeclaration, containingType, members,
generateEquals, generateGetHashCode, implementIEquatable, generateOperators);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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 System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.GenerateFromMembers;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PickMembers;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, LanguageNames.VisualBasic,
Name = PredefinedCodeRefactoringProviderNames.GenerateEqualsAndGetHashCodeFromMembers), Shared]
[ExtensionOrder(After = PredefinedCodeRefactoringProviderNames.GenerateConstructorFromMembers,
Before = PredefinedCodeRefactoringProviderNames.AddConstructorParametersFromMembers)]
internal partial class GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider : AbstractGenerateFromMembersCodeRefactoringProvider
{
public const string GenerateOperatorsId = nameof(GenerateOperatorsId);
public const string ImplementIEquatableId = nameof(ImplementIEquatableId);
private const string EqualsName = nameof(object.Equals);
private const string GetHashCodeName = nameof(object.GetHashCode);
private readonly IPickMembersService? _pickMembersService_forTestingPurposes;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider()
: this(pickMembersService: null)
{
}
[SuppressMessage("RoslynDiagnosticsReliability", "RS0034:Exported parts should have [ImportingConstructor]", Justification = "Used incorrectly by tests")]
public GenerateEqualsAndGetHashCodeFromMembersCodeRefactoringProvider(IPickMembersService? pickMembersService)
=> _pickMembersService_forTestingPurposes = pickMembersService;
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var (document, textSpan, cancellationToken) = context;
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
{
return;
}
var actions = await GenerateEqualsAndGetHashCodeFromMembersAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
context.RegisterRefactorings(actions);
if (actions.IsDefaultOrEmpty && textSpan.IsEmpty)
{
await HandleNonSelectionAsync(context).ConfigureAwait(false);
}
}
private async Task HandleNonSelectionAsync(CodeRefactoringContext context)
{
var (document, textSpan, cancellationToken) = context;
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
// We offer the refactoring when the user is either on the header of a class/struct,
// or if they're between any members of a class/struct and are on a blank line.
if (!syntaxFacts.IsOnTypeHeader(root, textSpan.Start, out var typeDeclaration) &&
!syntaxFacts.IsBetweenTypeMembers(sourceText, root, textSpan.Start, out typeDeclaration))
{
return;
}
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
// Only supported on classes/structs.
var containingType = semanticModel.GetDeclaredSymbol(typeDeclaration) as INamedTypeSymbol;
if (containingType?.TypeKind is not TypeKind.Class and not TypeKind.Struct)
{
return;
}
// No overrides in static classes.
if (containingType.IsStatic)
{
return;
}
// Find all the possible instance fields/properties. If there are any, then
// show a dialog to the user to select the ones they want.
var viableMembers = containingType
.GetBaseTypesAndThis()
.Reverse()
.SelectAccessibleMembers<ISymbol>(containingType)
.Where(IsReadableInstanceFieldOrProperty)
.ToImmutableArray();
if (viableMembers.Length == 0)
{
return;
}
GetExistingMemberInfo(
containingType, out var hasEquals, out var hasGetHashCode);
var actions = await CreateActionsAsync(
document, typeDeclaration, containingType, viableMembers,
hasEquals, hasGetHashCode, withDialog: true, cancellationToken).ConfigureAwait(false);
context.RegisterRefactorings(actions);
}
private static bool HasOperators(INamedTypeSymbol containingType)
=> HasOperator(containingType, WellKnownMemberNames.EqualityOperatorName) ||
HasOperator(containingType, WellKnownMemberNames.InequalityOperatorName);
private static bool HasOperator(INamedTypeSymbol containingType, string operatorName)
=> containingType.GetMembers(operatorName)
.OfType<IMethodSymbol>()
.Any(m => m.MethodKind == MethodKind.UserDefinedOperator &&
m.Parameters.Length == 2 &&
containingType.Equals(m.Parameters[0].Type) &&
containingType.Equals(m.Parameters[1].Type));
private static bool CanImplementIEquatable(
SemanticModel semanticModel, INamedTypeSymbol containingType,
[NotNullWhen(true)] out INamedTypeSymbol? constructedType)
{
// A ref struct can never implement an interface, therefore never add IEquatable to the selection
// options if the type is a ref struct.
if (!containingType.IsRefLikeType)
{
var equatableTypeOpt = semanticModel.Compilation.GetTypeByMetadataName(typeof(IEquatable<>).FullName!);
if (equatableTypeOpt != null)
{
constructedType = equatableTypeOpt.Construct(containingType);
// A ref struct can never implement an interface, therefore never add IEquatable to the selection
// options if the type is a ref struct.
return !containingType.AllInterfaces.Contains(constructedType);
}
}
constructedType = null;
return false;
}
private static void GetExistingMemberInfo(INamedTypeSymbol containingType, out bool hasEquals, out bool hasGetHashCode)
{
hasEquals = containingType.GetMembers(EqualsName)
.OfType<IMethodSymbol>()
.Any(m => m.Parameters.Length == 1 && !m.IsStatic);
hasGetHashCode = containingType.GetMembers(GetHashCodeName)
.OfType<IMethodSymbol>()
.Any(m => m.Parameters.Length == 0 && !m.IsStatic);
}
public async Task<ImmutableArray<CodeAction>> GenerateEqualsAndGetHashCodeFromMembersAsync(
Document document,
TextSpan textSpan,
CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Refactoring_GenerateFromMembers_GenerateEqualsAndGetHashCode, cancellationToken))
{
var info = await GetSelectedMemberInfoAsync(document, textSpan, allowPartialSelection: false, cancellationToken).ConfigureAwait(false);
if (info != null &&
info.SelectedMembers.All(IsReadableInstanceFieldOrProperty))
{
if (info.ContainingType != null && info.ContainingType.TypeKind != TypeKind.Interface)
{
GetExistingMemberInfo(
info.ContainingType, out var hasEquals, out var hasGetHashCode);
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var typeDeclaration = syntaxFacts.GetContainingTypeDeclaration(root, textSpan.Start);
RoslynDebug.AssertNotNull(typeDeclaration);
return await CreateActionsAsync(
document, typeDeclaration, info.ContainingType, info.SelectedMembers,
hasEquals, hasGetHashCode, withDialog: false, cancellationToken).ConfigureAwait(false);
}
}
return default;
}
}
private async Task<ImmutableArray<CodeAction>> CreateActionsAsync(
Document document, SyntaxNode typeDeclaration, INamedTypeSymbol containingType, ImmutableArray<ISymbol> selectedMembers,
bool hasEquals, bool hasGetHashCode, bool withDialog, CancellationToken cancellationToken)
{
using var _ = ArrayBuilder<Task<CodeAction>>.GetInstance(out var tasks);
if (!hasEquals && !hasGetHashCode)
{
// if we don't have either Equals or GetHashCode then offer:
// "Generate Equals" and
// "Generate Equals and GethashCode"
//
// Don't bother offering to just "Generate GetHashCode" as it's very unlikely
// the user would need to bother just generating that member without also
// generating 'Equals' as well.
tasks.Add(CreateCodeActionAsync(
document, typeDeclaration, containingType, selectedMembers,
generateEquals: true, generateGetHashCode: false, withDialog, cancellationToken));
tasks.Add(CreateCodeActionAsync(
document, typeDeclaration, containingType, selectedMembers,
generateEquals: true, generateGetHashCode: true, withDialog, cancellationToken));
}
else if (!hasEquals)
{
tasks.Add(CreateCodeActionAsync(
document, typeDeclaration, containingType, selectedMembers,
generateEquals: true, generateGetHashCode: false, withDialog, cancellationToken));
}
else if (!hasGetHashCode)
{
tasks.Add(CreateCodeActionAsync(
document, typeDeclaration, containingType, selectedMembers,
generateEquals: false, generateGetHashCode: true, withDialog, cancellationToken));
}
var codeActions = await Task.WhenAll(tasks).ConfigureAwait(false);
return codeActions.ToImmutableArray();
}
private Task<CodeAction> CreateCodeActionAsync(
Document document, SyntaxNode typeDeclaration, INamedTypeSymbol containingType, ImmutableArray<ISymbol> members,
bool generateEquals, bool generateGetHashCode, bool withDialog, CancellationToken cancellationToken)
{
return withDialog
? CreateCodeActionWithDialogAsync(document, typeDeclaration, containingType, members, generateEquals, generateGetHashCode, cancellationToken)
: CreateCodeActionWithoutDialogAsync(document, typeDeclaration, containingType, members, generateEquals, generateGetHashCode, cancellationToken);
}
private async Task<CodeAction> CreateCodeActionWithDialogAsync(
Document document, SyntaxNode typeDeclaration, INamedTypeSymbol containingType, ImmutableArray<ISymbol> members,
bool generateEquals, bool generateGetHashCode, CancellationToken cancellationToken)
{
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
using var _ = ArrayBuilder<PickMembersOption>.GetInstance(out var pickMembersOptions);
if (CanImplementIEquatable(semanticModel, containingType, out var equatableTypeOpt))
{
var value = options.GetOption(GenerateEqualsAndGetHashCodeFromMembersOptions.ImplementIEquatable);
var displayName = equatableTypeOpt.ToDisplayString(new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters));
pickMembersOptions.Add(new PickMembersOption(
ImplementIEquatableId,
string.Format(FeaturesResources.Implement_0, displayName),
value));
}
if (!HasOperators(containingType))
{
var value = options.GetOption(GenerateEqualsAndGetHashCodeFromMembersOptions.GenerateOperators);
pickMembersOptions.Add(new PickMembersOption(
GenerateOperatorsId,
FeaturesResources.Generate_operators,
value));
}
return new GenerateEqualsAndGetHashCodeWithDialogCodeAction(
this, document, typeDeclaration, containingType, members,
pickMembersOptions.ToImmutable(), generateEquals, generateGetHashCode);
}
private static async Task<CodeAction> CreateCodeActionWithoutDialogAsync(
Document document, SyntaxNode typeDeclaration, INamedTypeSymbol containingType, ImmutableArray<ISymbol> members,
bool generateEquals, bool generateGetHashCode, CancellationToken cancellationToken)
{
var implementIEquatable = false;
var generateOperators = false;
if (generateEquals && containingType.TypeKind == TypeKind.Struct)
{
// if we're generating equals for a struct, then also add IEquatable<S> support as
// well as operators (as long as the struct does not already have them).
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
implementIEquatable = CanImplementIEquatable(semanticModel, containingType, out _);
generateOperators = !HasOperators(containingType);
}
return new GenerateEqualsAndGetHashCodeAction(
document, typeDeclaration, containingType, members,
generateEquals, generateGetHashCode, implementIEquatable, generateOperators);
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/Core.Wpf/LineSeparators/LineSeparatorTag.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Microsoft.CodeAnalysis.Editor.Implementation.Adornments;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Formatting;
namespace Microsoft.CodeAnalysis.Editor.Implementation.LineSeparators
{
/// <summary>
/// Tag that specifies line separator.
/// </summary>
internal class LineSeparatorTag : GraphicsTag
{
public LineSeparatorTag(IEditorFormatMap editorFormatMap)
: base(editorFormatMap)
{
}
protected override Color? GetColor(
IWpfTextView view, IEditorFormatMap editorFormatMap)
{
var brush = view.VisualElement.TryFindResource("outlining.verticalrule.foreground") as SolidColorBrush;
return brush?.Color;
}
/// <summary>
/// Creates a very long line at the bottom of bounds.
/// </summary>
public override GraphicsResult GetGraphics(IWpfTextView view, Geometry bounds, TextFormattingRunProperties format)
{
Initialize(view);
var border = new Border()
{
BorderBrush = _graphicsTagBrush,
BorderThickness = new Thickness(0, 0, 0, bottom: 1),
Height = 1,
Width = view.ViewportWidth
};
void viewportWidthChangedHandler(object s, EventArgs e)
{
border.Width = view.ViewportWidth;
}
view.ViewportWidthChanged += viewportWidthChangedHandler;
// Subtract rect.Height to ensure that the line separator is drawn
// at the bottom of the line, rather than immediately below.
// This makes the line separator line up with the outlining bracket.
Canvas.SetTop(border, bounds.Bounds.Bottom - border.Height);
return new GraphicsResult(border,
() => view.ViewportWidthChanged -= viewportWidthChangedHandler);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Microsoft.CodeAnalysis.Editor.Implementation.Adornments;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Formatting;
namespace Microsoft.CodeAnalysis.Editor.Implementation.LineSeparators
{
/// <summary>
/// Tag that specifies line separator.
/// </summary>
internal class LineSeparatorTag : GraphicsTag
{
public LineSeparatorTag(IEditorFormatMap editorFormatMap)
: base(editorFormatMap)
{
}
protected override Color? GetColor(
IWpfTextView view, IEditorFormatMap editorFormatMap)
{
var brush = view.VisualElement.TryFindResource("outlining.verticalrule.foreground") as SolidColorBrush;
return brush?.Color;
}
/// <summary>
/// Creates a very long line at the bottom of bounds.
/// </summary>
public override GraphicsResult GetGraphics(IWpfTextView view, Geometry bounds, TextFormattingRunProperties format)
{
Initialize(view);
var border = new Border()
{
BorderBrush = _graphicsTagBrush,
BorderThickness = new Thickness(0, 0, 0, bottom: 1),
Height = 1,
Width = view.ViewportWidth
};
void viewportWidthChangedHandler(object s, EventArgs e)
{
border.Width = view.ViewportWidth;
}
view.ViewportWidthChanged += viewportWidthChangedHandler;
// Subtract rect.Height to ensure that the line separator is drawn
// at the bottom of the line, rather than immediately below.
// This makes the line separator line up with the outlining bracket.
Canvas.SetTop(border, bounds.Bounds.Bottom - border.Height);
return new GraphicsResult(border,
() => view.ViewportWidthChanged -= viewportWidthChangedHandler);
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Test/Resources/Core/SymbolsTests/NoPia/Pia5.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Generic
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58259")>
<Assembly: ImportedFromTypeLib("Pia5.dll")>
<ComImport(), Guid("27e3e649-994b-4f58-b3c6-f8089a5f2c05"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> _
Public Interface I5
Function Goo() As List(Of I6)
End Interface
<ComImport(), Guid("27e3e649-994b-4f58-b3c6-f8089a5f2c06"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> _
Public Interface I6
End Interface
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Generic
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58259")>
<Assembly: ImportedFromTypeLib("Pia5.dll")>
<ComImport(), Guid("27e3e649-994b-4f58-b3c6-f8089a5f2c05"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> _
Public Interface I5
Function Goo() As List(Of I6)
End Interface
<ComImport(), Guid("27e3e649-994b-4f58-b3c6-f8089a5f2c06"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> _
Public Interface I6
End Interface
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Tools/ExternalAccess/FSharp/Diagnostics/IFSharpDiagnosticAnalyzerService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Diagnostics
{
internal interface IFSharpDiagnosticAnalyzerService
{
/// <summary>
/// re-analyze given projects and documents
/// </summary>
void Reanalyze(Workspace workspace, IEnumerable<ProjectId> projectIds = null, IEnumerable<DocumentId> documentIds = null, bool highPriority = false);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Diagnostics
{
internal interface IFSharpDiagnosticAnalyzerService
{
/// <summary>
/// re-analyze given projects and documents
/// </summary>
void Reanalyze(Workspace workspace, IEnumerable<ProjectId> projectIds = null, IEnumerable<DocumentId> documentIds = null, bool highPriority = false);
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/IntegrationTest/IntegrationTests/Properties/launchSettings.json | {
"profiles": {
"xUnit.net Console (32-bit)": {
"commandName": "Executable",
"executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe",
"commandLineArgs": "$(TargetPath) -noshadow -verbose"
},
"xUnit.net Console (64-bit)": {
"commandName": "Executable",
"executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe",
"commandLineArgs": "$(TargetPath) -noshadow -verbose"
}
}
} | {
"profiles": {
"xUnit.net Console (32-bit)": {
"commandName": "Executable",
"executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe",
"commandLineArgs": "$(TargetPath) -noshadow -verbose"
},
"xUnit.net Console (64-bit)": {
"commandName": "Executable",
"executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe",
"commandLineArgs": "$(TargetPath) -noshadow -verbose"
}
}
} | -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/VisualBasic/Portable/Symbols/Source/TypeParameterConstraintKind.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
<Flags()>
Friend Enum TypeParameterConstraintKind
None = 0
ReferenceType = 1
ValueType = 2
Constructor = 4
End Enum
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
<Flags()>
Friend Enum TypeParameterConstraintKind
None = 0
ReferenceType = 1
ValueType = 2
Constructor = 4
End Enum
End Namespace
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/VisualBasicTest/Recommendations/Expressions/KeyKeywordRecommenderTests.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.Expressions
Public Class KeyKeywordRecommenderTests
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub KeyNotInStatementTest()
VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "Key")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub KeyNotAfterArrayInitializerSquiggleTest()
VerifyRecommendationsMissing(<MethodBody>Dim x = {|</MethodBody>, "Key")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub KeyNotAfterArrayInitializerCommaTest()
VerifyRecommendationsMissing(<MethodBody>Dim x = {0, |</MethodBody>, "Key")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub KeyNotAfterAsTest()
VerifyRecommendationsMissing(<MethodBody>Dim x As |</MethodBody>, "Key")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub KeyInAnonymousInitializer1Test()
VerifyRecommendationsContain(<MethodBody>Dim x As New With {|</MethodBody>, "Key")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub KeyInAnonymousInitializer2Test()
VerifyRecommendationsContain(<MethodBody>Dim x As New With {.Goo = 2, |</MethodBody>, "Key")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub KeyInAnonymousExpression1Test()
VerifyRecommendationsContain(<MethodBody>Dim x = New With {|</MethodBody>, "Key")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub KeyInAnonymousExpression2Test()
VerifyRecommendationsContain(<MethodBody>Dim x = New With {.Goo = 2, |</MethodBody>, "Key")
End Sub
''' <remark>Yes, "Onymous" is a word.</remark>
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub KeyNotInOnymousInitializerTest()
VerifyRecommendationsMissing(<MethodBody>Dim x As New Goo With {|</MethodBody>, "Key")
End Sub
''' <remark>Yes, "Onymous" is a word.</remark>
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub KeyNotInOnymousExpressionTest()
VerifyRecommendationsMissing(<MethodBody>Dim x = New Goo With {|</MethodBody>, "Key")
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.Expressions
Public Class KeyKeywordRecommenderTests
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub KeyNotInStatementTest()
VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "Key")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub KeyNotAfterArrayInitializerSquiggleTest()
VerifyRecommendationsMissing(<MethodBody>Dim x = {|</MethodBody>, "Key")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub KeyNotAfterArrayInitializerCommaTest()
VerifyRecommendationsMissing(<MethodBody>Dim x = {0, |</MethodBody>, "Key")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub KeyNotAfterAsTest()
VerifyRecommendationsMissing(<MethodBody>Dim x As |</MethodBody>, "Key")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub KeyInAnonymousInitializer1Test()
VerifyRecommendationsContain(<MethodBody>Dim x As New With {|</MethodBody>, "Key")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub KeyInAnonymousInitializer2Test()
VerifyRecommendationsContain(<MethodBody>Dim x As New With {.Goo = 2, |</MethodBody>, "Key")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub KeyInAnonymousExpression1Test()
VerifyRecommendationsContain(<MethodBody>Dim x = New With {|</MethodBody>, "Key")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub KeyInAnonymousExpression2Test()
VerifyRecommendationsContain(<MethodBody>Dim x = New With {.Goo = 2, |</MethodBody>, "Key")
End Sub
''' <remark>Yes, "Onymous" is a word.</remark>
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub KeyNotInOnymousInitializerTest()
VerifyRecommendationsMissing(<MethodBody>Dim x As New Goo With {|</MethodBody>, "Key")
End Sub
''' <remark>Yes, "Onymous" is a word.</remark>
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub KeyNotInOnymousExpressionTest()
VerifyRecommendationsMissing(<MethodBody>Dim x = New Goo With {|</MethodBody>, "Key")
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/VisualBasicTest/Recommendations/Statements/StopKeywordRecommenderTests.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.Statements
Public Class StopKeywordRecommenderTests
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub StopInMethodBodyTest()
VerifyRecommendationsContain(<MethodBody>|</MethodBody>, "Stop")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub StopAfterStatementTest()
VerifyRecommendationsContain(<MethodBody>
Dim x
|</MethodBody>, "Stop")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub StopMissingInClassBlockTest()
VerifyRecommendationsMissing(<ClassDeclaration>|</ClassDeclaration>, "Stop")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub StopInSingleLineLambdaTest()
VerifyRecommendationsContain(<MethodBody>Dim x = Sub() |</MethodBody>, "Stop")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub StopNotInSingleLineFunctionLambdaTest()
VerifyRecommendationsMissing(<MethodBody>Dim x = Function() |</MethodBody>, "Stop")
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.Statements
Public Class StopKeywordRecommenderTests
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub StopInMethodBodyTest()
VerifyRecommendationsContain(<MethodBody>|</MethodBody>, "Stop")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub StopAfterStatementTest()
VerifyRecommendationsContain(<MethodBody>
Dim x
|</MethodBody>, "Stop")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub StopMissingInClassBlockTest()
VerifyRecommendationsMissing(<ClassDeclaration>|</ClassDeclaration>, "Stop")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub StopInSingleLineLambdaTest()
VerifyRecommendationsContain(<MethodBody>Dim x = Sub() |</MethodBody>, "Stop")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub StopNotInSingleLineFunctionLambdaTest()
VerifyRecommendationsMissing(<MethodBody>Dim x = Function() |</MethodBody>, "Stop")
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.de.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="de" original="../BasicVSResources.resx">
<body>
<trans-unit id="Add_missing_imports_on_paste">
<source>Add missing imports on paste</source>
<target state="translated">Beim Einfügen fehlende import-Anweisungen hinzufügen</target>
<note>'import' is a Visual Basic keyword and should not be localized</note>
</trans-unit>
<trans-unit id="In_relational_binary_operators">
<source>In relational operators: = <> < > <= >= Like Is</source>
<target state="translated">In relationalen Operatoren: = <> < > <= >= Like Is</target>
<note />
</trans-unit>
<trans-unit id="Insert_apostrophe_at_the_start_of_new_lines_when_writing_apostrophe_comments">
<source>Insert ' at the start of new lines when writing ' comments</source>
<target state="translated">Fügen Sie beim Schreiben von '-Kommentaren ein Apostroph (') am Anfang der neuen Zeilen ein.</target>
<note />
</trans-unit>
<trans-unit id="Microsoft_Visual_Basic">
<source>Microsoft Visual Basic</source>
<target state="translated">Microsoft Visual Basic</target>
<note />
</trans-unit>
<trans-unit id="Insert_Snippet">
<source>Insert Snippet</source>
<target state="translated">Ausschnitt einfügen</target>
<note />
</trans-unit>
<trans-unit id="IntelliSense">
<source>IntelliSense</source>
<target state="translated">IntelliSense</target>
<note />
</trans-unit>
<trans-unit id="Automatic_insertion_of_Interface_and_MustOverride_members">
<source>Automatic _insertion of Interface and MustOverride members</source>
<target state="translated">Automatisches _Einfügen von Schnittstellen- und MustOverride-Membern</target>
<note />
</trans-unit>
<trans-unit id="Never">
<source>Never</source>
<target state="translated">Nie</target>
<note />
</trans-unit>
<trans-unit id="Prefer_IsNot_expression">
<source>Prefer 'IsNot' expression</source>
<target state="translated">Ausdruck "IsNot" bevorzugen</target>
<note />
</trans-unit>
<trans-unit id="Prefer_Is_Nothing_for_reference_equality_checks">
<source>Prefer 'Is Nothing' for reference equality checks</source>
<target state="translated">"Is Nothing" für Verweisübereinstimmungsprüfungen vorziehen</target>
<note />
</trans-unit>
<trans-unit id="Prefer_simplified_object_creation">
<source>Prefer simplified object creation</source>
<target state="translated">Vereinfachte Objekterstellung bevorzugen</target>
<note />
</trans-unit>
<trans-unit id="Remove_unnecessary_Imports">
<source>Remove unnecessary Imports</source>
<target state="translated">Unnötige Import-Direktiven entfernen</target>
<note>{Locked="Import"} 'import' is a Visual Basic keyword and should not be localized</note>
</trans-unit>
<trans-unit id="Show_hints_for_New_expressions">
<source>Show hints for 'New' expressions</source>
<target state="translated">Hinweise für new-Ausdrücke anzeigen</target>
<note />
</trans-unit>
<trans-unit id="Show_items_from_unimported_namespaces">
<source>Show items from unimported namespaces</source>
<target state="translated">Elemente aus nicht importierten Namespaces anzeigen</target>
<note />
</trans-unit>
<trans-unit id="Show_procedure_line_separators">
<source>_Show procedure line separators</source>
<target state="translated">_Zeilentrennzeichen in Prozeduren anzeigen</target>
<note />
</trans-unit>
<trans-unit id="Don_t_put_ByRef_on_custom_structure">
<source>_Don't put ByRef on custom structure</source>
<target state="translated">_ByRef nicht für benutzerdefinierte Struktur verwenden</target>
<note />
</trans-unit>
<trans-unit id="Editor_Help">
<source>Editor Help</source>
<target state="translated">Editor-Hilfe</target>
<note />
</trans-unit>
<trans-unit id="A_utomatic_insertion_of_end_constructs">
<source>A_utomatic insertion of end constructs</source>
<target state="translated">end-Konstrukte _automatisch einfügen</target>
<note />
</trans-unit>
<trans-unit id="Highlight_related_keywords_under_cursor">
<source>Highlight related _keywords under cursor</source>
<target state="translated">Verwandte _Schlüsselbegriffe unter Cursor anzeigen</target>
<note />
</trans-unit>
<trans-unit id="Highlight_references_to_symbol_under_cursor">
<source>_Highlight references to symbol under cursor</source>
<target state="translated">_Verweise auf Symbol unter Cursor hervorheben</target>
<note />
</trans-unit>
<trans-unit id="Pretty_listing_reformatting_of_code">
<source>_Pretty listing (reformatting) of code</source>
<target state="translated">_Automatische Strukturierung und Einrückung des Programmcodes</target>
<note />
</trans-unit>
<trans-unit id="Enter_outlining_mode_when_files_open">
<source>_Enter outlining mode when files open</source>
<target state="translated">_Gliederungsmodus beim Öffnen von Dateien starten</target>
<note />
</trans-unit>
<trans-unit id="Extract_Method">
<source>Extract Method</source>
<target state="translated">Methode extrahieren</target>
<note />
</trans-unit>
<trans-unit id="Generate_XML_documentation_comments_for">
<source>_Generate XML documentation comments for '''</source>
<target state="translated">_XML-Dokumentationskommentare generieren für '''</target>
<note>{Locked="'''"} "'''" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Highlighting">
<source>Highlighting</source>
<target state="translated">Hervorheben</target>
<note />
</trans-unit>
<trans-unit id="Optimize_for_solution_size">
<source>Optimize for solution size</source>
<target state="translated">Für Lösungsgröße optimieren</target>
<note />
</trans-unit>
<trans-unit id="Large">
<source>Large</source>
<target state="translated">Groß</target>
<note />
</trans-unit>
<trans-unit id="Regular">
<source>Regular</source>
<target state="translated">Regulär</target>
<note />
</trans-unit>
<trans-unit id="Show_remarks_in_Quick_Info">
<source>Show remarks in Quick Info</source>
<target state="translated">Hinweise in QuickInfo anzeigen</target>
<note />
</trans-unit>
<trans-unit id="Small">
<source>Small</source>
<target state="translated">Klein</target>
<note />
</trans-unit>
<trans-unit id="Performance">
<source>Performance</source>
<target state="translated">Leistung</target>
<note />
</trans-unit>
<trans-unit id="Show_preview_for_rename_tracking">
<source>Show preview for rename _tracking</source>
<target state="translated">Vorschau für Nachverfolgung beim _Umbenennen anzeigen</target>
<note />
</trans-unit>
<trans-unit id="Navigate_to_Object_Browser_for_symbols_defined_in_metadata">
<source>_Navigate to Object Browser for symbols defined in metadata</source>
<target state="translated">Für i_n Metadaten definierte Symbole zum Objektkatalog navigieren</target>
<note />
</trans-unit>
<trans-unit id="Go_to_Definition">
<source>Go to Definition</source>
<target state="translated">Gehe zu Definition</target>
<note />
</trans-unit>
<trans-unit id="Import_Directives">
<source>Import Directives</source>
<target state="translated">Import-Direktiven</target>
<note />
</trans-unit>
<trans-unit id="Sort_imports">
<source>Sort imports</source>
<target state="translated">Importe sortieren</target>
<note>{Locked="Import"} 'import' is a Visual Basic keyword and should not be localized</note>
</trans-unit>
<trans-unit id="Suggest_imports_for_types_in_NuGet_packages">
<source>Suggest imports for types in _NuGet packages</source>
<target state="translated">Import-Direktiven für Typen in _NuGet-Paketen vorschlagen</target>
<note />
</trans-unit>
<trans-unit id="Suggest_imports_for_types_in_reference_assemblies">
<source>Suggest imports for types in _reference assemblies</source>
<target state="translated">Import-Direktiven für Typen in _Verweisassemblys vorschlagen</target>
<note />
</trans-unit>
<trans-unit id="Place_System_directives_first_when_sorting_imports">
<source>_Place 'System' directives first when sorting imports</source>
<target state="translated">System-Anweisungen beim Sortieren von import-Anweisungen an erster Stelle _platzieren</target>
<note />
</trans-unit>
<trans-unit id="Qualify_event_access_with_Me">
<source>Qualify event access with 'Me'</source>
<target state="translated">Ereigniszugriff mit "Me" qualifizieren</target>
<note />
</trans-unit>
<trans-unit id="Qualify_field_access_with_Me">
<source>Qualify field access with 'Me'</source>
<target state="translated">Feldzugriff mit "Me" qualifizieren</target>
<note />
</trans-unit>
<trans-unit id="Qualify_method_access_with_Me">
<source>Qualify method access with 'Me'</source>
<target state="translated">Methodenzugriff mit "Me" qualifizieren</target>
<note />
</trans-unit>
<trans-unit id="Qualify_property_access_with_Me">
<source>Qualify property access with 'Me'</source>
<target state="translated">Eigenschaftenzugriff mit "Me" qualifizieren</target>
<note />
</trans-unit>
<trans-unit id="Do_not_prefer_Me">
<source>Do not prefer 'Me.'</source>
<target state="translated">"me" nicht bevorzugen</target>
<note />
</trans-unit>
<trans-unit id="Prefer_Me">
<source>Prefer 'Me.'</source>
<target state="translated">"me" bevorzugen</target>
<note />
</trans-unit>
<trans-unit id="Me_preferences_colon">
<source>'Me.' preferences:</source>
<target state="translated">'me.-Einstellungen:</target>
<note />
</trans-unit>
<trans-unit id="Predefined_type_preferences_colon">
<source>Predefined type preferences:</source>
<target state="translated">Vordefinierte Typeinstellungen:</target>
<note />
</trans-unit>
<trans-unit id="Highlight_matching_portions_of_completion_list_items">
<source>_Highlight matching portions of completion list items</source>
<target state="translated">_Übereinstimmende Teile der Vervollständigungslistenelemente anzeigen</target>
<note />
</trans-unit>
<trans-unit id="Show_completion_item_filters">
<source>Show completion item _filters</source>
<target state="translated">Vervollständigungselement_filter anzeigen</target>
<note />
</trans-unit>
<trans-unit id="Completion_Lists">
<source>Completion Lists</source>
<target state="translated">Vervollständigungslisten</target>
<note />
</trans-unit>
<trans-unit id="Enter_key_behavior_colon">
<source>Enter key behavior:</source>
<target state="translated">Verhalten der EINGABETASTE:</target>
<note />
</trans-unit>
<trans-unit id="Only_add_new_line_on_enter_after_end_of_fully_typed_word">
<source>_Only add new line on enter after end of fully typed word</source>
<target state="translated">Neue _Zeile beim Drücken der EINGABETASTE nur nach einem vollständig eingegebenen Wort einfügen</target>
<note />
</trans-unit>
<trans-unit id="Always_add_new_line_on_enter">
<source>_Always add new line on enter</source>
<target state="translated">_Immer neue Zeile beim Drücken der EINGABETASTE einfügen</target>
<note />
</trans-unit>
<trans-unit id="Never_add_new_line_on_enter">
<source>_Never add new line on enter</source>
<target state="translated">_Nie neue Zeile beim Drücken der EINGABETASTE einfügen</target>
<note />
</trans-unit>
<trans-unit id="Always_include_snippets">
<source>Always include snippets</source>
<target state="translated">Ausschnitte immer einschließen</target>
<note />
</trans-unit>
<trans-unit id="Include_snippets_when_Tab_is_typed_after_an_identifier">
<source>Include snippets when ?-Tab is typed after an identifier</source>
<target state="translated">Ausschnitte einschließen, wenn ?-TAB nach einem Bezeichner eingegeben wird</target>
<note />
</trans-unit>
<trans-unit id="Never_include_snippets">
<source>Never include snippets</source>
<target state="translated">Ausschnitte nie einschließen</target>
<note />
</trans-unit>
<trans-unit id="Snippets_behavior">
<source>Snippets behavior</source>
<target state="translated">Ausschnittverhalten</target>
<note />
</trans-unit>
<trans-unit id="Show_completion_list_after_a_character_is_deleted">
<source>Show completion list after a character is _deleted</source>
<target state="translated">Vervollstän_digungsliste nach Löschen eines Zeichens anzeigen</target>
<note />
</trans-unit>
<trans-unit id="Show_completion_list_after_a_character_is_typed">
<source>_Show completion list after a character is typed</source>
<target state="translated">_Vervollständigungsliste nach Eingabe eines Zeichens anzeigen</target>
<note />
</trans-unit>
<trans-unit id="Unused_local">
<source>Unused local</source>
<target state="translated">Nicht verwendete lokale Variable</target>
<note />
</trans-unit>
<trans-unit id="VB_Coding_Conventions">
<source>VB Coding Conventions</source>
<target state="translated">VB-Codierungskonvention</target>
<note />
</trans-unit>
<trans-unit id="nothing_checking_colon">
<source>'nothing' checking:</source>
<target state="translated">'Überprüfung auf "nothing":</target>
<note />
</trans-unit>
<trans-unit id="Fade_out_unused_imports">
<source>Fade out unused imports</source>
<target state="translated">Nicht verwendete Importe ausblenden</target>
<note />
</trans-unit>
<trans-unit id="Report_invalid_placeholders_in_string_dot_format_calls">
<source>Report invalid placeholders in 'String.Format' calls</source>
<target state="translated">Ungültige Platzhalter in String.Format-Aufrufen melden</target>
<note />
</trans-unit>
<trans-unit id="Separate_import_directive_groups">
<source>Separate import directive groups</source>
<target state="translated">Import-Anweisungsgruppen trennen</target>
<note />
</trans-unit>
<trans-unit id="In_arithmetic_binary_operators">
<source>In arithmetic operators: ^ * / \ Mod + - & << >></source>
<target state="translated">In arithmetischen Operatoren: ^ * / \ Mod + - & << >></target>
<note />
</trans-unit>
<trans-unit id="In_other_binary_operators">
<source>In other binary operators: And AndAlso Or OrElse</source>
<target state="translated">In anderen binären Operatoren: And AndAlso Or OrElse</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="de" original="../BasicVSResources.resx">
<body>
<trans-unit id="Add_missing_imports_on_paste">
<source>Add missing imports on paste</source>
<target state="translated">Beim Einfügen fehlende import-Anweisungen hinzufügen</target>
<note>'import' is a Visual Basic keyword and should not be localized</note>
</trans-unit>
<trans-unit id="In_relational_binary_operators">
<source>In relational operators: = <> < > <= >= Like Is</source>
<target state="translated">In relationalen Operatoren: = <> < > <= >= Like Is</target>
<note />
</trans-unit>
<trans-unit id="Insert_apostrophe_at_the_start_of_new_lines_when_writing_apostrophe_comments">
<source>Insert ' at the start of new lines when writing ' comments</source>
<target state="translated">Fügen Sie beim Schreiben von '-Kommentaren ein Apostroph (') am Anfang der neuen Zeilen ein.</target>
<note />
</trans-unit>
<trans-unit id="Microsoft_Visual_Basic">
<source>Microsoft Visual Basic</source>
<target state="translated">Microsoft Visual Basic</target>
<note />
</trans-unit>
<trans-unit id="Insert_Snippet">
<source>Insert Snippet</source>
<target state="translated">Ausschnitt einfügen</target>
<note />
</trans-unit>
<trans-unit id="IntelliSense">
<source>IntelliSense</source>
<target state="translated">IntelliSense</target>
<note />
</trans-unit>
<trans-unit id="Automatic_insertion_of_Interface_and_MustOverride_members">
<source>Automatic _insertion of Interface and MustOverride members</source>
<target state="translated">Automatisches _Einfügen von Schnittstellen- und MustOverride-Membern</target>
<note />
</trans-unit>
<trans-unit id="Never">
<source>Never</source>
<target state="translated">Nie</target>
<note />
</trans-unit>
<trans-unit id="Prefer_IsNot_expression">
<source>Prefer 'IsNot' expression</source>
<target state="translated">Ausdruck "IsNot" bevorzugen</target>
<note />
</trans-unit>
<trans-unit id="Prefer_Is_Nothing_for_reference_equality_checks">
<source>Prefer 'Is Nothing' for reference equality checks</source>
<target state="translated">"Is Nothing" für Verweisübereinstimmungsprüfungen vorziehen</target>
<note />
</trans-unit>
<trans-unit id="Prefer_simplified_object_creation">
<source>Prefer simplified object creation</source>
<target state="translated">Vereinfachte Objekterstellung bevorzugen</target>
<note />
</trans-unit>
<trans-unit id="Remove_unnecessary_Imports">
<source>Remove unnecessary Imports</source>
<target state="translated">Unnötige Import-Direktiven entfernen</target>
<note>{Locked="Import"} 'import' is a Visual Basic keyword and should not be localized</note>
</trans-unit>
<trans-unit id="Show_hints_for_New_expressions">
<source>Show hints for 'New' expressions</source>
<target state="translated">Hinweise für new-Ausdrücke anzeigen</target>
<note />
</trans-unit>
<trans-unit id="Show_items_from_unimported_namespaces">
<source>Show items from unimported namespaces</source>
<target state="translated">Elemente aus nicht importierten Namespaces anzeigen</target>
<note />
</trans-unit>
<trans-unit id="Show_procedure_line_separators">
<source>_Show procedure line separators</source>
<target state="translated">_Zeilentrennzeichen in Prozeduren anzeigen</target>
<note />
</trans-unit>
<trans-unit id="Don_t_put_ByRef_on_custom_structure">
<source>_Don't put ByRef on custom structure</source>
<target state="translated">_ByRef nicht für benutzerdefinierte Struktur verwenden</target>
<note />
</trans-unit>
<trans-unit id="Editor_Help">
<source>Editor Help</source>
<target state="translated">Editor-Hilfe</target>
<note />
</trans-unit>
<trans-unit id="A_utomatic_insertion_of_end_constructs">
<source>A_utomatic insertion of end constructs</source>
<target state="translated">end-Konstrukte _automatisch einfügen</target>
<note />
</trans-unit>
<trans-unit id="Highlight_related_keywords_under_cursor">
<source>Highlight related _keywords under cursor</source>
<target state="translated">Verwandte _Schlüsselbegriffe unter Cursor anzeigen</target>
<note />
</trans-unit>
<trans-unit id="Highlight_references_to_symbol_under_cursor">
<source>_Highlight references to symbol under cursor</source>
<target state="translated">_Verweise auf Symbol unter Cursor hervorheben</target>
<note />
</trans-unit>
<trans-unit id="Pretty_listing_reformatting_of_code">
<source>_Pretty listing (reformatting) of code</source>
<target state="translated">_Automatische Strukturierung und Einrückung des Programmcodes</target>
<note />
</trans-unit>
<trans-unit id="Enter_outlining_mode_when_files_open">
<source>_Enter outlining mode when files open</source>
<target state="translated">_Gliederungsmodus beim Öffnen von Dateien starten</target>
<note />
</trans-unit>
<trans-unit id="Extract_Method">
<source>Extract Method</source>
<target state="translated">Methode extrahieren</target>
<note />
</trans-unit>
<trans-unit id="Generate_XML_documentation_comments_for">
<source>_Generate XML documentation comments for '''</source>
<target state="translated">_XML-Dokumentationskommentare generieren für '''</target>
<note>{Locked="'''"} "'''" is a VB keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Highlighting">
<source>Highlighting</source>
<target state="translated">Hervorheben</target>
<note />
</trans-unit>
<trans-unit id="Optimize_for_solution_size">
<source>Optimize for solution size</source>
<target state="translated">Für Lösungsgröße optimieren</target>
<note />
</trans-unit>
<trans-unit id="Large">
<source>Large</source>
<target state="translated">Groß</target>
<note />
</trans-unit>
<trans-unit id="Regular">
<source>Regular</source>
<target state="translated">Regulär</target>
<note />
</trans-unit>
<trans-unit id="Show_remarks_in_Quick_Info">
<source>Show remarks in Quick Info</source>
<target state="translated">Hinweise in QuickInfo anzeigen</target>
<note />
</trans-unit>
<trans-unit id="Small">
<source>Small</source>
<target state="translated">Klein</target>
<note />
</trans-unit>
<trans-unit id="Performance">
<source>Performance</source>
<target state="translated">Leistung</target>
<note />
</trans-unit>
<trans-unit id="Show_preview_for_rename_tracking">
<source>Show preview for rename _tracking</source>
<target state="translated">Vorschau für Nachverfolgung beim _Umbenennen anzeigen</target>
<note />
</trans-unit>
<trans-unit id="Navigate_to_Object_Browser_for_symbols_defined_in_metadata">
<source>_Navigate to Object Browser for symbols defined in metadata</source>
<target state="translated">Für i_n Metadaten definierte Symbole zum Objektkatalog navigieren</target>
<note />
</trans-unit>
<trans-unit id="Go_to_Definition">
<source>Go to Definition</source>
<target state="translated">Gehe zu Definition</target>
<note />
</trans-unit>
<trans-unit id="Import_Directives">
<source>Import Directives</source>
<target state="translated">Import-Direktiven</target>
<note />
</trans-unit>
<trans-unit id="Sort_imports">
<source>Sort imports</source>
<target state="translated">Importe sortieren</target>
<note>{Locked="Import"} 'import' is a Visual Basic keyword and should not be localized</note>
</trans-unit>
<trans-unit id="Suggest_imports_for_types_in_NuGet_packages">
<source>Suggest imports for types in _NuGet packages</source>
<target state="translated">Import-Direktiven für Typen in _NuGet-Paketen vorschlagen</target>
<note />
</trans-unit>
<trans-unit id="Suggest_imports_for_types_in_reference_assemblies">
<source>Suggest imports for types in _reference assemblies</source>
<target state="translated">Import-Direktiven für Typen in _Verweisassemblys vorschlagen</target>
<note />
</trans-unit>
<trans-unit id="Place_System_directives_first_when_sorting_imports">
<source>_Place 'System' directives first when sorting imports</source>
<target state="translated">System-Anweisungen beim Sortieren von import-Anweisungen an erster Stelle _platzieren</target>
<note />
</trans-unit>
<trans-unit id="Qualify_event_access_with_Me">
<source>Qualify event access with 'Me'</source>
<target state="translated">Ereigniszugriff mit "Me" qualifizieren</target>
<note />
</trans-unit>
<trans-unit id="Qualify_field_access_with_Me">
<source>Qualify field access with 'Me'</source>
<target state="translated">Feldzugriff mit "Me" qualifizieren</target>
<note />
</trans-unit>
<trans-unit id="Qualify_method_access_with_Me">
<source>Qualify method access with 'Me'</source>
<target state="translated">Methodenzugriff mit "Me" qualifizieren</target>
<note />
</trans-unit>
<trans-unit id="Qualify_property_access_with_Me">
<source>Qualify property access with 'Me'</source>
<target state="translated">Eigenschaftenzugriff mit "Me" qualifizieren</target>
<note />
</trans-unit>
<trans-unit id="Do_not_prefer_Me">
<source>Do not prefer 'Me.'</source>
<target state="translated">"me" nicht bevorzugen</target>
<note />
</trans-unit>
<trans-unit id="Prefer_Me">
<source>Prefer 'Me.'</source>
<target state="translated">"me" bevorzugen</target>
<note />
</trans-unit>
<trans-unit id="Me_preferences_colon">
<source>'Me.' preferences:</source>
<target state="translated">'me.-Einstellungen:</target>
<note />
</trans-unit>
<trans-unit id="Predefined_type_preferences_colon">
<source>Predefined type preferences:</source>
<target state="translated">Vordefinierte Typeinstellungen:</target>
<note />
</trans-unit>
<trans-unit id="Highlight_matching_portions_of_completion_list_items">
<source>_Highlight matching portions of completion list items</source>
<target state="translated">_Übereinstimmende Teile der Vervollständigungslistenelemente anzeigen</target>
<note />
</trans-unit>
<trans-unit id="Show_completion_item_filters">
<source>Show completion item _filters</source>
<target state="translated">Vervollständigungselement_filter anzeigen</target>
<note />
</trans-unit>
<trans-unit id="Completion_Lists">
<source>Completion Lists</source>
<target state="translated">Vervollständigungslisten</target>
<note />
</trans-unit>
<trans-unit id="Enter_key_behavior_colon">
<source>Enter key behavior:</source>
<target state="translated">Verhalten der EINGABETASTE:</target>
<note />
</trans-unit>
<trans-unit id="Only_add_new_line_on_enter_after_end_of_fully_typed_word">
<source>_Only add new line on enter after end of fully typed word</source>
<target state="translated">Neue _Zeile beim Drücken der EINGABETASTE nur nach einem vollständig eingegebenen Wort einfügen</target>
<note />
</trans-unit>
<trans-unit id="Always_add_new_line_on_enter">
<source>_Always add new line on enter</source>
<target state="translated">_Immer neue Zeile beim Drücken der EINGABETASTE einfügen</target>
<note />
</trans-unit>
<trans-unit id="Never_add_new_line_on_enter">
<source>_Never add new line on enter</source>
<target state="translated">_Nie neue Zeile beim Drücken der EINGABETASTE einfügen</target>
<note />
</trans-unit>
<trans-unit id="Always_include_snippets">
<source>Always include snippets</source>
<target state="translated">Ausschnitte immer einschließen</target>
<note />
</trans-unit>
<trans-unit id="Include_snippets_when_Tab_is_typed_after_an_identifier">
<source>Include snippets when ?-Tab is typed after an identifier</source>
<target state="translated">Ausschnitte einschließen, wenn ?-TAB nach einem Bezeichner eingegeben wird</target>
<note />
</trans-unit>
<trans-unit id="Never_include_snippets">
<source>Never include snippets</source>
<target state="translated">Ausschnitte nie einschließen</target>
<note />
</trans-unit>
<trans-unit id="Snippets_behavior">
<source>Snippets behavior</source>
<target state="translated">Ausschnittverhalten</target>
<note />
</trans-unit>
<trans-unit id="Show_completion_list_after_a_character_is_deleted">
<source>Show completion list after a character is _deleted</source>
<target state="translated">Vervollstän_digungsliste nach Löschen eines Zeichens anzeigen</target>
<note />
</trans-unit>
<trans-unit id="Show_completion_list_after_a_character_is_typed">
<source>_Show completion list after a character is typed</source>
<target state="translated">_Vervollständigungsliste nach Eingabe eines Zeichens anzeigen</target>
<note />
</trans-unit>
<trans-unit id="Unused_local">
<source>Unused local</source>
<target state="translated">Nicht verwendete lokale Variable</target>
<note />
</trans-unit>
<trans-unit id="VB_Coding_Conventions">
<source>VB Coding Conventions</source>
<target state="translated">VB-Codierungskonvention</target>
<note />
</trans-unit>
<trans-unit id="nothing_checking_colon">
<source>'nothing' checking:</source>
<target state="translated">'Überprüfung auf "nothing":</target>
<note />
</trans-unit>
<trans-unit id="Fade_out_unused_imports">
<source>Fade out unused imports</source>
<target state="translated">Nicht verwendete Importe ausblenden</target>
<note />
</trans-unit>
<trans-unit id="Report_invalid_placeholders_in_string_dot_format_calls">
<source>Report invalid placeholders in 'String.Format' calls</source>
<target state="translated">Ungültige Platzhalter in String.Format-Aufrufen melden</target>
<note />
</trans-unit>
<trans-unit id="Separate_import_directive_groups">
<source>Separate import directive groups</source>
<target state="translated">Import-Anweisungsgruppen trennen</target>
<note />
</trans-unit>
<trans-unit id="In_arithmetic_binary_operators">
<source>In arithmetic operators: ^ * / \ Mod + - & << >></source>
<target state="translated">In arithmetischen Operatoren: ^ * / \ Mod + - & << >></target>
<note />
</trans-unit>
<trans-unit id="In_other_binary_operators">
<source>In other binary operators: And AndAlso Or OrElse</source>
<target state="translated">In anderen binären Operatoren: And AndAlso Or OrElse</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/Core/SymbolSearch/Patching/Delta.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.SymbolSearch.Patching
{
/// <summary>
/// Wrapper around the msdelta api so we can consume patches produced by the Elfie service.
/// Pinvokes and code provided by Dan Thompson
/// </summary>
internal static unsafe class Delta
{
[StructLayout(LayoutKind.Sequential)]
private struct DeltaInput
{
public byte* pBuf;
public IntPtr cbBuf; // SIZE_T, so different size on x86/x64
[MarshalAs(UnmanagedType.Bool)]
public bool editable;
public DeltaInput(byte* pBuf_, int cbBuf_, bool editable_) : this()
{
pBuf = pBuf_;
cbBuf = new IntPtr(cbBuf_);
editable = editable_;
}
public static DeltaInput Empty = new();
}
[StructLayout(LayoutKind.Sequential)]
private struct DeltaOutput
{
public IntPtr pBuf;
public IntPtr cbBuf; // SIZE_T, so different size on x86/x64
}
[Flags]
private enum DeltaApplyFlag : long
{
None = 0,
AllowPa19 = 0x00000001
}
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("msdelta.dll", SetLastError = true)]
private static extern bool ApplyDeltaB(
DeltaApplyFlag applyFlags,
DeltaInput source,
DeltaInput delta,
out DeltaOutput target);
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("msdelta.dll", SetLastError = true)]
private static extern bool DeltaFree(IntPtr memory);
public static unsafe byte[] ApplyPatch(byte[] sourceBytes, byte[] patchBytes)
{
fixed (byte* pSourceBuf = sourceBytes)
fixed (byte* pPatchBuf = patchBytes)
{
var ds = new DeltaInput(pSourceBuf, sourceBytes.Length, true);
var dp = new DeltaInput(pPatchBuf, patchBytes.Length, true);
if (!ApplyDeltaB(DeltaApplyFlag.None,
ds,
dp,
out var output))
{
throw new Win32Exception();
}
var targetBytes = new byte[output.cbBuf.ToInt32()];
Marshal.Copy(output.pBuf, targetBytes, 0, targetBytes.Length);
DeltaFree(output.pBuf);
return targetBytes;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.SymbolSearch.Patching
{
/// <summary>
/// Wrapper around the msdelta api so we can consume patches produced by the Elfie service.
/// Pinvokes and code provided by Dan Thompson
/// </summary>
internal static unsafe class Delta
{
[StructLayout(LayoutKind.Sequential)]
private struct DeltaInput
{
public byte* pBuf;
public IntPtr cbBuf; // SIZE_T, so different size on x86/x64
[MarshalAs(UnmanagedType.Bool)]
public bool editable;
public DeltaInput(byte* pBuf_, int cbBuf_, bool editable_) : this()
{
pBuf = pBuf_;
cbBuf = new IntPtr(cbBuf_);
editable = editable_;
}
public static DeltaInput Empty = new();
}
[StructLayout(LayoutKind.Sequential)]
private struct DeltaOutput
{
public IntPtr pBuf;
public IntPtr cbBuf; // SIZE_T, so different size on x86/x64
}
[Flags]
private enum DeltaApplyFlag : long
{
None = 0,
AllowPa19 = 0x00000001
}
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("msdelta.dll", SetLastError = true)]
private static extern bool ApplyDeltaB(
DeltaApplyFlag applyFlags,
DeltaInput source,
DeltaInput delta,
out DeltaOutput target);
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("msdelta.dll", SetLastError = true)]
private static extern bool DeltaFree(IntPtr memory);
public static unsafe byte[] ApplyPatch(byte[] sourceBytes, byte[] patchBytes)
{
fixed (byte* pSourceBuf = sourceBytes)
fixed (byte* pPatchBuf = patchBytes)
{
var ds = new DeltaInput(pSourceBuf, sourceBytes.Length, true);
var dp = new DeltaInput(pPatchBuf, patchBytes.Length, true);
if (!ApplyDeltaB(DeltaApplyFlag.None,
ds,
dp,
out var output))
{
throw new Win32Exception();
}
var targetBytes = new byte[output.cbBuf.ToInt32()];
Marshal.Copy(output.pBuf, targetBytes, 0, targetBytes.Length);
DeltaFree(output.pBuf);
return targetBytes;
}
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/CSharpTest2/Recommendations/ByteKeywordRecommenderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class ByteKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot()
{
await VerifyKeywordAsync(
@"$$", options: CSharp9ParseOptions);
}
[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()
{
await VerifyKeywordAsync(
@"System.Console.WriteLine();
$$", options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalVariableDeclaration()
{
await VerifyKeywordAsync(
@"int i = 0;
$$", options: CSharp9ParseOptions);
}
[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 TestAfterStackAlloc()
{
await VerifyKeywordAsync(
@"class C {
int* goo = stackalloc $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInFixedStatement(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"fixed ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDelegateReturnType()
{
await VerifyKeywordAsync(
@"public delegate $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInCastType(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"var str = (($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInCastType2(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"var str = (($$)items) as string;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstInMemberContext()
{
await VerifyKeywordAsync(
@"class C {
const $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefInMemberContext()
{
await VerifyKeywordAsync(
@"class C {
ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefReadonlyInMemberContext()
{
await VerifyKeywordAsync(
@"class C {
ref readonly $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterConstInStatementContext(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"const $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterRefInStatementContext(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterRefReadonlyInStatementContext(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref readonly $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterConstLocalDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"const $$ int local;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterRefLocalDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref $$ int local;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterRefReadonlyLocalDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref readonly $$ int local;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterRefLocalFunction(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref $$ int Function();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterRefReadonlyLocalFunction(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref readonly $$ int Function();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterRefExpression(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref int x = ref $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInEmptyStatement(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestEnumBaseTypes()
{
await VerifyKeywordAsync(
@"enum E : $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInGenericType1(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInGenericType2(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<int,$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInGenericType3(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<int[],$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInGenericType4(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<IGoo<int?,byte*>,$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInBaseList()
{
await VerifyAbsenceAsync(
@"class C : $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType_InBaseList()
{
await VerifyKeywordAsync(
@"class C : IList<$$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterIs(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"var v = goo is $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterAs(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"var v = goo as $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethod()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterField()
{
await VerifyKeywordAsync(
@"class C {
int i;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterProperty()
{
await VerifyKeywordAsync(
@"class C {
int i { get; }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task 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 TestNotAfterNestedPartial()
{
await VerifyAbsenceAsync(
@"class C {
partial $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAbstract()
{
await VerifyKeywordAsync(
@"class C {
abstract $$");
}
[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 TestAfterNestedStaticPublic()
{
await VerifyKeywordAsync(
@"class C {
static public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPublicStatic()
{
await VerifyKeywordAsync(
@"class C {
public static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterVirtualPublic()
{
await VerifyKeywordAsync(
@"class C {
virtual public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPublic()
{
await VerifyKeywordAsync(
@"class C {
public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPrivate()
{
await VerifyKeywordAsync(
@"class C {
private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedProtected()
{
await VerifyKeywordAsync(
@"class C {
protected $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedSealed()
{
await VerifyKeywordAsync(
@"class C {
sealed $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedStatic()
{
await VerifyKeywordAsync(
@"class C {
static $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInLocalVariableDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInForVariableDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"for ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInForeachVariableDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"foreach ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInUsingVariableDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"using ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInFromVariableDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInJoinVariableDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from a in b
join $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodOpenParen()
{
await VerifyKeywordAsync(
@"class C {
void Goo($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodComma()
{
await VerifyKeywordAsync(
@"class C {
void Goo(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodAttribute()
{
await VerifyKeywordAsync(
@"class C {
void Goo(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorOpenParen()
{
await VerifyKeywordAsync(
@"class C {
public C($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorComma()
{
await VerifyKeywordAsync(
@"class C {
public C(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorAttribute()
{
await VerifyKeywordAsync(
@"class C {
public C(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateOpenParen()
{
await VerifyKeywordAsync(
@"delegate void D($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateComma()
{
await VerifyKeywordAsync(
@"delegate void D(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateAttribute()
{
await VerifyKeywordAsync(
@"delegate void D(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterThis()
{
await VerifyKeywordAsync(
@"static class C {
public static void Goo(this $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRef()
{
await VerifyKeywordAsync(
@"class C {
void Goo(ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterOut()
{
await VerifyKeywordAsync(
@"class C {
void Goo(out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterLambdaRef()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
System.Func<int, int> f = (ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterLambdaOut()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
System.Func<int, int> f = (out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterParams()
{
await VerifyKeywordAsync(
@"class C {
void Goo(params $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInImplicitOperator()
{
await VerifyKeywordAsync(
@"class C {
public static implicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInExplicitOperator()
{
await VerifyKeywordAsync(
@"class C {
public static explicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerBracket()
{
await VerifyKeywordAsync(
@"class C {
int this[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerBracketComma()
{
await VerifyKeywordAsync(
@"class C {
int this[int i, $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterNewInExpression(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"new $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInTypeOf(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"typeof($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInDefault(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"default($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInSizeOf(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"sizeof($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInObjectInitializerMemberContext()
{
await VerifyAbsenceAsync(@"
class C
{
public int x, y;
void M()
{
var c = new C { x = 2, y = 3, $$");
}
[WorkItem(546938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCrefContext()
{
await VerifyKeywordAsync(@"
class Program
{
/// <see cref=""$$"">
static void Main(string[] args)
{
}
}");
}
[WorkItem(546955, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCrefContextNotAfterDot()
{
await VerifyAbsenceAsync(@"
/// <see cref=""System.$$"" />
class C { }
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAsync()
=> await VerifyKeywordAsync(@"class c { async $$ }");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAsyncAsType()
=> await VerifyAbsenceAsync(@"class c { async async $$ }");
[WorkItem(1468, "https://github.com/dotnet/roslyn/issues/1468")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInCrefTypeParameter()
{
await VerifyAbsenceAsync(@"
using System;
/// <see cref=""List{$$}"" />
class C { }
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task Preselection()
{
await VerifyKeywordAsync(@"
class Program
{
static void Main(string[] args)
{
Helper($$)
}
static void Helper(byte x) { }
}
");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInTupleWithinType()
{
await VerifyKeywordAsync(@"
class Program
{
($$
}");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInTupleWithinMember(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerType()
{
await VerifyKeywordAsync(@"
class C
{
delegate*<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerTypeAfterComma()
{
await VerifyKeywordAsync(@"
class C
{
delegate*<int, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerTypeAfterModifier()
{
await VerifyKeywordAsync(@"
class C
{
delegate*<ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterDelegateAsterisk()
{
await VerifyAbsenceAsync(@"
class C
{
delegate*$$");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class ByteKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot()
{
await VerifyKeywordAsync(
@"$$", options: CSharp9ParseOptions);
}
[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()
{
await VerifyKeywordAsync(
@"System.Console.WriteLine();
$$", options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalVariableDeclaration()
{
await VerifyKeywordAsync(
@"int i = 0;
$$", options: CSharp9ParseOptions);
}
[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 TestAfterStackAlloc()
{
await VerifyKeywordAsync(
@"class C {
int* goo = stackalloc $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInFixedStatement(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"fixed ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDelegateReturnType()
{
await VerifyKeywordAsync(
@"public delegate $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInCastType(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"var str = (($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInCastType2(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"var str = (($$)items) as string;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstInMemberContext()
{
await VerifyKeywordAsync(
@"class C {
const $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefInMemberContext()
{
await VerifyKeywordAsync(
@"class C {
ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefReadonlyInMemberContext()
{
await VerifyKeywordAsync(
@"class C {
ref readonly $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterConstInStatementContext(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"const $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterRefInStatementContext(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterRefReadonlyInStatementContext(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref readonly $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterConstLocalDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"const $$ int local;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterRefLocalDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref $$ int local;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterRefReadonlyLocalDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref readonly $$ int local;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterRefLocalFunction(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref $$ int Function();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterRefReadonlyLocalFunction(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref readonly $$ int Function();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterRefExpression(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref int x = ref $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInEmptyStatement(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestEnumBaseTypes()
{
await VerifyKeywordAsync(
@"enum E : $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInGenericType1(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInGenericType2(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<int,$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInGenericType3(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<int[],$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInGenericType4(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<IGoo<int?,byte*>,$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInBaseList()
{
await VerifyAbsenceAsync(
@"class C : $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType_InBaseList()
{
await VerifyKeywordAsync(
@"class C : IList<$$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterIs(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"var v = goo is $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterAs(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"var v = goo as $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethod()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterField()
{
await VerifyKeywordAsync(
@"class C {
int i;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterProperty()
{
await VerifyKeywordAsync(
@"class C {
int i { get; }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task 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 TestNotAfterNestedPartial()
{
await VerifyAbsenceAsync(
@"class C {
partial $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAbstract()
{
await VerifyKeywordAsync(
@"class C {
abstract $$");
}
[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 TestAfterNestedStaticPublic()
{
await VerifyKeywordAsync(
@"class C {
static public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPublicStatic()
{
await VerifyKeywordAsync(
@"class C {
public static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterVirtualPublic()
{
await VerifyKeywordAsync(
@"class C {
virtual public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPublic()
{
await VerifyKeywordAsync(
@"class C {
public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPrivate()
{
await VerifyKeywordAsync(
@"class C {
private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedProtected()
{
await VerifyKeywordAsync(
@"class C {
protected $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedSealed()
{
await VerifyKeywordAsync(
@"class C {
sealed $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedStatic()
{
await VerifyKeywordAsync(
@"class C {
static $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInLocalVariableDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInForVariableDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"for ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInForeachVariableDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"foreach ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInUsingVariableDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"using ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInFromVariableDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInJoinVariableDeclaration(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from a in b
join $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodOpenParen()
{
await VerifyKeywordAsync(
@"class C {
void Goo($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodComma()
{
await VerifyKeywordAsync(
@"class C {
void Goo(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodAttribute()
{
await VerifyKeywordAsync(
@"class C {
void Goo(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorOpenParen()
{
await VerifyKeywordAsync(
@"class C {
public C($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorComma()
{
await VerifyKeywordAsync(
@"class C {
public C(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorAttribute()
{
await VerifyKeywordAsync(
@"class C {
public C(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateOpenParen()
{
await VerifyKeywordAsync(
@"delegate void D($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateComma()
{
await VerifyKeywordAsync(
@"delegate void D(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateAttribute()
{
await VerifyKeywordAsync(
@"delegate void D(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterThis()
{
await VerifyKeywordAsync(
@"static class C {
public static void Goo(this $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRef()
{
await VerifyKeywordAsync(
@"class C {
void Goo(ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterOut()
{
await VerifyKeywordAsync(
@"class C {
void Goo(out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterLambdaRef()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
System.Func<int, int> f = (ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterLambdaOut()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
System.Func<int, int> f = (out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterParams()
{
await VerifyKeywordAsync(
@"class C {
void Goo(params $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInImplicitOperator()
{
await VerifyKeywordAsync(
@"class C {
public static implicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInExplicitOperator()
{
await VerifyKeywordAsync(
@"class C {
public static explicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerBracket()
{
await VerifyKeywordAsync(
@"class C {
int this[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerBracketComma()
{
await VerifyKeywordAsync(
@"class C {
int this[int i, $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestAfterNewInExpression(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"new $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInTypeOf(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"typeof($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInDefault(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"default($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInSizeOf(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"sizeof($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInObjectInitializerMemberContext()
{
await VerifyAbsenceAsync(@"
class C
{
public int x, y;
void M()
{
var c = new C { x = 2, y = 3, $$");
}
[WorkItem(546938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCrefContext()
{
await VerifyKeywordAsync(@"
class Program
{
/// <see cref=""$$"">
static void Main(string[] args)
{
}
}");
}
[WorkItem(546955, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCrefContextNotAfterDot()
{
await VerifyAbsenceAsync(@"
/// <see cref=""System.$$"" />
class C { }
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAsync()
=> await VerifyKeywordAsync(@"class c { async $$ }");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAsyncAsType()
=> await VerifyAbsenceAsync(@"class c { async async $$ }");
[WorkItem(1468, "https://github.com/dotnet/roslyn/issues/1468")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInCrefTypeParameter()
{
await VerifyAbsenceAsync(@"
using System;
/// <see cref=""List{$$}"" />
class C { }
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task Preselection()
{
await VerifyKeywordAsync(@"
class Program
{
static void Main(string[] args)
{
Helper($$)
}
static void Helper(byte x) { }
}
");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInTupleWithinType()
{
await VerifyKeywordAsync(@"
class Program
{
($$
}");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestInTupleWithinMember(bool topLevelStatement)
{
await VerifyKeywordAsync(AddInsideMethod(
@"($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerType()
{
await VerifyKeywordAsync(@"
class C
{
delegate*<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerTypeAfterComma()
{
await VerifyKeywordAsync(@"
class C
{
delegate*<int, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerTypeAfterModifier()
{
await VerifyKeywordAsync(@"
class C
{
delegate*<ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterDelegateAsterisk()
{
await VerifyAbsenceAsync(@"
class C
{
delegate*$$");
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./eng/Signing.props | <?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>
<PropertyGroup>
<UseDotNetCertificate>true</UseDotNetCertificate>
</PropertyGroup>
<!--
Non-default certificates.
-->
<ItemGroup>
<!-- Expression Compiler dependencies that run in remote debugger must be signed with Microsoft101240624 certificate in order to work on Windows 10S -->
<FileSignInfo Include="Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.dll" CertificateName="Microsoft101240624"/>
<FileSignInfo Include="Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ExpressionCompiler.dll" CertificateName="Microsoft101240624"/>
<FileSignInfo Include="Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ExpressionCompiler.dll" CertificateName="Microsoft101240624"/>
<FileSignInfo Include="Microsoft.CodeAnalysis.ExpressionEvaluator.ResultProvider.dll" PublicKeyToken="31bf3856ad364e35" TargetFramework=".NETStandard,Version=v1.3" CertificateName="Microsoft101240624"/>
<FileSignInfo Include="Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ResultProvider.dll" PublicKeyToken="31bf3856ad364e35" TargetFramework=".NETStandard,Version=v1.3" CertificateName="Microsoft101240624"/>
<FileSignInfo Include="Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ResultProvider.dll" PublicKeyToken="31bf3856ad364e35" TargetFramework=".NETStandard,Version=v1.3" CertificateName="Microsoft101240624"/>
<FileSignInfo Include="Microsoft.CodeAnalysis.ExpressionEvaluator.FunctionResolver.dll" PublicKeyToken="31bf3856ad364e35" TargetFramework=".NETStandard,Version=v1.3" CertificateName="Microsoft101240624"/>
<FileSignInfo Include="Microsoft.CodeAnalysis.ExpressionEvaluator.ResultProvider.dll" PublicKeyToken="31bf3856ad364e35" TargetFramework=".NETFramework,Version=v2.0" CertificateName="MicrosoftWin8WinBlue"/>
<FileSignInfo Include="Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ResultProvider.dll" PublicKeyToken="31bf3856ad364e35" TargetFramework=".NETFramework,Version=v2.0" CertificateName="MicrosoftWin8WinBlue"/>
<FileSignInfo Include="Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ResultProvider.dll" PublicKeyToken="31bf3856ad364e35" TargetFramework=".NETFramework,Version=v2.0" CertificateName="MicrosoftWin8WinBlue"/>
<FileSignInfo Include="Microsoft.CodeAnalysis.ExpressionEvaluator.FunctionResolver.dll" PublicKeyToken="31bf3856ad364e35" TargetFramework=".NETFramework,Version=v4.5" CertificateName="MicrosoftWin8WinBlue"/>
<FileSignInfo Include="System.Collections.Immutable.dll" CertificateName="Microsoft101240624"/>
<FileSignInfo Include="System.Reflection.Metadata.dll" CertificateName="Microsoft101240624"/>
<!-- Sign 3rd party dlls with 3rd party cert -->
<FileSignInfo Include="ICSharpCode.Decompiler.dll" CertificateName="3PartySHA2" />
<FileSignInfo Include="e_sqlite3.dll" CertificateName="3PartySHA2" />
<FileSignInfo Include="SQLitePCLRaw.core.dll" CertificateName="3PartySHA2" />
<FileSignInfo Include="SQLitePCLRaw.batteries_v2.dll" CertificateName="3PartySHA2" />
<FileSignInfo Include="SQLitePCLRaw.batteries_green.dll" CertificateName="3PartySHA2" />
<FileSignInfo Include="SQLitePCLRaw.nativelibrary.dll" CertificateName="3PartySHA2" />
<FileSignInfo Include="SQLitePCLRaw.provider.e_sqlite3.dll" CertificateName="3PartySHA2" />
<FileSignInfo Include="SQLitePCLRaw.provider.dynamic_cdecl.dll" CertificateName="3PartySHA2" />
<FileSignInfo Include="MessagePack.Annotations.dll" CertificateName="3PartySHA2" />
<FileSignInfo Include="MessagePack.dll" CertificateName="3PartySHA2" />
<FileSignInfo Include="Nerdbank.FullDuplexStream.dll" CertificateName="3PartySHA2" />
<FileSignInfo Include="Nerdbank.Streams.dll" CertificateName="3PartySHA2" />
<FileSignInfo Include="Newtonsoft.Json.dll" CertificateName="3PartySHA2" />
<FileSignInfo Include="Validation.dll" CertificateName="3PartySHA2" />
</ItemGroup>
</Project>
| <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project>
<PropertyGroup>
<UseDotNetCertificate>true</UseDotNetCertificate>
</PropertyGroup>
<!--
Non-default certificates.
-->
<ItemGroup>
<!-- Expression Compiler dependencies that run in remote debugger must be signed with Microsoft101240624 certificate in order to work on Windows 10S -->
<FileSignInfo Include="Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.dll" CertificateName="Microsoft101240624"/>
<FileSignInfo Include="Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ExpressionCompiler.dll" CertificateName="Microsoft101240624"/>
<FileSignInfo Include="Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ExpressionCompiler.dll" CertificateName="Microsoft101240624"/>
<FileSignInfo Include="Microsoft.CodeAnalysis.ExpressionEvaluator.ResultProvider.dll" PublicKeyToken="31bf3856ad364e35" TargetFramework=".NETStandard,Version=v1.3" CertificateName="Microsoft101240624"/>
<FileSignInfo Include="Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ResultProvider.dll" PublicKeyToken="31bf3856ad364e35" TargetFramework=".NETStandard,Version=v1.3" CertificateName="Microsoft101240624"/>
<FileSignInfo Include="Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ResultProvider.dll" PublicKeyToken="31bf3856ad364e35" TargetFramework=".NETStandard,Version=v1.3" CertificateName="Microsoft101240624"/>
<FileSignInfo Include="Microsoft.CodeAnalysis.ExpressionEvaluator.FunctionResolver.dll" PublicKeyToken="31bf3856ad364e35" TargetFramework=".NETStandard,Version=v1.3" CertificateName="Microsoft101240624"/>
<FileSignInfo Include="Microsoft.CodeAnalysis.ExpressionEvaluator.ResultProvider.dll" PublicKeyToken="31bf3856ad364e35" TargetFramework=".NETFramework,Version=v2.0" CertificateName="MicrosoftWin8WinBlue"/>
<FileSignInfo Include="Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ResultProvider.dll" PublicKeyToken="31bf3856ad364e35" TargetFramework=".NETFramework,Version=v2.0" CertificateName="MicrosoftWin8WinBlue"/>
<FileSignInfo Include="Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ResultProvider.dll" PublicKeyToken="31bf3856ad364e35" TargetFramework=".NETFramework,Version=v2.0" CertificateName="MicrosoftWin8WinBlue"/>
<FileSignInfo Include="Microsoft.CodeAnalysis.ExpressionEvaluator.FunctionResolver.dll" PublicKeyToken="31bf3856ad364e35" TargetFramework=".NETFramework,Version=v4.5" CertificateName="MicrosoftWin8WinBlue"/>
<FileSignInfo Include="System.Collections.Immutable.dll" CertificateName="Microsoft101240624"/>
<FileSignInfo Include="System.Reflection.Metadata.dll" CertificateName="Microsoft101240624"/>
<!-- Sign 3rd party dlls with 3rd party cert -->
<FileSignInfo Include="ICSharpCode.Decompiler.dll" CertificateName="3PartySHA2" />
<FileSignInfo Include="e_sqlite3.dll" CertificateName="3PartySHA2" />
<FileSignInfo Include="SQLitePCLRaw.core.dll" CertificateName="3PartySHA2" />
<FileSignInfo Include="SQLitePCLRaw.batteries_v2.dll" CertificateName="3PartySHA2" />
<FileSignInfo Include="SQLitePCLRaw.batteries_green.dll" CertificateName="3PartySHA2" />
<FileSignInfo Include="SQLitePCLRaw.nativelibrary.dll" CertificateName="3PartySHA2" />
<FileSignInfo Include="SQLitePCLRaw.provider.e_sqlite3.dll" CertificateName="3PartySHA2" />
<FileSignInfo Include="SQLitePCLRaw.provider.dynamic_cdecl.dll" CertificateName="3PartySHA2" />
<FileSignInfo Include="MessagePack.Annotations.dll" CertificateName="3PartySHA2" />
<FileSignInfo Include="MessagePack.dll" CertificateName="3PartySHA2" />
<FileSignInfo Include="Nerdbank.FullDuplexStream.dll" CertificateName="3PartySHA2" />
<FileSignInfo Include="Nerdbank.Streams.dll" CertificateName="3PartySHA2" />
<FileSignInfo Include="Newtonsoft.Json.dll" CertificateName="3PartySHA2" />
<FileSignInfo Include="Validation.dll" CertificateName="3PartySHA2" />
</ItemGroup>
</Project>
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/CSharpTest/Interactive/CodeActions/InteractiveIntroduceVariableTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.IntroduceVariable;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.IntroduceVariable
{
public class InteractiveIntroduceVariableTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new IntroduceVariableCodeRefactoringProvider();
protected override ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> actions)
=> GetNestedActions(actions);
protected Task TestAsync(string initial, string expected, int index = 0)
=> TestAsync(initial, expected, Options.Script, null, index);
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)]
public async Task TestMethodFix1()
{
await TestAsync(
@"void Goo()
{
Bar([|1 + 1|]);
Bar(1 + 1);
}",
@"void Goo()
{
const int {|Rename:V|} = 1 + 1;
Bar(V);
Bar(1 + 1);
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)]
public async Task TestMethodFix2()
{
await TestAsync(
@"void Goo()
{
Bar([|1 + 1|]);
Bar(1 + 1);
}",
@"void Goo()
{
const int {|Rename:V|} = 1 + 1;
Bar(V);
Bar(V);
}",
index: 3);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)]
public async Task TestFieldFix1()
{
var code =
@"int i = ([|1 + 1|]) + (1 + 1);";
var expected =
@"private const int {|Rename:V|} = 1 + 1;
int i = V + (1 + 1);";
await TestAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)]
public async Task TestFieldFix2()
{
var code =
@"int i = ([|1 + 1|]) + (1 + 1);";
var expected =
@"private const int {|Rename:V|} = 1 + 1;
int i = V + V;";
await TestAsync(code, expected, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)]
public async Task TestParameterFix1()
{
await TestAsync(
@"void Bar(int i = [|1 + 1|], int j = 1 + 1)
{
}",
@"private const int {|Rename:V|} = 1 + 1;
void Bar(int i = V, int j = 1 + 1)
{
}",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)]
public async Task TestParameterFix2()
{
await TestAsync(
@"void Bar(int i = [|1 + 1|], int j = 1 + 1)
{
}",
@"private const int {|Rename:V|} = 1 + 1;
void Bar(int i = V, int j = V)
{
}",
index: 1);
}
[Fact]
public async Task TestAttributeFix1()
{
await TestAsync(
@"[Goo([|1 + 1|], 1 + 1)]
void Bar()
{
}",
@"private const int {|Rename:V|} = 1 + 1;
[Goo(V, 1 + 1)]
void Bar()
{
}",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)]
public async Task TestAttributeFix2()
{
await TestAsync(
@"[Goo([|1 + 1|], 1 + 1)]
void Bar()
{
}",
@"private const int {|Rename:V|} = 1 + 1;
[Goo(V, V)]
void Bar()
{
}",
index: 1);
}
[WorkItem(541287, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541287")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)]
public async Task TestBlockFormatting()
{
await TestAsync(
@"using System;
class C
{
public static void Main()
{
for (int i = 0; i < 10; i++)
Console.WriteLine([|i+1|]);
}
}
",
@"using System;
class C
{
public static void Main()
{
for (int i = 0; i < 10; i++)
{
int {|Rename:value|} = i + 1;
Console.WriteLine(value);
}
}
}
",
index: 1);
}
[WorkItem(546465, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546465")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)]
public async Task TestPreserveTrivia()
{
await TestAsync(
@"class C
{
void M(params string[] args)
{
M(
""a"",
[|""b""|],
""c"");
}
}
",
@"class C
{
private const string {|Rename:V|} = ""b"";
void M(params string[] args)
{
M(
""a"",
V,
""c"");
}
}
");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.IntroduceVariable;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.IntroduceVariable
{
public class InteractiveIntroduceVariableTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new IntroduceVariableCodeRefactoringProvider();
protected override ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> actions)
=> GetNestedActions(actions);
protected Task TestAsync(string initial, string expected, int index = 0)
=> TestAsync(initial, expected, Options.Script, null, index);
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)]
public async Task TestMethodFix1()
{
await TestAsync(
@"void Goo()
{
Bar([|1 + 1|]);
Bar(1 + 1);
}",
@"void Goo()
{
const int {|Rename:V|} = 1 + 1;
Bar(V);
Bar(1 + 1);
}",
index: 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)]
public async Task TestMethodFix2()
{
await TestAsync(
@"void Goo()
{
Bar([|1 + 1|]);
Bar(1 + 1);
}",
@"void Goo()
{
const int {|Rename:V|} = 1 + 1;
Bar(V);
Bar(V);
}",
index: 3);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)]
public async Task TestFieldFix1()
{
var code =
@"int i = ([|1 + 1|]) + (1 + 1);";
var expected =
@"private const int {|Rename:V|} = 1 + 1;
int i = V + (1 + 1);";
await TestAsync(code, expected, index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)]
public async Task TestFieldFix2()
{
var code =
@"int i = ([|1 + 1|]) + (1 + 1);";
var expected =
@"private const int {|Rename:V|} = 1 + 1;
int i = V + V;";
await TestAsync(code, expected, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)]
public async Task TestParameterFix1()
{
await TestAsync(
@"void Bar(int i = [|1 + 1|], int j = 1 + 1)
{
}",
@"private const int {|Rename:V|} = 1 + 1;
void Bar(int i = V, int j = 1 + 1)
{
}",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)]
public async Task TestParameterFix2()
{
await TestAsync(
@"void Bar(int i = [|1 + 1|], int j = 1 + 1)
{
}",
@"private const int {|Rename:V|} = 1 + 1;
void Bar(int i = V, int j = V)
{
}",
index: 1);
}
[Fact]
public async Task TestAttributeFix1()
{
await TestAsync(
@"[Goo([|1 + 1|], 1 + 1)]
void Bar()
{
}",
@"private const int {|Rename:V|} = 1 + 1;
[Goo(V, 1 + 1)]
void Bar()
{
}",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)]
public async Task TestAttributeFix2()
{
await TestAsync(
@"[Goo([|1 + 1|], 1 + 1)]
void Bar()
{
}",
@"private const int {|Rename:V|} = 1 + 1;
[Goo(V, V)]
void Bar()
{
}",
index: 1);
}
[WorkItem(541287, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541287")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)]
public async Task TestBlockFormatting()
{
await TestAsync(
@"using System;
class C
{
public static void Main()
{
for (int i = 0; i < 10; i++)
Console.WriteLine([|i+1|]);
}
}
",
@"using System;
class C
{
public static void Main()
{
for (int i = 0; i < 10; i++)
{
int {|Rename:value|} = i + 1;
Console.WriteLine(value);
}
}
}
",
index: 1);
}
[WorkItem(546465, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546465")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)]
public async Task TestPreserveTrivia()
{
await TestAsync(
@"class C
{
void M(params string[] args)
{
M(
""a"",
[|""b""|],
""c"");
}
}
",
@"class C
{
private const string {|Rename:V|} = ""b"";
void M(params string[] args)
{
M(
""a"",
V,
""c"");
}
}
");
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/Core/Portable/TemporaryStorage/TemporaryStorageServiceFactory.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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 System.Diagnostics;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Host
{
[ExportWorkspaceServiceFactory(typeof(ITemporaryStorageService), ServiceLayer.Default), Shared]
internal partial class TemporaryStorageServiceFactory : IWorkspaceServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TemporaryStorageServiceFactory()
{
}
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
{
var textFactory = workspaceServices.GetRequiredService<ITextFactoryService>();
// MemoryMapped files which are used by the TemporaryStorageService are present in .NET Framework (including Mono)
// and .NET Core Windows. For non-Windows .NET Core scenarios, we can return the TrivialTemporaryStorageService
// until https://github.com/dotnet/runtime/issues/30878 is fixed.
return PlatformInformation.IsWindows || PlatformInformation.IsRunningOnMono
? (ITemporaryStorageService)new TemporaryStorageService(textFactory)
: TrivialTemporaryStorageService.Instance;
}
/// <summary>
/// Temporarily stores text and streams in memory mapped files.
/// </summary>
internal class TemporaryStorageService : ITemporaryStorageService2
{
/// <summary>
/// The maximum size in bytes of a single storage unit in a memory mapped file which is shared with other
/// storage units.
/// </summary>
/// <remarks>
/// <para>This value was arbitrarily chosen and appears to work well. Can be changed if data suggests
/// something better.</para>
/// </remarks>
/// <seealso cref="_weakFileReference"/>
private const long SingleFileThreshold = 128 * 1024;
/// <summary>
/// The size in bytes of a memory mapped file created to store multiple temporary objects.
/// </summary>
/// <remarks>
/// <para>This value was arbitrarily chosen and appears to work well. Can be changed if data suggests
/// something better.</para>
/// </remarks>
/// <seealso cref="_weakFileReference"/>
private const long MultiFileBlockSize = SingleFileThreshold * 32;
private readonly ITextFactoryService _textFactory;
/// <summary>
/// The synchronization object for accessing the memory mapped file related fields (indicated in the remarks
/// of each field).
/// </summary>
/// <remarks>
/// <para>PERF DEV NOTE: A concurrent (but complex) implementation of this type with identical semantics is
/// available in source control history. The use of exclusive locks was not causing any measurable
/// performance overhead even on 28-thread machines at the time this was written.</para>
/// </remarks>
private readonly object _gate = new();
/// <summary>
/// The most recent memory mapped file for creating multiple storage units. It will be used via bump-pointer
/// allocation until space is no longer available in it.
/// </summary>
/// <remarks>
/// <para>Access should be synchronized on <see cref="_gate"/>.</para>
/// </remarks>
private ReferenceCountedDisposable<MemoryMappedFile>.WeakReference _weakFileReference;
/// <summary>The name of the current memory mapped file for multiple storage units.</summary>
/// <remarks>
/// <para>Access should be synchronized on <see cref="_gate"/>.</para>
/// </remarks>
/// <seealso cref="_weakFileReference"/>
private string? _name;
/// <summary>The total size of the current memory mapped file for multiple storage units.</summary>
/// <remarks>
/// <para>Access should be synchronized on <see cref="_gate"/>.</para>
/// </remarks>
/// <seealso cref="_weakFileReference"/>
private long _fileSize;
/// <summary>
/// The offset into the current memory mapped file where the next storage unit can be held.
/// </summary>
/// <remarks>
/// <para>Access should be synchronized on <see cref="_gate"/>.</para>
/// </remarks>
/// <seealso cref="_weakFileReference"/>
private long _offset;
public TemporaryStorageService(ITextFactoryService textFactory)
=> _textFactory = textFactory;
public ITemporaryTextStorage CreateTemporaryTextStorage(CancellationToken cancellationToken)
=> new TemporaryTextStorage(this);
public ITemporaryTextStorage AttachTemporaryTextStorage(string storageName, long offset, long size, SourceHashAlgorithm checksumAlgorithm, Encoding? encoding, CancellationToken cancellationToken)
=> new TemporaryTextStorage(this, storageName, offset, size, checksumAlgorithm, encoding);
public ITemporaryStreamStorage CreateTemporaryStreamStorage(CancellationToken cancellationToken)
=> new TemporaryStreamStorage(this);
public ITemporaryStreamStorage AttachTemporaryStreamStorage(string storageName, long offset, long size, CancellationToken cancellationToken)
=> new TemporaryStreamStorage(this, storageName, offset, size);
/// <summary>
/// Allocate shared storage of a specified size.
/// </summary>
/// <remarks>
/// <para>"Small" requests are fulfilled from oversized memory mapped files which support several individual
/// storage units. Larger requests are allocated in their own memory mapped files.</para>
/// </remarks>
/// <param name="size">The size of the shared storage block to allocate.</param>
/// <returns>A <see cref="MemoryMappedInfo"/> describing the allocated block.</returns>
private MemoryMappedInfo CreateTemporaryStorage(long size)
{
if (size >= SingleFileThreshold)
{
// Larger blocks are allocated separately
var mapName = CreateUniqueName(size);
var storage = MemoryMappedFile.CreateNew(mapName, size);
return new MemoryMappedInfo(new ReferenceCountedDisposable<MemoryMappedFile>(storage), mapName, offset: 0, size: size);
}
lock (_gate)
{
// Obtain a reference to the memory mapped file, creating one if necessary. If a reference counted
// handle to a memory mapped file is obtained in this section, it must either be disposed before
// returning or returned to the caller who will own it through the MemoryMappedInfo.
var reference = _weakFileReference.TryAddReference();
if (reference == null || _offset + size > _fileSize)
{
var mapName = CreateUniqueName(MultiFileBlockSize);
var file = MemoryMappedFile.CreateNew(mapName, MultiFileBlockSize);
reference = new ReferenceCountedDisposable<MemoryMappedFile>(file);
_weakFileReference = new ReferenceCountedDisposable<MemoryMappedFile>.WeakReference(reference);
_name = mapName;
_fileSize = MultiFileBlockSize;
_offset = size;
return new MemoryMappedInfo(reference, _name, offset: 0, size: size);
}
else
{
// Reserve additional space in the existing storage location
Contract.ThrowIfNull(_name);
_offset += size;
return new MemoryMappedInfo(reference, _name, _offset - size, size);
}
}
}
public static string CreateUniqueName(long size)
=> "Roslyn Temp Storage " + size.ToString() + " " + Guid.NewGuid().ToString("N");
private sealed class TemporaryTextStorage : ITemporaryTextStorage, ITemporaryTextStorageWithName
{
private readonly TemporaryStorageService _service;
private SourceHashAlgorithm _checksumAlgorithm;
private Encoding? _encoding;
private ImmutableArray<byte> _checksum;
private MemoryMappedInfo? _memoryMappedInfo;
public TemporaryTextStorage(TemporaryStorageService service)
=> _service = service;
public TemporaryTextStorage(TemporaryStorageService service, string storageName, long offset, long size, SourceHashAlgorithm checksumAlgorithm, Encoding? encoding)
{
_service = service;
_checksumAlgorithm = checksumAlgorithm;
_encoding = encoding;
_memoryMappedInfo = new MemoryMappedInfo(storageName, offset, size);
}
// TODO: cleanup https://github.com/dotnet/roslyn/issues/43037
// Offet, Size not accessed if Name is null
public string? Name => _memoryMappedInfo?.Name;
public long Offset => _memoryMappedInfo!.Offset;
public long Size => _memoryMappedInfo!.Size;
public SourceHashAlgorithm ChecksumAlgorithm => _checksumAlgorithm;
public Encoding? Encoding => _encoding;
public ImmutableArray<byte> GetChecksum()
{
if (_checksum.IsDefault)
{
ImmutableInterlocked.InterlockedInitialize(ref _checksum, ReadText(CancellationToken.None).GetChecksum());
}
return _checksum;
}
public void Dispose()
{
// Destructors of SafeHandle and FileStream in MemoryMappedFile
// will eventually release resources if this Dispose is not called
// explicitly
_memoryMappedInfo?.Dispose();
_memoryMappedInfo = null;
_encoding = null;
}
public SourceText ReadText(CancellationToken cancellationToken)
{
if (_memoryMappedInfo == null)
{
throw new InvalidOperationException();
}
using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_ReadText, cancellationToken))
{
using var stream = _memoryMappedInfo.CreateReadableStream();
using var reader = CreateTextReaderFromTemporaryStorage((ISupportDirectMemoryAccess)stream, (int)stream.Length);
// we pass in encoding we got from original source text even if it is null.
return _service._textFactory.CreateText(reader, _encoding, cancellationToken);
}
}
public Task<SourceText> ReadTextAsync(CancellationToken cancellationToken)
{
// There is a reason for implementing it like this: proper async implementation
// that reads the underlying memory mapped file stream in an asynchronous fashion
// doesn't actually work. Windows doesn't offer
// any non-blocking way to read from a memory mapped file; the underlying memcpy
// may block as the memory pages back in and that's something you have to live
// with. Therefore, any implementation that attempts to use async will still
// always be blocking at least one threadpool thread in the memcpy in the case
// of a page fault. Therefore, if we're going to be blocking a thread, we should
// just block one thread and do the whole thing at once vs. a fake "async"
// implementation which will continue to requeue work back to the thread pool.
return Task.Factory.StartNew(() => ReadText(cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default);
}
public void WriteText(SourceText text, CancellationToken cancellationToken)
{
if (_memoryMappedInfo != null)
{
throw new InvalidOperationException();
}
using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_WriteText, cancellationToken))
{
_checksumAlgorithm = text.ChecksumAlgorithm;
_encoding = text.Encoding;
// the method we use to get text out of SourceText uses Unicode (2bytes per char).
var size = Encoding.Unicode.GetMaxByteCount(text.Length);
_memoryMappedInfo = _service.CreateTemporaryStorage(size);
// Write the source text out as Unicode. We expect that to be cheap.
using var stream = _memoryMappedInfo.CreateWritableStream();
using var writer = new StreamWriter(stream, Encoding.Unicode);
text.Write(writer, cancellationToken);
}
}
public Task WriteTextAsync(SourceText text, CancellationToken cancellationToken = default)
{
// See commentary in ReadTextAsync for why this is implemented this way.
return Task.Factory.StartNew(() => WriteText(text, cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default);
}
private static unsafe TextReader CreateTextReaderFromTemporaryStorage(ISupportDirectMemoryAccess accessor, int streamLength)
{
var src = (char*)accessor.GetPointer();
// BOM: Unicode, little endian
// Skip the BOM when creating the reader
Debug.Assert(*src == 0xFEFF);
return new DirectMemoryAccessStreamReader(src + 1, streamLength / sizeof(char) - 1);
}
}
private class TemporaryStreamStorage : ITemporaryStreamStorage, ITemporaryStorageWithName
{
private readonly TemporaryStorageService _service;
private MemoryMappedInfo? _memoryMappedInfo;
public TemporaryStreamStorage(TemporaryStorageService service)
=> _service = service;
public TemporaryStreamStorage(TemporaryStorageService service, string storageName, long offset, long size)
{
_service = service;
_memoryMappedInfo = new MemoryMappedInfo(storageName, offset, size);
}
// TODO: clean up https://github.com/dotnet/roslyn/issues/43037
// Offset, Size is only used when Name is not null.
public string? Name => _memoryMappedInfo?.Name;
public long Offset => _memoryMappedInfo!.Offset;
public long Size => _memoryMappedInfo!.Size;
public void Dispose()
{
// Destructors of SafeHandle and FileStream in MemoryMappedFile
// will eventually release resources if this Dispose is not called
// explicitly
_memoryMappedInfo?.Dispose();
_memoryMappedInfo = null;
}
public Stream ReadStream(CancellationToken cancellationToken)
{
if (_memoryMappedInfo == null)
{
throw new InvalidOperationException();
}
using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_ReadStream, cancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
return _memoryMappedInfo.CreateReadableStream();
}
}
public Task<Stream> ReadStreamAsync(CancellationToken cancellationToken = default)
{
// See commentary in ReadTextAsync for why this is implemented this way.
return Task.Factory.StartNew(() => ReadStream(cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default);
}
public void WriteStream(Stream stream, CancellationToken cancellationToken = default)
{
// The Wait() here will not actually block, since with useAsync: false, the
// entire operation will already be done when WaitStreamMaybeAsync completes.
WriteStreamMaybeAsync(stream, useAsync: false, cancellationToken: cancellationToken).GetAwaiter().GetResult();
}
public Task WriteStreamAsync(Stream stream, CancellationToken cancellationToken = default)
=> WriteStreamMaybeAsync(stream, useAsync: true, cancellationToken: cancellationToken);
private async Task WriteStreamMaybeAsync(Stream stream, bool useAsync, CancellationToken cancellationToken)
{
if (_memoryMappedInfo != null)
{
throw new InvalidOperationException(WorkspacesResources.Temporary_storage_cannot_be_written_more_than_once);
}
using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_WriteStream, cancellationToken))
{
var size = stream.Length;
_memoryMappedInfo = _service.CreateTemporaryStorage(size);
using var viewStream = _memoryMappedInfo.CreateWritableStream();
var buffer = SharedPools.ByteArray.Allocate();
try
{
while (true)
{
int count;
if (useAsync)
{
count = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false);
}
else
{
count = stream.Read(buffer, 0, buffer.Length);
}
if (count == 0)
{
break;
}
viewStream.Write(buffer, 0, count);
}
}
finally
{
SharedPools.ByteArray.Free(buffer);
}
}
}
}
}
internal unsafe class DirectMemoryAccessStreamReader : TextReaderWithLength
{
private char* _position;
private readonly char* _end;
public DirectMemoryAccessStreamReader(char* src, int length)
: base(length)
{
RoslynDebug.Assert(src != null);
RoslynDebug.Assert(length >= 0);
_position = src;
_end = _position + length;
}
public override int Peek()
{
if (_position >= _end)
{
return -1;
}
return *_position;
}
public override int Read()
{
if (_position >= _end)
{
return -1;
}
return *_position++;
}
public override int Read(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (index < 0 || index >= buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
if (count < 0 || (index + count) > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
count = Math.Min(count, (int)(_end - _position));
if (count > 0)
{
Marshal.Copy((IntPtr)_position, buffer, index, count);
_position += count;
}
return count;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Host
{
[ExportWorkspaceServiceFactory(typeof(ITemporaryStorageService), ServiceLayer.Default), Shared]
internal partial class TemporaryStorageServiceFactory : IWorkspaceServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TemporaryStorageServiceFactory()
{
}
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
{
var textFactory = workspaceServices.GetRequiredService<ITextFactoryService>();
// MemoryMapped files which are used by the TemporaryStorageService are present in .NET Framework (including Mono)
// and .NET Core Windows. For non-Windows .NET Core scenarios, we can return the TrivialTemporaryStorageService
// until https://github.com/dotnet/runtime/issues/30878 is fixed.
return PlatformInformation.IsWindows || PlatformInformation.IsRunningOnMono
? (ITemporaryStorageService)new TemporaryStorageService(textFactory)
: TrivialTemporaryStorageService.Instance;
}
/// <summary>
/// Temporarily stores text and streams in memory mapped files.
/// </summary>
internal class TemporaryStorageService : ITemporaryStorageService2
{
/// <summary>
/// The maximum size in bytes of a single storage unit in a memory mapped file which is shared with other
/// storage units.
/// </summary>
/// <remarks>
/// <para>This value was arbitrarily chosen and appears to work well. Can be changed if data suggests
/// something better.</para>
/// </remarks>
/// <seealso cref="_weakFileReference"/>
private const long SingleFileThreshold = 128 * 1024;
/// <summary>
/// The size in bytes of a memory mapped file created to store multiple temporary objects.
/// </summary>
/// <remarks>
/// <para>This value was arbitrarily chosen and appears to work well. Can be changed if data suggests
/// something better.</para>
/// </remarks>
/// <seealso cref="_weakFileReference"/>
private const long MultiFileBlockSize = SingleFileThreshold * 32;
private readonly ITextFactoryService _textFactory;
/// <summary>
/// The synchronization object for accessing the memory mapped file related fields (indicated in the remarks
/// of each field).
/// </summary>
/// <remarks>
/// <para>PERF DEV NOTE: A concurrent (but complex) implementation of this type with identical semantics is
/// available in source control history. The use of exclusive locks was not causing any measurable
/// performance overhead even on 28-thread machines at the time this was written.</para>
/// </remarks>
private readonly object _gate = new();
/// <summary>
/// The most recent memory mapped file for creating multiple storage units. It will be used via bump-pointer
/// allocation until space is no longer available in it.
/// </summary>
/// <remarks>
/// <para>Access should be synchronized on <see cref="_gate"/>.</para>
/// </remarks>
private ReferenceCountedDisposable<MemoryMappedFile>.WeakReference _weakFileReference;
/// <summary>The name of the current memory mapped file for multiple storage units.</summary>
/// <remarks>
/// <para>Access should be synchronized on <see cref="_gate"/>.</para>
/// </remarks>
/// <seealso cref="_weakFileReference"/>
private string? _name;
/// <summary>The total size of the current memory mapped file for multiple storage units.</summary>
/// <remarks>
/// <para>Access should be synchronized on <see cref="_gate"/>.</para>
/// </remarks>
/// <seealso cref="_weakFileReference"/>
private long _fileSize;
/// <summary>
/// The offset into the current memory mapped file where the next storage unit can be held.
/// </summary>
/// <remarks>
/// <para>Access should be synchronized on <see cref="_gate"/>.</para>
/// </remarks>
/// <seealso cref="_weakFileReference"/>
private long _offset;
public TemporaryStorageService(ITextFactoryService textFactory)
=> _textFactory = textFactory;
public ITemporaryTextStorage CreateTemporaryTextStorage(CancellationToken cancellationToken)
=> new TemporaryTextStorage(this);
public ITemporaryTextStorage AttachTemporaryTextStorage(string storageName, long offset, long size, SourceHashAlgorithm checksumAlgorithm, Encoding? encoding, CancellationToken cancellationToken)
=> new TemporaryTextStorage(this, storageName, offset, size, checksumAlgorithm, encoding);
public ITemporaryStreamStorage CreateTemporaryStreamStorage(CancellationToken cancellationToken)
=> new TemporaryStreamStorage(this);
public ITemporaryStreamStorage AttachTemporaryStreamStorage(string storageName, long offset, long size, CancellationToken cancellationToken)
=> new TemporaryStreamStorage(this, storageName, offset, size);
/// <summary>
/// Allocate shared storage of a specified size.
/// </summary>
/// <remarks>
/// <para>"Small" requests are fulfilled from oversized memory mapped files which support several individual
/// storage units. Larger requests are allocated in their own memory mapped files.</para>
/// </remarks>
/// <param name="size">The size of the shared storage block to allocate.</param>
/// <returns>A <see cref="MemoryMappedInfo"/> describing the allocated block.</returns>
private MemoryMappedInfo CreateTemporaryStorage(long size)
{
if (size >= SingleFileThreshold)
{
// Larger blocks are allocated separately
var mapName = CreateUniqueName(size);
var storage = MemoryMappedFile.CreateNew(mapName, size);
return new MemoryMappedInfo(new ReferenceCountedDisposable<MemoryMappedFile>(storage), mapName, offset: 0, size: size);
}
lock (_gate)
{
// Obtain a reference to the memory mapped file, creating one if necessary. If a reference counted
// handle to a memory mapped file is obtained in this section, it must either be disposed before
// returning or returned to the caller who will own it through the MemoryMappedInfo.
var reference = _weakFileReference.TryAddReference();
if (reference == null || _offset + size > _fileSize)
{
var mapName = CreateUniqueName(MultiFileBlockSize);
var file = MemoryMappedFile.CreateNew(mapName, MultiFileBlockSize);
reference = new ReferenceCountedDisposable<MemoryMappedFile>(file);
_weakFileReference = new ReferenceCountedDisposable<MemoryMappedFile>.WeakReference(reference);
_name = mapName;
_fileSize = MultiFileBlockSize;
_offset = size;
return new MemoryMappedInfo(reference, _name, offset: 0, size: size);
}
else
{
// Reserve additional space in the existing storage location
Contract.ThrowIfNull(_name);
_offset += size;
return new MemoryMappedInfo(reference, _name, _offset - size, size);
}
}
}
public static string CreateUniqueName(long size)
=> "Roslyn Temp Storage " + size.ToString() + " " + Guid.NewGuid().ToString("N");
private sealed class TemporaryTextStorage : ITemporaryTextStorage, ITemporaryTextStorageWithName
{
private readonly TemporaryStorageService _service;
private SourceHashAlgorithm _checksumAlgorithm;
private Encoding? _encoding;
private ImmutableArray<byte> _checksum;
private MemoryMappedInfo? _memoryMappedInfo;
public TemporaryTextStorage(TemporaryStorageService service)
=> _service = service;
public TemporaryTextStorage(TemporaryStorageService service, string storageName, long offset, long size, SourceHashAlgorithm checksumAlgorithm, Encoding? encoding)
{
_service = service;
_checksumAlgorithm = checksumAlgorithm;
_encoding = encoding;
_memoryMappedInfo = new MemoryMappedInfo(storageName, offset, size);
}
// TODO: cleanup https://github.com/dotnet/roslyn/issues/43037
// Offet, Size not accessed if Name is null
public string? Name => _memoryMappedInfo?.Name;
public long Offset => _memoryMappedInfo!.Offset;
public long Size => _memoryMappedInfo!.Size;
public SourceHashAlgorithm ChecksumAlgorithm => _checksumAlgorithm;
public Encoding? Encoding => _encoding;
public ImmutableArray<byte> GetChecksum()
{
if (_checksum.IsDefault)
{
ImmutableInterlocked.InterlockedInitialize(ref _checksum, ReadText(CancellationToken.None).GetChecksum());
}
return _checksum;
}
public void Dispose()
{
// Destructors of SafeHandle and FileStream in MemoryMappedFile
// will eventually release resources if this Dispose is not called
// explicitly
_memoryMappedInfo?.Dispose();
_memoryMappedInfo = null;
_encoding = null;
}
public SourceText ReadText(CancellationToken cancellationToken)
{
if (_memoryMappedInfo == null)
{
throw new InvalidOperationException();
}
using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_ReadText, cancellationToken))
{
using var stream = _memoryMappedInfo.CreateReadableStream();
using var reader = CreateTextReaderFromTemporaryStorage((ISupportDirectMemoryAccess)stream, (int)stream.Length);
// we pass in encoding we got from original source text even if it is null.
return _service._textFactory.CreateText(reader, _encoding, cancellationToken);
}
}
public Task<SourceText> ReadTextAsync(CancellationToken cancellationToken)
{
// There is a reason for implementing it like this: proper async implementation
// that reads the underlying memory mapped file stream in an asynchronous fashion
// doesn't actually work. Windows doesn't offer
// any non-blocking way to read from a memory mapped file; the underlying memcpy
// may block as the memory pages back in and that's something you have to live
// with. Therefore, any implementation that attempts to use async will still
// always be blocking at least one threadpool thread in the memcpy in the case
// of a page fault. Therefore, if we're going to be blocking a thread, we should
// just block one thread and do the whole thing at once vs. a fake "async"
// implementation which will continue to requeue work back to the thread pool.
return Task.Factory.StartNew(() => ReadText(cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default);
}
public void WriteText(SourceText text, CancellationToken cancellationToken)
{
if (_memoryMappedInfo != null)
{
throw new InvalidOperationException();
}
using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_WriteText, cancellationToken))
{
_checksumAlgorithm = text.ChecksumAlgorithm;
_encoding = text.Encoding;
// the method we use to get text out of SourceText uses Unicode (2bytes per char).
var size = Encoding.Unicode.GetMaxByteCount(text.Length);
_memoryMappedInfo = _service.CreateTemporaryStorage(size);
// Write the source text out as Unicode. We expect that to be cheap.
using var stream = _memoryMappedInfo.CreateWritableStream();
using var writer = new StreamWriter(stream, Encoding.Unicode);
text.Write(writer, cancellationToken);
}
}
public Task WriteTextAsync(SourceText text, CancellationToken cancellationToken = default)
{
// See commentary in ReadTextAsync for why this is implemented this way.
return Task.Factory.StartNew(() => WriteText(text, cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default);
}
private static unsafe TextReader CreateTextReaderFromTemporaryStorage(ISupportDirectMemoryAccess accessor, int streamLength)
{
var src = (char*)accessor.GetPointer();
// BOM: Unicode, little endian
// Skip the BOM when creating the reader
Debug.Assert(*src == 0xFEFF);
return new DirectMemoryAccessStreamReader(src + 1, streamLength / sizeof(char) - 1);
}
}
private class TemporaryStreamStorage : ITemporaryStreamStorage, ITemporaryStorageWithName
{
private readonly TemporaryStorageService _service;
private MemoryMappedInfo? _memoryMappedInfo;
public TemporaryStreamStorage(TemporaryStorageService service)
=> _service = service;
public TemporaryStreamStorage(TemporaryStorageService service, string storageName, long offset, long size)
{
_service = service;
_memoryMappedInfo = new MemoryMappedInfo(storageName, offset, size);
}
// TODO: clean up https://github.com/dotnet/roslyn/issues/43037
// Offset, Size is only used when Name is not null.
public string? Name => _memoryMappedInfo?.Name;
public long Offset => _memoryMappedInfo!.Offset;
public long Size => _memoryMappedInfo!.Size;
public void Dispose()
{
// Destructors of SafeHandle and FileStream in MemoryMappedFile
// will eventually release resources if this Dispose is not called
// explicitly
_memoryMappedInfo?.Dispose();
_memoryMappedInfo = null;
}
public Stream ReadStream(CancellationToken cancellationToken)
{
if (_memoryMappedInfo == null)
{
throw new InvalidOperationException();
}
using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_ReadStream, cancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
return _memoryMappedInfo.CreateReadableStream();
}
}
public Task<Stream> ReadStreamAsync(CancellationToken cancellationToken = default)
{
// See commentary in ReadTextAsync for why this is implemented this way.
return Task.Factory.StartNew(() => ReadStream(cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default);
}
public void WriteStream(Stream stream, CancellationToken cancellationToken = default)
{
// The Wait() here will not actually block, since with useAsync: false, the
// entire operation will already be done when WaitStreamMaybeAsync completes.
WriteStreamMaybeAsync(stream, useAsync: false, cancellationToken: cancellationToken).GetAwaiter().GetResult();
}
public Task WriteStreamAsync(Stream stream, CancellationToken cancellationToken = default)
=> WriteStreamMaybeAsync(stream, useAsync: true, cancellationToken: cancellationToken);
private async Task WriteStreamMaybeAsync(Stream stream, bool useAsync, CancellationToken cancellationToken)
{
if (_memoryMappedInfo != null)
{
throw new InvalidOperationException(WorkspacesResources.Temporary_storage_cannot_be_written_more_than_once);
}
using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_WriteStream, cancellationToken))
{
var size = stream.Length;
_memoryMappedInfo = _service.CreateTemporaryStorage(size);
using var viewStream = _memoryMappedInfo.CreateWritableStream();
var buffer = SharedPools.ByteArray.Allocate();
try
{
while (true)
{
int count;
if (useAsync)
{
count = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false);
}
else
{
count = stream.Read(buffer, 0, buffer.Length);
}
if (count == 0)
{
break;
}
viewStream.Write(buffer, 0, count);
}
}
finally
{
SharedPools.ByteArray.Free(buffer);
}
}
}
}
}
internal unsafe class DirectMemoryAccessStreamReader : TextReaderWithLength
{
private char* _position;
private readonly char* _end;
public DirectMemoryAccessStreamReader(char* src, int length)
: base(length)
{
RoslynDebug.Assert(src != null);
RoslynDebug.Assert(length >= 0);
_position = src;
_end = _position + length;
}
public override int Peek()
{
if (_position >= _end)
{
return -1;
}
return *_position;
}
public override int Read()
{
if (_position >= _end)
{
return -1;
}
return *_position++;
}
public override int Read(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (index < 0 || index >= buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
if (count < 0 || (index + count) > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
count = Math.Min(count, (int)(_end - _position));
if (count > 0)
{
Marshal.Copy((IntPtr)_position, buffer, index, count);
_position += count;
}
return count;
}
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Analyzers/CSharp/Tests/UseDeconstruction/UseDeconstructionTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.UseDeconstruction;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseDeconstruction
{
public class UseDeconstructionTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
public UseDeconstructionTests(ITestOutputHelper logger)
: base(logger)
{
}
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new CSharpUseDeconstructionDiagnosticAnalyzer(), new CSharpUseDeconstructionCodeFixProvider());
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestVar()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
var [|t1|] = GetPerson();
}
(string name, int age) GetPerson() => default;
}",
@"class C
{
void M()
{
var (name, age) = GetPerson();
}
(string name, int age) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestNotIfNameInInnerScope()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
var [|t1|] = GetPerson();
{
int age;
}
}
(string name, int age) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestNotIfNameInOuterScope()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
int age;
void M()
{
var [|t1|] = GetPerson();
}
(string name, int age) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestUpdateReference()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
var [|t1|] = GetPerson();
Console.WriteLine(t1.name + "" "" + t1.age);
}
(string name, int age) GetPerson() => default;
}",
@"class C
{
void M()
{
var (name, age) = GetPerson();
Console.WriteLine(name + "" "" + age);
}
(string name, int age) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestTupleType()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
(int name, int age) [|t1|] = GetPerson();
Console.WriteLine(t1.name + "" "" + t1.age);
}
(string name, int age) GetPerson() => default;
}",
@"class C
{
void M()
{
(int name, int age) = GetPerson();
Console.WriteLine(name + "" "" + age);
}
(string name, int age) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestVarInForEach()
{
await TestInRegularAndScript1Async(
@"using System.Collections.Generic;
class C
{
void M()
{
foreach (var [|t1|] in GetPeople())
Console.WriteLine(t1.name + "" "" + t1.age);
}
IEnumerable<(string name, int age)> GetPeople() => default;
}",
@"using System.Collections.Generic;
class C
{
void M()
{
foreach (var (name, age) in GetPeople())
Console.WriteLine(name + "" "" + age);
}
IEnumerable<(string name, int age)> GetPeople() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestTupleTypeInForEach()
{
await TestInRegularAndScript1Async(
@"using System.Collections.Generic;
class C
{
void M()
{
foreach ((string name, int age) [|t1|] in GetPeople())
Console.WriteLine(t1.name + "" "" + t1.age);
}
IEnumerable<(string name, int age)> GetPeople() => default;
}",
@"using System.Collections.Generic;
class C
{
void M()
{
foreach ((string name, int age) in GetPeople())
Console.WriteLine(name + "" "" + age);
}
IEnumerable<(string name, int age)> GetPeople() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestFixAll1()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
var {|FixAllInDocument:t1|} = GetPerson();
var t2 = GetPerson();
}
(string name, int age) GetPerson() => default;
}",
@"class C
{
void M()
{
var (name, age) = GetPerson();
var t2 = GetPerson();
}
(string name, int age) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestFixAll2()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
var {|FixAllInDocument:t1|} = GetPerson();
}
void M2()
{
var t2 = GetPerson();
}
(string name, int age) GetPerson() => default;
}",
@"class C
{
void M()
{
var (name, age) = GetPerson();
}
void M2()
{
var (name, age) = GetPerson();
}
(string name, int age) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestFixAll3()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
(string name1, int age1) {|FixAllInDocument:t1|} = GetPerson();
(string name2, int age2) t2 = GetPerson();
}
(string name, int age) GetPerson() => default;
}",
@"class C
{
void M()
{
(string name1, int age1) = GetPerson();
(string name2, int age2) = GetPerson();
}
(string name, int age) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestFixAll4()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
(string name, int age) {|FixAllInDocument:t1|} = GetPerson();
(string name, int age) t2 = GetPerson();
}
(string name, int age) GetPerson() => default;
}",
@"class C
{
void M()
{
(string name, int age) = GetPerson();
(string name, int age) t2 = GetPerson();
}
(string name, int age) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestNotIfDefaultTupleNameWithVar()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
var [|t1|] = GetPerson();
}
(string, int) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestWithUserNamesThatMatchDefaultTupleNameWithVar1()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
var [|t1|] = GetPerson();
}
(string Item1, int Item2) GetPerson() => default;
}",
@"class C
{
void M()
{
var (Item1, Item2) = GetPerson();
}
(string Item1, int Item2) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestWithUserNamesThatMatchDefaultTupleNameWithVar2()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
var [|t1|] = GetPerson();
Console.WriteLine(t1.Item1);
}
(string Item1, int Item2) GetPerson() => default;
}",
@"class C
{
void M()
{
var (Item1, Item2) = GetPerson();
Console.WriteLine(Item1);
}
(string Item1, int Item2) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestNotIfDefaultTupleNameWithTupleType()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
(string, int) [|t1|] = GetPerson();
}
(string, int) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestNotIfTupleIsUsed()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
var [|t1|] = GetPerson();
Console.WriteLine(t1);
}
(string name, int age) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestNotIfTupleMethodIsUsed()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
var [|t1|] = GetPerson();
Console.WriteLine(t1.ToString());
}
(string name, int age) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestNotIfTupleDefaultElementNameUsed()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
var [|t1|] = GetPerson();
Console.WriteLine(t1.Item1);
}
(string name, int age) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestNotIfTupleRandomNameUsed()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
var [|t1|] = GetPerson();
Console.WriteLine(t1.Unknown);
}
(string name, int age) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestTrivia1()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
/*1*/(/*2*/int/*3*/ name, /*4*/int/*5*/ age)/*6*/ [|t1|] = GetPerson();
Console.WriteLine(/*7*/t1.name/*8*/ + "" "" + /*9*/t1.age/*10*/);
}
(string name, int age) GetPerson() => default;
}",
@"class C
{
void M()
{
/*1*/(/*2*/int/*3*/ name, /*4*/int/*5*/ age)/*6*/ = GetPerson();
Console.WriteLine(/*7*/name/*8*/ + "" "" + /*9*/age/*10*/);
}
(string name, int age) GetPerson() => default;
}");
}
[WorkItem(25260, "https://github.com/dotnet/roslyn/issues/25260")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestNotWithDefaultLiteralInitializer()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
(string name, int age) [|person|] = default;
Console.WriteLine(person.name + "" "" + person.age);
}
}", new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7_1)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestWithDefaultExpressionInitializer()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
(string name, int age) [|person|] = default((string, int));
Console.WriteLine(person.name + "" "" + person.age);
}
}",
@"class C
{
void M()
{
(string name, int age) = default((string, int));
Console.WriteLine(name + "" "" + age);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestNotWithImplicitConversionFromNonTuple()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
class Person
{
public static implicit operator (string, int)(Person person) => default;
}
void M()
{
(string name, int age) [|person|] = new Person();
Console.WriteLine(person.name + "" "" + person.age);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestWithExplicitImplicitConversionFromNonTuple()
{
await TestInRegularAndScript1Async(
@"class C
{
class Person
{
public static implicit operator (string, int)(Person person) => default;
}
void M()
{
(string name, int age) [|person|] = ((string, int))new Person();
Console.WriteLine(person.name + "" "" + person.age);
}
}",
@"class C
{
class Person
{
public static implicit operator (string, int)(Person person) => default;
}
void M()
{
(string name, int age) = ((string, int))new Person();
Console.WriteLine(name + "" "" + age);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestNotWithImplicitConversionFromNonTupleInForEach()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
class Person
{
public static implicit operator (string, int)(Person person) => default;
}
void M()
{
foreach ((string name, int age) [|person|] in new Person[] { })
Console.WriteLine(person.name + "" "" + person.age);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestWithExplicitImplicitConversionFromNonTupleInForEach()
{
await TestInRegularAndScript1Async(
@"using System.Linq;
class C
{
class Person
{
public static implicit operator (string, int)(Person person) => default;
}
void M()
{
foreach ((string name, int age) [|person|] in new Person[] { }.Cast<(string, int)>())
Console.WriteLine(person.name + "" "" + person.age);
}
}",
@"using System.Linq;
class C
{
class Person
{
public static implicit operator (string, int)(Person person) => default;
}
void M()
{
foreach ((string name, int age) in new Person[] { }.Cast<(string, int)>())
Console.WriteLine(name + "" "" + age);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestWithTupleLiteralConversion()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
(object name, double age) [|person|] = (null, 0);
Console.WriteLine(person.name + "" "" + person.age);
}
}",
@"class C
{
void M()
{
(object name, double age) = (null, 0);
Console.WriteLine(name + "" "" + age);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestWithImplicitTupleConversion()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
(object name, double age) [|person|] = GetPerson();
Console.WriteLine(person.name + "" "" + person.age);
}
(string name, int age) GetPerson() => default;
}",
@"class C
{
void M()
{
(object name, double age) = GetPerson();
Console.WriteLine(name + "" "" + age);
}
(string name, int age) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestWithImplicitTupleConversionInForEach()
{
await TestInRegularAndScript1Async(
@"using System.Collections.Generic;
class C
{
void M()
{
foreach ((object name, double age) [|person|] in GetPeople())
Console.WriteLine(person.name + "" "" + person.age);
}
IEnumerable<(string name, int age)> GetPeople() => default;
}",
@"using System.Collections.Generic;
class C
{
void M()
{
foreach ((object name, double age) in GetPeople())
Console.WriteLine(name + "" "" + age);
}
IEnumerable<(string name, int age)> GetPeople() => default;
}");
}
[WorkItem(27251, "https://github.com/dotnet/roslyn/issues/27251")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestEscapedContextualKeywordAsTupleName()
{
await TestInRegularAndScript1Async(
@"using System.Collections.Generic;
class C
{
void M()
{
var collection = new List<(int position, int @delegate)>();
foreach (var it[||]em in collection)
{
// Do something
}
}
IEnumerable<(string name, int age)> GetPeople() => default;
}",
@"using System.Collections.Generic;
class C
{
void M()
{
var collection = new List<(int position, int @delegate)>();
foreach (var (position, @delegate) in collection)
{
// Do something
}
}
IEnumerable<(string name, int age)> GetPeople() => default;
}");
}
[Fact]
[WorkItem(42770, "https://github.com/dotnet/roslyn/issues/42770")]
[Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestPreserveAwait()
{
await TestInRegularAndScript1Async(
@"using System;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
[Goo]
await foreach (var [|t|] in Sequence())
{
Console.WriteLine(t.x + t.y);
}
}
static async IAsyncEnumerable<(int x, int y)> Sequence()
{
yield return (0, 0);
await Task.Yield();
}
}" + IAsyncEnumerable,
@"using System;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
[Goo]
await foreach (var (x, y) in Sequence())
{
Console.WriteLine(x + y);
}
}
static async IAsyncEnumerable<(int x, int y)> Sequence()
{
yield return (0, 0);
await Task.Yield();
}
}" + IAsyncEnumerable);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.UseDeconstruction;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseDeconstruction
{
public class UseDeconstructionTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
public UseDeconstructionTests(ITestOutputHelper logger)
: base(logger)
{
}
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new CSharpUseDeconstructionDiagnosticAnalyzer(), new CSharpUseDeconstructionCodeFixProvider());
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestVar()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
var [|t1|] = GetPerson();
}
(string name, int age) GetPerson() => default;
}",
@"class C
{
void M()
{
var (name, age) = GetPerson();
}
(string name, int age) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestNotIfNameInInnerScope()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
var [|t1|] = GetPerson();
{
int age;
}
}
(string name, int age) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestNotIfNameInOuterScope()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
int age;
void M()
{
var [|t1|] = GetPerson();
}
(string name, int age) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestUpdateReference()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
var [|t1|] = GetPerson();
Console.WriteLine(t1.name + "" "" + t1.age);
}
(string name, int age) GetPerson() => default;
}",
@"class C
{
void M()
{
var (name, age) = GetPerson();
Console.WriteLine(name + "" "" + age);
}
(string name, int age) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestTupleType()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
(int name, int age) [|t1|] = GetPerson();
Console.WriteLine(t1.name + "" "" + t1.age);
}
(string name, int age) GetPerson() => default;
}",
@"class C
{
void M()
{
(int name, int age) = GetPerson();
Console.WriteLine(name + "" "" + age);
}
(string name, int age) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestVarInForEach()
{
await TestInRegularAndScript1Async(
@"using System.Collections.Generic;
class C
{
void M()
{
foreach (var [|t1|] in GetPeople())
Console.WriteLine(t1.name + "" "" + t1.age);
}
IEnumerable<(string name, int age)> GetPeople() => default;
}",
@"using System.Collections.Generic;
class C
{
void M()
{
foreach (var (name, age) in GetPeople())
Console.WriteLine(name + "" "" + age);
}
IEnumerable<(string name, int age)> GetPeople() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestTupleTypeInForEach()
{
await TestInRegularAndScript1Async(
@"using System.Collections.Generic;
class C
{
void M()
{
foreach ((string name, int age) [|t1|] in GetPeople())
Console.WriteLine(t1.name + "" "" + t1.age);
}
IEnumerable<(string name, int age)> GetPeople() => default;
}",
@"using System.Collections.Generic;
class C
{
void M()
{
foreach ((string name, int age) in GetPeople())
Console.WriteLine(name + "" "" + age);
}
IEnumerable<(string name, int age)> GetPeople() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestFixAll1()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
var {|FixAllInDocument:t1|} = GetPerson();
var t2 = GetPerson();
}
(string name, int age) GetPerson() => default;
}",
@"class C
{
void M()
{
var (name, age) = GetPerson();
var t2 = GetPerson();
}
(string name, int age) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestFixAll2()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
var {|FixAllInDocument:t1|} = GetPerson();
}
void M2()
{
var t2 = GetPerson();
}
(string name, int age) GetPerson() => default;
}",
@"class C
{
void M()
{
var (name, age) = GetPerson();
}
void M2()
{
var (name, age) = GetPerson();
}
(string name, int age) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestFixAll3()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
(string name1, int age1) {|FixAllInDocument:t1|} = GetPerson();
(string name2, int age2) t2 = GetPerson();
}
(string name, int age) GetPerson() => default;
}",
@"class C
{
void M()
{
(string name1, int age1) = GetPerson();
(string name2, int age2) = GetPerson();
}
(string name, int age) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestFixAll4()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
(string name, int age) {|FixAllInDocument:t1|} = GetPerson();
(string name, int age) t2 = GetPerson();
}
(string name, int age) GetPerson() => default;
}",
@"class C
{
void M()
{
(string name, int age) = GetPerson();
(string name, int age) t2 = GetPerson();
}
(string name, int age) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestNotIfDefaultTupleNameWithVar()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
var [|t1|] = GetPerson();
}
(string, int) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestWithUserNamesThatMatchDefaultTupleNameWithVar1()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
var [|t1|] = GetPerson();
}
(string Item1, int Item2) GetPerson() => default;
}",
@"class C
{
void M()
{
var (Item1, Item2) = GetPerson();
}
(string Item1, int Item2) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestWithUserNamesThatMatchDefaultTupleNameWithVar2()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
var [|t1|] = GetPerson();
Console.WriteLine(t1.Item1);
}
(string Item1, int Item2) GetPerson() => default;
}",
@"class C
{
void M()
{
var (Item1, Item2) = GetPerson();
Console.WriteLine(Item1);
}
(string Item1, int Item2) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestNotIfDefaultTupleNameWithTupleType()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
(string, int) [|t1|] = GetPerson();
}
(string, int) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestNotIfTupleIsUsed()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
var [|t1|] = GetPerson();
Console.WriteLine(t1);
}
(string name, int age) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestNotIfTupleMethodIsUsed()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
var [|t1|] = GetPerson();
Console.WriteLine(t1.ToString());
}
(string name, int age) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestNotIfTupleDefaultElementNameUsed()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
var [|t1|] = GetPerson();
Console.WriteLine(t1.Item1);
}
(string name, int age) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestNotIfTupleRandomNameUsed()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
var [|t1|] = GetPerson();
Console.WriteLine(t1.Unknown);
}
(string name, int age) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestTrivia1()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
/*1*/(/*2*/int/*3*/ name, /*4*/int/*5*/ age)/*6*/ [|t1|] = GetPerson();
Console.WriteLine(/*7*/t1.name/*8*/ + "" "" + /*9*/t1.age/*10*/);
}
(string name, int age) GetPerson() => default;
}",
@"class C
{
void M()
{
/*1*/(/*2*/int/*3*/ name, /*4*/int/*5*/ age)/*6*/ = GetPerson();
Console.WriteLine(/*7*/name/*8*/ + "" "" + /*9*/age/*10*/);
}
(string name, int age) GetPerson() => default;
}");
}
[WorkItem(25260, "https://github.com/dotnet/roslyn/issues/25260")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestNotWithDefaultLiteralInitializer()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
(string name, int age) [|person|] = default;
Console.WriteLine(person.name + "" "" + person.age);
}
}", new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7_1)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestWithDefaultExpressionInitializer()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
(string name, int age) [|person|] = default((string, int));
Console.WriteLine(person.name + "" "" + person.age);
}
}",
@"class C
{
void M()
{
(string name, int age) = default((string, int));
Console.WriteLine(name + "" "" + age);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestNotWithImplicitConversionFromNonTuple()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
class Person
{
public static implicit operator (string, int)(Person person) => default;
}
void M()
{
(string name, int age) [|person|] = new Person();
Console.WriteLine(person.name + "" "" + person.age);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestWithExplicitImplicitConversionFromNonTuple()
{
await TestInRegularAndScript1Async(
@"class C
{
class Person
{
public static implicit operator (string, int)(Person person) => default;
}
void M()
{
(string name, int age) [|person|] = ((string, int))new Person();
Console.WriteLine(person.name + "" "" + person.age);
}
}",
@"class C
{
class Person
{
public static implicit operator (string, int)(Person person) => default;
}
void M()
{
(string name, int age) = ((string, int))new Person();
Console.WriteLine(name + "" "" + age);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestNotWithImplicitConversionFromNonTupleInForEach()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
class Person
{
public static implicit operator (string, int)(Person person) => default;
}
void M()
{
foreach ((string name, int age) [|person|] in new Person[] { })
Console.WriteLine(person.name + "" "" + person.age);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestWithExplicitImplicitConversionFromNonTupleInForEach()
{
await TestInRegularAndScript1Async(
@"using System.Linq;
class C
{
class Person
{
public static implicit operator (string, int)(Person person) => default;
}
void M()
{
foreach ((string name, int age) [|person|] in new Person[] { }.Cast<(string, int)>())
Console.WriteLine(person.name + "" "" + person.age);
}
}",
@"using System.Linq;
class C
{
class Person
{
public static implicit operator (string, int)(Person person) => default;
}
void M()
{
foreach ((string name, int age) in new Person[] { }.Cast<(string, int)>())
Console.WriteLine(name + "" "" + age);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestWithTupleLiteralConversion()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
(object name, double age) [|person|] = (null, 0);
Console.WriteLine(person.name + "" "" + person.age);
}
}",
@"class C
{
void M()
{
(object name, double age) = (null, 0);
Console.WriteLine(name + "" "" + age);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestWithImplicitTupleConversion()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
(object name, double age) [|person|] = GetPerson();
Console.WriteLine(person.name + "" "" + person.age);
}
(string name, int age) GetPerson() => default;
}",
@"class C
{
void M()
{
(object name, double age) = GetPerson();
Console.WriteLine(name + "" "" + age);
}
(string name, int age) GetPerson() => default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestWithImplicitTupleConversionInForEach()
{
await TestInRegularAndScript1Async(
@"using System.Collections.Generic;
class C
{
void M()
{
foreach ((object name, double age) [|person|] in GetPeople())
Console.WriteLine(person.name + "" "" + person.age);
}
IEnumerable<(string name, int age)> GetPeople() => default;
}",
@"using System.Collections.Generic;
class C
{
void M()
{
foreach ((object name, double age) in GetPeople())
Console.WriteLine(name + "" "" + age);
}
IEnumerable<(string name, int age)> GetPeople() => default;
}");
}
[WorkItem(27251, "https://github.com/dotnet/roslyn/issues/27251")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestEscapedContextualKeywordAsTupleName()
{
await TestInRegularAndScript1Async(
@"using System.Collections.Generic;
class C
{
void M()
{
var collection = new List<(int position, int @delegate)>();
foreach (var it[||]em in collection)
{
// Do something
}
}
IEnumerable<(string name, int age)> GetPeople() => default;
}",
@"using System.Collections.Generic;
class C
{
void M()
{
var collection = new List<(int position, int @delegate)>();
foreach (var (position, @delegate) in collection)
{
// Do something
}
}
IEnumerable<(string name, int age)> GetPeople() => default;
}");
}
[Fact]
[WorkItem(42770, "https://github.com/dotnet/roslyn/issues/42770")]
[Trait(Traits.Feature, Traits.Features.CodeActionsUseDeconstruction)]
public async Task TestPreserveAwait()
{
await TestInRegularAndScript1Async(
@"using System;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
[Goo]
await foreach (var [|t|] in Sequence())
{
Console.WriteLine(t.x + t.y);
}
}
static async IAsyncEnumerable<(int x, int y)> Sequence()
{
yield return (0, 0);
await Task.Yield();
}
}" + IAsyncEnumerable,
@"using System;
using System.Collections.Generic;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
[Goo]
await foreach (var (x, y) in Sequence())
{
Console.WriteLine(x + y);
}
}
static async IAsyncEnumerable<(int x, int y)> Sequence()
{
yield return (0, 0);
await Task.Yield();
}
}" + IAsyncEnumerable);
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Helpers/RemoveUnnecessaryImports/AbstractUnnecessaryImportsProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
namespace Microsoft.CodeAnalysis.RemoveUnnecessaryImports
{
internal abstract class AbstractUnnecessaryImportsProvider<T>
: IUnnecessaryImportsProvider, IEqualityComparer<T> where T : SyntaxNode
{
public ImmutableArray<SyntaxNode> GetUnnecessaryImports(
SemanticModel model, CancellationToken cancellationToken)
{
var root = model.SyntaxTree.GetRoot(cancellationToken);
return GetUnnecessaryImports(model, root, predicate: null, cancellationToken: cancellationToken);
}
protected abstract ImmutableArray<SyntaxNode> GetUnnecessaryImports(
SemanticModel model, SyntaxNode root,
Func<SyntaxNode, bool> predicate, CancellationToken cancellationToken);
ImmutableArray<SyntaxNode> IUnnecessaryImportsProvider.GetUnnecessaryImports(SemanticModel model, SyntaxNode root, Func<SyntaxNode, bool> predicate, CancellationToken cancellationToken)
=> GetUnnecessaryImports(model, root, predicate, cancellationToken);
bool IEqualityComparer<T>.Equals(T x, T y)
=> x.Span == y.Span;
int IEqualityComparer<T>.GetHashCode(T obj)
=> obj.Span.GetHashCode();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
namespace Microsoft.CodeAnalysis.RemoveUnnecessaryImports
{
internal abstract class AbstractUnnecessaryImportsProvider<T>
: IUnnecessaryImportsProvider, IEqualityComparer<T> where T : SyntaxNode
{
public ImmutableArray<SyntaxNode> GetUnnecessaryImports(
SemanticModel model, CancellationToken cancellationToken)
{
var root = model.SyntaxTree.GetRoot(cancellationToken);
return GetUnnecessaryImports(model, root, predicate: null, cancellationToken: cancellationToken);
}
protected abstract ImmutableArray<SyntaxNode> GetUnnecessaryImports(
SemanticModel model, SyntaxNode root,
Func<SyntaxNode, bool> predicate, CancellationToken cancellationToken);
ImmutableArray<SyntaxNode> IUnnecessaryImportsProvider.GetUnnecessaryImports(SemanticModel model, SyntaxNode root, Func<SyntaxNode, bool> predicate, CancellationToken cancellationToken)
=> GetUnnecessaryImports(model, root, predicate, cancellationToken);
bool IEqualityComparer<T>.Equals(T x, T y)
=> x.Span == y.Span;
int IEqualityComparer<T>.GetHashCode(T obj)
=> obj.Span.GetHashCode();
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Def/Implementation/ProjectSystem/Extensions/ProjectItemExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.CodeAnalysis;
using EnvDTE;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions
{
internal static class ProjectItemExtensions
{
public static ProjectItem FindItem(this ProjectItem item, string itemName, StringComparer comparer)
=> item.ProjectItems.FindItem(itemName, comparer);
public static bool TryGetFullPath(this ProjectItem item, [NotNullWhen(returnValue: true)] out string? fullPath)
{
fullPath = item.Properties.Item("FullPath").Value as string;
return fullPath != null;
}
public static bool IsFolder(this ProjectItem item)
=> item != null && item.Kind == Constants.vsProjectItemKindPhysicalFolder;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics.CodeAnalysis;
using EnvDTE;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions
{
internal static class ProjectItemExtensions
{
public static ProjectItem FindItem(this ProjectItem item, string itemName, StringComparer comparer)
=> item.ProjectItems.FindItem(itemName, comparer);
public static bool TryGetFullPath(this ProjectItem item, [NotNullWhen(returnValue: true)] out string? fullPath)
{
fullPath = item.Properties.Item("FullPath").Value as string;
return fullPath != null;
}
public static bool IsFolder(this ProjectItem item)
=> item != null && item.Kind == Constants.vsProjectItemKindPhysicalFolder;
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/IntroduceUsingStatement/AbstractIntroduceUsingStatementCodeRefactoringProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.CodeRefactorings;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Utilities;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.CodeActions.CodeAction;
namespace Microsoft.CodeAnalysis.IntroduceUsingStatement
{
internal abstract class AbstractIntroduceUsingStatementCodeRefactoringProvider<TStatementSyntax, TLocalDeclarationSyntax> : CodeRefactoringProvider
where TStatementSyntax : SyntaxNode
where TLocalDeclarationSyntax : TStatementSyntax
{
protected abstract string CodeActionTitle { get; }
protected abstract bool CanRefactorToContainBlockStatements(SyntaxNode parent);
protected abstract SyntaxList<TStatementSyntax> GetStatements(SyntaxNode parentOfStatementsToSurround);
protected abstract SyntaxNode WithStatements(SyntaxNode parentOfStatementsToSurround, SyntaxList<TStatementSyntax> statements);
protected abstract TStatementSyntax CreateUsingStatement(TLocalDeclarationSyntax declarationStatement, SyntaxTriviaList sameLineTrivia, SyntaxList<TStatementSyntax> statementsToSurround);
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var (document, span, cancellationToken) = context;
var declarationSyntax = await FindDisposableLocalDeclarationAsync(document, span, cancellationToken).ConfigureAwait(false);
if (declarationSyntax != null)
{
context.RegisterRefactoring(
new MyCodeAction(
CodeActionTitle,
cancellationToken => IntroduceUsingStatementAsync(document, declarationSyntax, cancellationToken)),
declarationSyntax.Span);
}
}
private async Task<TLocalDeclarationSyntax?> FindDisposableLocalDeclarationAsync(Document document, TextSpan selection, CancellationToken cancellationToken)
{
var declarationSyntax = await document.TryGetRelevantNodeAsync<TLocalDeclarationSyntax>(selection, cancellationToken).ConfigureAwait(false);
if (declarationSyntax is null || !CanRefactorToContainBlockStatements(declarationSyntax.GetRequiredParent()))
{
return null;
}
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var disposableType = semanticModel.Compilation.GetSpecialType(SpecialType.System_IDisposable);
if (disposableType is null)
{
return null;
}
var operation = semanticModel.GetOperation(declarationSyntax, cancellationToken) as IVariableDeclarationGroupOperation;
if (operation?.Declarations.Length != 1)
{
return null;
}
var localDeclaration = operation.Declarations[0];
if (localDeclaration.Declarators.Length != 1)
{
return null;
}
var declarator = localDeclaration.Declarators[0];
var localType = declarator.Symbol?.Type;
if (localType is null)
{
return null;
}
var initializer = (localDeclaration.Initializer ?? declarator.Initializer)?.Value;
// Initializer kind is invalid when incomplete declaration syntax ends in an equals token.
if (initializer is null || initializer.Kind == OperationKind.Invalid)
{
return null;
}
if (!IsLegalUsingStatementType(semanticModel.Compilation, disposableType, localType))
{
return null;
}
return declarationSyntax;
}
/// <summary>
/// Up to date with C# 7.3. Pattern-based disposal is likely to be added to C# 8.0,
/// in which case accessible instance and extension methods will need to be detected.
/// </summary>
private static bool IsLegalUsingStatementType(Compilation compilation, ITypeSymbol disposableType, ITypeSymbol type)
{
if (disposableType == null)
{
return false;
}
// CS1674: type used in a using statement must be implicitly convertible to 'System.IDisposable'
return compilation.ClassifyCommonConversion(type, disposableType).IsImplicit;
}
private async Task<Document> IntroduceUsingStatementAsync(
Document document,
TLocalDeclarationSyntax declarationStatement,
CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var syntaxFactsService = document.GetRequiredLanguageService<ISyntaxFactsService>();
var statementsToSurround = GetStatementsToSurround(declarationStatement, semanticModel, syntaxFactsService, cancellationToken);
// Separate the newline from the trivia that is going on the using declaration line.
var (sameLine, endOfLine) = SplitTrailingTrivia(declarationStatement, syntaxFactsService);
var usingStatement =
CreateUsingStatement(
declarationStatement,
sameLine,
statementsToSurround)
.WithLeadingTrivia(declarationStatement.GetLeadingTrivia())
.WithTrailingTrivia(endOfLine);
if (statementsToSurround.Any())
{
var parentStatements = GetStatements(declarationStatement.GetRequiredParent());
var declarationStatementIndex = parentStatements.IndexOf(declarationStatement);
var newParent = WithStatements(
declarationStatement.GetRequiredParent(),
new SyntaxList<TStatementSyntax>(parentStatements
.Take(declarationStatementIndex)
.Concat(usingStatement)
.Concat(parentStatements.Skip(declarationStatementIndex + 1 + statementsToSurround.Count))));
return document.WithSyntaxRoot(root.ReplaceNode(
declarationStatement.GetRequiredParent(),
newParent.WithAdditionalAnnotations(Formatter.Annotation)));
}
else
{
// Either the parent is not blocklike, meaning WithStatements can’t be used as in the other branch,
// or there’s just no need to replace more than the statement itself because no following statements
// will be surrounded.
return document.WithSyntaxRoot(root.ReplaceNode(
declarationStatement,
usingStatement.WithAdditionalAnnotations(Formatter.Annotation)));
}
}
private SyntaxList<TStatementSyntax> GetStatementsToSurround(
TLocalDeclarationSyntax declarationStatement,
SemanticModel semanticModel,
ISyntaxFactsService syntaxFactsService,
CancellationToken cancellationToken)
{
// Find the minimal number of statements to move into the using block
// in order to not break existing references to the local.
var lastUsageStatement = FindSiblingStatementContainingLastUsage(
declarationStatement,
semanticModel,
syntaxFactsService,
cancellationToken);
if (lastUsageStatement == declarationStatement)
{
return default;
}
var parentStatements = GetStatements(declarationStatement.GetRequiredParent());
var declarationStatementIndex = parentStatements.IndexOf(declarationStatement);
var lastUsageStatementIndex = parentStatements.IndexOf(lastUsageStatement, declarationStatementIndex + 1);
return new SyntaxList<TStatementSyntax>(parentStatements
.Take(lastUsageStatementIndex + 1)
.Skip(declarationStatementIndex + 1));
}
private static (SyntaxTriviaList sameLine, SyntaxTriviaList endOfLine) SplitTrailingTrivia(SyntaxNode node, ISyntaxFactsService syntaxFactsService)
{
var trailingTrivia = node.GetTrailingTrivia();
var lastIndex = trailingTrivia.Count - 1;
return lastIndex != -1 && syntaxFactsService.IsEndOfLineTrivia(trailingTrivia[lastIndex])
? (sameLine: trailingTrivia.RemoveAt(lastIndex), endOfLine: new SyntaxTriviaList(trailingTrivia[lastIndex]))
: (sameLine: trailingTrivia, endOfLine: SyntaxTriviaList.Empty);
}
private static TStatementSyntax FindSiblingStatementContainingLastUsage(
TStatementSyntax declarationSyntax,
SemanticModel semanticModel,
ISyntaxFactsService syntaxFactsService,
CancellationToken cancellationToken)
{
// We are going to step through the statements starting with the trigger variable's declaration.
// We will track when new locals are declared and when they are used. To determine the last
// statement that we should surround, we will walk through the locals in the order they are declared.
// If the local's declaration index falls within the last variable usage index, we will extend
// the last variable usage index to include the local's last usage.
// Take all the statements starting with the trigger variable's declaration.
var statementsFromDeclarationToEnd = declarationSyntax.GetRequiredParent().ChildNodesAndTokens()
.Select(nodeOrToken => nodeOrToken.AsNode())
.OfType<TStatementSyntax>()
.SkipWhile(node => node != declarationSyntax)
.ToImmutableArray();
// List of local variables that will be in the order they are declared.
using var _0 = ArrayBuilder<ISymbol>.GetInstance(out var localVariables);
// Map a symbol to an index into the statementsFromDeclarationToEnd array.
using var _1 = PooledDictionary<ISymbol, int>.GetInstance(out var variableDeclarationIndex);
using var _2 = PooledDictionary<ISymbol, int>.GetInstance(out var lastVariableUsageIndex);
// Loop through the statements from the trigger declaration to the end of the containing body.
// By starting with the trigger declaration it will add the trigger variable to the list of
// local variables.
for (var statementIndex = 0; statementIndex < statementsFromDeclarationToEnd.Length; statementIndex++)
{
var currentStatement = statementsFromDeclarationToEnd[statementIndex];
// Determine which local variables were referenced in this statement.
using var _ = PooledHashSet<ISymbol>.GetInstance(out var referencedVariables);
AddReferencedLocalVariables(referencedVariables, currentStatement, localVariables, semanticModel, syntaxFactsService, cancellationToken);
// Update the last usage index for each of the referenced variables.
foreach (var referencedVariable in referencedVariables)
{
lastVariableUsageIndex[referencedVariable] = statementIndex;
}
// Determine if new variables were declared in this statement.
var declaredVariables = semanticModel.GetAllDeclaredSymbols(currentStatement, cancellationToken);
foreach (var declaredVariable in declaredVariables)
{
// Initialize the declaration and usage index for the new variable and add it
// to the list of local variables.
variableDeclarationIndex[declaredVariable] = statementIndex;
lastVariableUsageIndex[declaredVariable] = statementIndex;
localVariables.Add(declaredVariable);
}
}
// Initially we will consider the trigger declaration statement the end of the using
// statement. This index will grow as we examine the last usage index of the local
// variables declared within the using statements scope.
var endOfUsingStatementIndex = 0;
// Walk through the local variables in the order that they were declared, starting
// with the trigger variable.
foreach (var localSymbol in localVariables)
{
var declarationIndex = variableDeclarationIndex[localSymbol];
if (declarationIndex > endOfUsingStatementIndex)
{
// If the variable was declared after the last statement to include in
// the using statement, we have gone far enough and other variables will
// also be declared outside the using statement.
break;
}
// If this variable was used later in the method than what we were considering
// the scope of the using statement, then increase the scope to include its last
// usage.
endOfUsingStatementIndex = Math.Max(endOfUsingStatementIndex, lastVariableUsageIndex[localSymbol]);
}
return statementsFromDeclarationToEnd[endOfUsingStatementIndex];
}
/// <summary>
/// Adds local variables that are being referenced within a statement to a set of symbols.
/// </summary>
private static void AddReferencedLocalVariables(
HashSet<ISymbol> referencedVariables,
SyntaxNode node,
IReadOnlyList<ISymbol> localVariables,
SemanticModel semanticModel,
ISyntaxFactsService syntaxFactsService,
CancellationToken cancellationToken)
{
// If this node matches one of our local variables, then we can say it has been referenced.
if (syntaxFactsService.IsIdentifierName(node))
{
var identifierName = syntaxFactsService.GetIdentifierOfSimpleName(node).ValueText;
var variable = localVariables.FirstOrDefault(localVariable
=> syntaxFactsService.StringComparer.Equals(localVariable.Name, identifierName) &&
localVariable.Equals(semanticModel.GetSymbolInfo(node, cancellationToken).Symbol));
if (variable is object)
{
referencedVariables.Add(variable);
}
}
// Walk through child nodes looking for references
foreach (var nodeOrToken in node.ChildNodesAndTokens())
{
// If we have already referenced all the local variables we are
// concerned with, then we can return early.
if (referencedVariables.Count == localVariables.Count)
{
return;
}
var childNode = nodeOrToken.AsNode();
if (childNode is null)
{
continue;
}
AddReferencedLocalVariables(referencedVariables, childNode, localVariables, semanticModel, syntaxFactsService, cancellationToken);
}
}
private sealed class MyCodeAction : 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.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Utilities;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.CodeActions.CodeAction;
namespace Microsoft.CodeAnalysis.IntroduceUsingStatement
{
internal abstract class AbstractIntroduceUsingStatementCodeRefactoringProvider<TStatementSyntax, TLocalDeclarationSyntax> : CodeRefactoringProvider
where TStatementSyntax : SyntaxNode
where TLocalDeclarationSyntax : TStatementSyntax
{
protected abstract string CodeActionTitle { get; }
protected abstract bool CanRefactorToContainBlockStatements(SyntaxNode parent);
protected abstract SyntaxList<TStatementSyntax> GetStatements(SyntaxNode parentOfStatementsToSurround);
protected abstract SyntaxNode WithStatements(SyntaxNode parentOfStatementsToSurround, SyntaxList<TStatementSyntax> statements);
protected abstract TStatementSyntax CreateUsingStatement(TLocalDeclarationSyntax declarationStatement, SyntaxTriviaList sameLineTrivia, SyntaxList<TStatementSyntax> statementsToSurround);
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var (document, span, cancellationToken) = context;
var declarationSyntax = await FindDisposableLocalDeclarationAsync(document, span, cancellationToken).ConfigureAwait(false);
if (declarationSyntax != null)
{
context.RegisterRefactoring(
new MyCodeAction(
CodeActionTitle,
cancellationToken => IntroduceUsingStatementAsync(document, declarationSyntax, cancellationToken)),
declarationSyntax.Span);
}
}
private async Task<TLocalDeclarationSyntax?> FindDisposableLocalDeclarationAsync(Document document, TextSpan selection, CancellationToken cancellationToken)
{
var declarationSyntax = await document.TryGetRelevantNodeAsync<TLocalDeclarationSyntax>(selection, cancellationToken).ConfigureAwait(false);
if (declarationSyntax is null || !CanRefactorToContainBlockStatements(declarationSyntax.GetRequiredParent()))
{
return null;
}
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var disposableType = semanticModel.Compilation.GetSpecialType(SpecialType.System_IDisposable);
if (disposableType is null)
{
return null;
}
var operation = semanticModel.GetOperation(declarationSyntax, cancellationToken) as IVariableDeclarationGroupOperation;
if (operation?.Declarations.Length != 1)
{
return null;
}
var localDeclaration = operation.Declarations[0];
if (localDeclaration.Declarators.Length != 1)
{
return null;
}
var declarator = localDeclaration.Declarators[0];
var localType = declarator.Symbol?.Type;
if (localType is null)
{
return null;
}
var initializer = (localDeclaration.Initializer ?? declarator.Initializer)?.Value;
// Initializer kind is invalid when incomplete declaration syntax ends in an equals token.
if (initializer is null || initializer.Kind == OperationKind.Invalid)
{
return null;
}
if (!IsLegalUsingStatementType(semanticModel.Compilation, disposableType, localType))
{
return null;
}
return declarationSyntax;
}
/// <summary>
/// Up to date with C# 7.3. Pattern-based disposal is likely to be added to C# 8.0,
/// in which case accessible instance and extension methods will need to be detected.
/// </summary>
private static bool IsLegalUsingStatementType(Compilation compilation, ITypeSymbol disposableType, ITypeSymbol type)
{
if (disposableType == null)
{
return false;
}
// CS1674: type used in a using statement must be implicitly convertible to 'System.IDisposable'
return compilation.ClassifyCommonConversion(type, disposableType).IsImplicit;
}
private async Task<Document> IntroduceUsingStatementAsync(
Document document,
TLocalDeclarationSyntax declarationStatement,
CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var syntaxFactsService = document.GetRequiredLanguageService<ISyntaxFactsService>();
var statementsToSurround = GetStatementsToSurround(declarationStatement, semanticModel, syntaxFactsService, cancellationToken);
// Separate the newline from the trivia that is going on the using declaration line.
var (sameLine, endOfLine) = SplitTrailingTrivia(declarationStatement, syntaxFactsService);
var usingStatement =
CreateUsingStatement(
declarationStatement,
sameLine,
statementsToSurround)
.WithLeadingTrivia(declarationStatement.GetLeadingTrivia())
.WithTrailingTrivia(endOfLine);
if (statementsToSurround.Any())
{
var parentStatements = GetStatements(declarationStatement.GetRequiredParent());
var declarationStatementIndex = parentStatements.IndexOf(declarationStatement);
var newParent = WithStatements(
declarationStatement.GetRequiredParent(),
new SyntaxList<TStatementSyntax>(parentStatements
.Take(declarationStatementIndex)
.Concat(usingStatement)
.Concat(parentStatements.Skip(declarationStatementIndex + 1 + statementsToSurround.Count))));
return document.WithSyntaxRoot(root.ReplaceNode(
declarationStatement.GetRequiredParent(),
newParent.WithAdditionalAnnotations(Formatter.Annotation)));
}
else
{
// Either the parent is not blocklike, meaning WithStatements can’t be used as in the other branch,
// or there’s just no need to replace more than the statement itself because no following statements
// will be surrounded.
return document.WithSyntaxRoot(root.ReplaceNode(
declarationStatement,
usingStatement.WithAdditionalAnnotations(Formatter.Annotation)));
}
}
private SyntaxList<TStatementSyntax> GetStatementsToSurround(
TLocalDeclarationSyntax declarationStatement,
SemanticModel semanticModel,
ISyntaxFactsService syntaxFactsService,
CancellationToken cancellationToken)
{
// Find the minimal number of statements to move into the using block
// in order to not break existing references to the local.
var lastUsageStatement = FindSiblingStatementContainingLastUsage(
declarationStatement,
semanticModel,
syntaxFactsService,
cancellationToken);
if (lastUsageStatement == declarationStatement)
{
return default;
}
var parentStatements = GetStatements(declarationStatement.GetRequiredParent());
var declarationStatementIndex = parentStatements.IndexOf(declarationStatement);
var lastUsageStatementIndex = parentStatements.IndexOf(lastUsageStatement, declarationStatementIndex + 1);
return new SyntaxList<TStatementSyntax>(parentStatements
.Take(lastUsageStatementIndex + 1)
.Skip(declarationStatementIndex + 1));
}
private static (SyntaxTriviaList sameLine, SyntaxTriviaList endOfLine) SplitTrailingTrivia(SyntaxNode node, ISyntaxFactsService syntaxFactsService)
{
var trailingTrivia = node.GetTrailingTrivia();
var lastIndex = trailingTrivia.Count - 1;
return lastIndex != -1 && syntaxFactsService.IsEndOfLineTrivia(trailingTrivia[lastIndex])
? (sameLine: trailingTrivia.RemoveAt(lastIndex), endOfLine: new SyntaxTriviaList(trailingTrivia[lastIndex]))
: (sameLine: trailingTrivia, endOfLine: SyntaxTriviaList.Empty);
}
private static TStatementSyntax FindSiblingStatementContainingLastUsage(
TStatementSyntax declarationSyntax,
SemanticModel semanticModel,
ISyntaxFactsService syntaxFactsService,
CancellationToken cancellationToken)
{
// We are going to step through the statements starting with the trigger variable's declaration.
// We will track when new locals are declared and when they are used. To determine the last
// statement that we should surround, we will walk through the locals in the order they are declared.
// If the local's declaration index falls within the last variable usage index, we will extend
// the last variable usage index to include the local's last usage.
// Take all the statements starting with the trigger variable's declaration.
var statementsFromDeclarationToEnd = declarationSyntax.GetRequiredParent().ChildNodesAndTokens()
.Select(nodeOrToken => nodeOrToken.AsNode())
.OfType<TStatementSyntax>()
.SkipWhile(node => node != declarationSyntax)
.ToImmutableArray();
// List of local variables that will be in the order they are declared.
using var _0 = ArrayBuilder<ISymbol>.GetInstance(out var localVariables);
// Map a symbol to an index into the statementsFromDeclarationToEnd array.
using var _1 = PooledDictionary<ISymbol, int>.GetInstance(out var variableDeclarationIndex);
using var _2 = PooledDictionary<ISymbol, int>.GetInstance(out var lastVariableUsageIndex);
// Loop through the statements from the trigger declaration to the end of the containing body.
// By starting with the trigger declaration it will add the trigger variable to the list of
// local variables.
for (var statementIndex = 0; statementIndex < statementsFromDeclarationToEnd.Length; statementIndex++)
{
var currentStatement = statementsFromDeclarationToEnd[statementIndex];
// Determine which local variables were referenced in this statement.
using var _ = PooledHashSet<ISymbol>.GetInstance(out var referencedVariables);
AddReferencedLocalVariables(referencedVariables, currentStatement, localVariables, semanticModel, syntaxFactsService, cancellationToken);
// Update the last usage index for each of the referenced variables.
foreach (var referencedVariable in referencedVariables)
{
lastVariableUsageIndex[referencedVariable] = statementIndex;
}
// Determine if new variables were declared in this statement.
var declaredVariables = semanticModel.GetAllDeclaredSymbols(currentStatement, cancellationToken);
foreach (var declaredVariable in declaredVariables)
{
// Initialize the declaration and usage index for the new variable and add it
// to the list of local variables.
variableDeclarationIndex[declaredVariable] = statementIndex;
lastVariableUsageIndex[declaredVariable] = statementIndex;
localVariables.Add(declaredVariable);
}
}
// Initially we will consider the trigger declaration statement the end of the using
// statement. This index will grow as we examine the last usage index of the local
// variables declared within the using statements scope.
var endOfUsingStatementIndex = 0;
// Walk through the local variables in the order that they were declared, starting
// with the trigger variable.
foreach (var localSymbol in localVariables)
{
var declarationIndex = variableDeclarationIndex[localSymbol];
if (declarationIndex > endOfUsingStatementIndex)
{
// If the variable was declared after the last statement to include in
// the using statement, we have gone far enough and other variables will
// also be declared outside the using statement.
break;
}
// If this variable was used later in the method than what we were considering
// the scope of the using statement, then increase the scope to include its last
// usage.
endOfUsingStatementIndex = Math.Max(endOfUsingStatementIndex, lastVariableUsageIndex[localSymbol]);
}
return statementsFromDeclarationToEnd[endOfUsingStatementIndex];
}
/// <summary>
/// Adds local variables that are being referenced within a statement to a set of symbols.
/// </summary>
private static void AddReferencedLocalVariables(
HashSet<ISymbol> referencedVariables,
SyntaxNode node,
IReadOnlyList<ISymbol> localVariables,
SemanticModel semanticModel,
ISyntaxFactsService syntaxFactsService,
CancellationToken cancellationToken)
{
// If this node matches one of our local variables, then we can say it has been referenced.
if (syntaxFactsService.IsIdentifierName(node))
{
var identifierName = syntaxFactsService.GetIdentifierOfSimpleName(node).ValueText;
var variable = localVariables.FirstOrDefault(localVariable
=> syntaxFactsService.StringComparer.Equals(localVariable.Name, identifierName) &&
localVariable.Equals(semanticModel.GetSymbolInfo(node, cancellationToken).Symbol));
if (variable is object)
{
referencedVariables.Add(variable);
}
}
// Walk through child nodes looking for references
foreach (var nodeOrToken in node.ChildNodesAndTokens())
{
// If we have already referenced all the local variables we are
// concerned with, then we can return early.
if (referencedVariables.Count == localVariables.Count)
{
return;
}
var childNode = nodeOrToken.AsNode();
if (childNode is null)
{
continue;
}
AddReferencedLocalVariables(referencedVariables, childNode, localVariables, semanticModel, syntaxFactsService, cancellationToken);
}
}
private sealed class MyCodeAction : DocumentChangeAction
{
public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument)
: base(title, createChangedDocument, title)
{
}
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CompilationContext.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Utilities;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal sealed class CompilationContext
{
internal readonly CSharpCompilation Compilation;
internal readonly Binder NamespaceBinder; // Internal for test purposes.
private readonly MethodSymbol _currentFrame;
private readonly ImmutableArray<LocalSymbol> _locals;
private readonly ImmutableDictionary<string, DisplayClassVariable> _displayClassVariables;
private readonly ImmutableArray<string> _sourceMethodParametersInOrder;
private readonly ImmutableArray<LocalSymbol> _localsForBinding;
private readonly bool _methodNotType;
/// <summary>
/// Create a context to compile expressions within a method scope.
/// </summary>
internal CompilationContext(
CSharpCompilation compilation,
MethodSymbol currentFrame,
MethodSymbol? currentSourceMethod,
ImmutableArray<LocalSymbol> locals,
ImmutableSortedSet<int> inScopeHoistedLocalSlots,
MethodDebugInfo<TypeSymbol, LocalSymbol> methodDebugInfo)
{
_currentFrame = currentFrame;
_methodNotType = !locals.IsDefault;
// NOTE: Since this is done within CompilationContext, it will not be cached.
// CONSIDER: The values should be the same everywhere in the module, so they
// could be cached.
// (Catch: what happens in a type context without a method def?)
Compilation = GetCompilationWithExternAliases(compilation, methodDebugInfo.ExternAliasRecords);
// Each expression compile should use a unique compilation
// to ensure expression-specific synthesized members can be
// added (anonymous types, for instance).
Debug.Assert(Compilation != compilation);
NamespaceBinder = CreateBinderChain(
Compilation,
currentFrame.ContainingNamespace,
methodDebugInfo.ImportRecordGroups);
if (_methodNotType)
{
_locals = locals;
_sourceMethodParametersInOrder = GetSourceMethodParametersInOrder(currentFrame, currentSourceMethod);
GetDisplayClassVariables(
currentFrame,
_locals,
inScopeHoistedLocalSlots,
_sourceMethodParametersInOrder,
out var displayClassVariableNamesInOrder,
out _displayClassVariables);
Debug.Assert(displayClassVariableNamesInOrder.Length == _displayClassVariables.Count);
_localsForBinding = GetLocalsForBinding(_locals, displayClassVariableNamesInOrder, _displayClassVariables);
}
else
{
_locals = ImmutableArray<LocalSymbol>.Empty;
_displayClassVariables = ImmutableDictionary<string, DisplayClassVariable>.Empty;
_localsForBinding = ImmutableArray<LocalSymbol>.Empty;
}
// Assert that the cheap check for "this" is equivalent to the expensive check for "this".
Debug.Assert(
(GetThisProxy(_displayClassVariables) != null) ==
_displayClassVariables.Values.Any(v => v.Kind == DisplayClassVariableKind.This));
}
internal bool TryCompileExpressions(
ImmutableArray<CSharpSyntaxNode> syntaxNodes,
string typeNameBase,
string methodName,
DiagnosticBag diagnostics,
[NotNullWhen(true)] out CommonPEModuleBuilder? module)
{
// Create a separate synthesized type for each evaluation method.
// (Necessary for VB in particular since the EENamedTypeSymbol.Locations
// is tied to the expression syntax in VB.)
var synthesizedTypes = syntaxNodes.SelectAsArray(
(syntax, i, _) => (NamedTypeSymbol)CreateSynthesizedType(syntax, typeNameBase + i, methodName, ImmutableArray<Alias>.Empty),
arg: (object?)null);
if (synthesizedTypes.Length == 0)
{
module = null;
return false;
}
module = CreateModuleBuilder(
Compilation,
additionalTypes: synthesizedTypes,
testData: null,
diagnostics: diagnostics);
Compilation.Compile(
module,
emittingPdb: false,
diagnostics: diagnostics,
filterOpt: null,
CancellationToken.None);
return !diagnostics.HasAnyErrors();
}
internal bool TryCompileExpression(
CSharpSyntaxNode syntax,
string typeName,
string methodName,
ImmutableArray<Alias> aliases,
CompilationTestData? testData,
DiagnosticBag diagnostics,
[NotNullWhen(true)] out CommonPEModuleBuilder? module,
[NotNullWhen(true)] out EEMethodSymbol? synthesizedMethod)
{
var synthesizedType = CreateSynthesizedType(syntax, typeName, methodName, aliases);
module = CreateModuleBuilder(
Compilation,
additionalTypes: ImmutableArray.Create((NamedTypeSymbol)synthesizedType),
testData,
diagnostics);
Compilation.Compile(
module,
emittingPdb: false,
diagnostics,
filterOpt: null,
CancellationToken.None);
if (diagnostics.HasAnyErrors())
{
module = null;
synthesizedMethod = null;
return false;
}
synthesizedMethod = GetSynthesizedMethod(synthesizedType);
return true;
}
private EENamedTypeSymbol CreateSynthesizedType(
CSharpSyntaxNode syntax,
string typeName,
string methodName,
ImmutableArray<Alias> aliases)
{
var objectType = Compilation.GetSpecialType(SpecialType.System_Object);
var synthesizedType = new EENamedTypeSymbol(
Compilation.SourceModule.GlobalNamespace,
objectType,
syntax,
_currentFrame,
typeName,
methodName,
this,
(EEMethodSymbol method, DiagnosticBag diags, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) =>
{
var hasDisplayClassThis = GetThisProxy(_displayClassVariables) != null;
var binder = ExtendBinderChain(
syntax,
aliases,
method,
NamespaceBinder,
hasDisplayClassThis,
_methodNotType,
out declaredLocals);
return (syntax is StatementSyntax statementSyntax) ?
BindStatement(binder, statementSyntax, diags, out properties) :
BindExpression(binder, (ExpressionSyntax)syntax, diags, out properties);
});
return synthesizedType;
}
internal bool TryCompileAssignment(
ExpressionSyntax syntax,
string typeName,
string methodName,
ImmutableArray<Alias> aliases,
CompilationTestData? testData,
DiagnosticBag diagnostics,
[NotNullWhen(true)] out CommonPEModuleBuilder? module,
[NotNullWhen(true)] out EEMethodSymbol? synthesizedMethod)
{
var objectType = Compilation.GetSpecialType(SpecialType.System_Object);
var synthesizedType = new EENamedTypeSymbol(
Compilation.SourceModule.GlobalNamespace,
objectType,
syntax,
_currentFrame,
typeName,
methodName,
this,
(EEMethodSymbol method, DiagnosticBag diags, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) =>
{
var hasDisplayClassThis = GetThisProxy(_displayClassVariables) != null;
var binder = ExtendBinderChain(
syntax,
aliases,
method,
NamespaceBinder,
hasDisplayClassThis,
methodNotType: true,
out declaredLocals);
properties = new ResultProperties(DkmClrCompilationResultFlags.PotentialSideEffect);
return BindAssignment(binder, syntax, diags);
});
module = CreateModuleBuilder(
Compilation,
additionalTypes: ImmutableArray.Create((NamedTypeSymbol)synthesizedType),
testData,
diagnostics);
Compilation.Compile(
module,
emittingPdb: false,
diagnostics,
filterOpt: null,
CancellationToken.None);
if (diagnostics.HasAnyErrors())
{
module = null;
synthesizedMethod = null;
return false;
}
synthesizedMethod = GetSynthesizedMethod(synthesizedType);
return true;
}
private static EEMethodSymbol GetSynthesizedMethod(EENamedTypeSymbol synthesizedType)
=> (EEMethodSymbol)synthesizedType.Methods[0];
private static string GetNextMethodName(ArrayBuilder<MethodSymbol> builder)
=> "<>m" + builder.Count;
/// <summary>
/// Generate a class containing methods that represent
/// the set of arguments and locals at the current scope.
/// </summary>
internal CommonPEModuleBuilder? CompileGetLocals(
string typeName,
ArrayBuilder<LocalAndMethod> localBuilder,
bool argumentsOnly,
ImmutableArray<Alias> aliases,
CompilationTestData? testData,
DiagnosticBag diagnostics)
{
var objectType = Compilation.GetSpecialType(SpecialType.System_Object);
var allTypeParameters = _currentFrame.GetAllTypeParameters();
var additionalTypes = ArrayBuilder<NamedTypeSymbol>.GetInstance();
EENamedTypeSymbol? typeVariablesType = null;
if (!argumentsOnly && allTypeParameters.Length > 0)
{
// Generate a generic type with matching type parameters.
// A null instance of the type will be used to represent the
// "Type variables" local.
typeVariablesType = new EENamedTypeSymbol(
Compilation.SourceModule.GlobalNamespace,
objectType,
_currentFrame,
ExpressionCompilerConstants.TypeVariablesClassName,
(m, t) => ImmutableArray.Create<MethodSymbol>(new EEConstructorSymbol(t)),
allTypeParameters,
(t1, t2) => allTypeParameters.SelectAsArray((tp, i, t) => (TypeParameterSymbol)new SimpleTypeParameterSymbol(t, i, tp.Name), t2));
additionalTypes.Add(typeVariablesType);
}
var synthesizedType = new EENamedTypeSymbol(
Compilation.SourceModule.GlobalNamespace,
objectType,
_currentFrame,
typeName,
(m, container) =>
{
var methodBuilder = ArrayBuilder<MethodSymbol>.GetInstance();
if (!argumentsOnly)
{
// Pseudo-variables: $exception, $ReturnValue, etc.
if (aliases.Length > 0)
{
var sourceAssembly = Compilation.SourceAssembly;
var typeNameDecoder = new EETypeNameDecoder(Compilation, (PEModuleSymbol)_currentFrame.ContainingModule);
foreach (var alias in aliases)
{
if (alias.IsReturnValueWithoutIndex())
{
Debug.Assert(aliases.Count(a => a.Kind == DkmClrAliasKind.ReturnValue) > 1);
continue;
}
var local = PlaceholderLocalSymbol.Create(
typeNameDecoder,
_currentFrame,
sourceAssembly,
alias);
// Skip pseudo-variables with errors.
if (local.HasUseSiteError)
{
continue;
}
var methodName = GetNextMethodName(methodBuilder);
var syntax = SyntaxFactory.IdentifierName(SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken));
var aliasMethod = CreateMethod(
container,
methodName,
syntax,
(EEMethodSymbol method, DiagnosticBag diags, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) =>
{
declaredLocals = ImmutableArray<LocalSymbol>.Empty;
var expression = new BoundLocal(syntax, local, constantValueOpt: null, type: local.Type);
properties = default;
return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true };
});
var flags = local.IsWritableVariable ? DkmClrCompilationResultFlags.None : DkmClrCompilationResultFlags.ReadOnlyResult;
localBuilder.Add(MakeLocalAndMethod(local, aliasMethod, flags));
methodBuilder.Add(aliasMethod);
}
}
// "this" for non-static methods that are not display class methods or
// display class methods where the display class contains "<>4__this".
if (!m.IsStatic && !IsDisplayClassType(m.ContainingType) ||
GetThisProxy(_displayClassVariables) != null)
{
var methodName = GetNextMethodName(methodBuilder);
var method = GetThisMethod(container, methodName);
localBuilder.Add(new CSharpLocalAndMethod("this", "this", method, DkmClrCompilationResultFlags.None)); // Note: writable in dev11.
methodBuilder.Add(method);
}
}
var itemsAdded = PooledHashSet<string>.GetInstance();
// Method parameters
int parameterIndex = m.IsStatic ? 0 : 1;
foreach (var parameter in m.Parameters)
{
var parameterName = parameter.Name;
if (GeneratedNames.GetKind(parameterName) == GeneratedNameKind.None &&
!IsDisplayClassParameter(parameter))
{
itemsAdded.Add(parameterName);
AppendParameterAndMethod(localBuilder, methodBuilder, parameter, container, parameterIndex);
}
parameterIndex++;
}
// In case of iterator or async state machine, the 'm' method has no parameters
// but the source method can have parameters to iterate over.
if (itemsAdded.Count == 0 && _sourceMethodParametersInOrder.Length != 0)
{
var localsDictionary = PooledDictionary<string, (LocalSymbol, int)>.GetInstance();
int localIndex = 0;
foreach (var local in _localsForBinding)
{
localsDictionary.Add(local.Name, (local, localIndex));
localIndex++;
}
foreach (var argumentName in _sourceMethodParametersInOrder)
{
(LocalSymbol local, int localIndex) localSymbolAndIndex;
if (localsDictionary.TryGetValue(argumentName, out localSymbolAndIndex))
{
itemsAdded.Add(argumentName);
var local = localSymbolAndIndex.local;
AppendLocalAndMethod(localBuilder, methodBuilder, local, container, localSymbolAndIndex.localIndex, GetLocalResultFlags(local));
}
}
localsDictionary.Free();
}
if (!argumentsOnly)
{
// Locals which were not added as parameters or parameters of the source method.
int localIndex = 0;
foreach (var local in _localsForBinding)
{
if (!itemsAdded.Contains(local.Name))
{
AppendLocalAndMethod(localBuilder, methodBuilder, local, container, localIndex, GetLocalResultFlags(local));
}
localIndex++;
}
// "Type variables".
if (typeVariablesType is object)
{
var methodName = GetNextMethodName(methodBuilder);
var returnType = typeVariablesType.Construct(allTypeParameters.Cast<TypeParameterSymbol, TypeSymbol>());
var method = GetTypeVariablesMethod(container, methodName, returnType);
localBuilder.Add(new CSharpLocalAndMethod(
ExpressionCompilerConstants.TypeVariablesLocalName,
ExpressionCompilerConstants.TypeVariablesLocalName,
method,
DkmClrCompilationResultFlags.ReadOnlyResult));
methodBuilder.Add(method);
}
}
itemsAdded.Free();
return methodBuilder.ToImmutableAndFree();
});
additionalTypes.Add(synthesizedType);
var module = CreateModuleBuilder(
Compilation,
additionalTypes.ToImmutableAndFree(),
testData,
diagnostics);
RoslynDebug.AssertNotNull(module);
Compilation.Compile(
module,
emittingPdb: false,
diagnostics,
filterOpt: null,
CancellationToken.None);
return diagnostics.HasAnyErrors() ? null : module;
}
private void AppendLocalAndMethod(
ArrayBuilder<LocalAndMethod> localBuilder,
ArrayBuilder<MethodSymbol> methodBuilder,
LocalSymbol local,
EENamedTypeSymbol container,
int localIndex,
DkmClrCompilationResultFlags resultFlags)
{
var methodName = GetNextMethodName(methodBuilder);
var method = GetLocalMethod(container, methodName, local.Name, localIndex);
localBuilder.Add(MakeLocalAndMethod(local, method, resultFlags));
methodBuilder.Add(method);
}
private void AppendParameterAndMethod(
ArrayBuilder<LocalAndMethod> localBuilder,
ArrayBuilder<MethodSymbol> methodBuilder,
ParameterSymbol parameter,
EENamedTypeSymbol container,
int parameterIndex)
{
// Note: The native EE doesn't do this, but if we don't escape keyword identifiers,
// the ResultProvider needs to be able to disambiguate cases like "this" and "@this",
// which it can't do correctly without semantic information.
var name = SyntaxHelpers.EscapeKeywordIdentifiers(parameter.Name);
var methodName = GetNextMethodName(methodBuilder);
var method = GetParameterMethod(container, methodName, name, parameterIndex);
localBuilder.Add(new CSharpLocalAndMethod(name, name, method, DkmClrCompilationResultFlags.None));
methodBuilder.Add(method);
}
private static LocalAndMethod MakeLocalAndMethod(LocalSymbol local, MethodSymbol method, DkmClrCompilationResultFlags flags)
{
// Note: The native EE doesn't do this, but if we don't escape keyword identifiers,
// the ResultProvider needs to be able to disambiguate cases like "this" and "@this",
// which it can't do correctly without semantic information.
var escapedName = SyntaxHelpers.EscapeKeywordIdentifiers(local.Name);
var displayName = (local as PlaceholderLocalSymbol)?.DisplayName ?? escapedName;
return new CSharpLocalAndMethod(escapedName, displayName, method, flags);
}
private static EEAssemblyBuilder CreateModuleBuilder(
CSharpCompilation compilation,
ImmutableArray<NamedTypeSymbol> additionalTypes,
CompilationTestData? testData,
DiagnosticBag diagnostics)
{
// Each assembly must have a unique name.
var emitOptions = new EmitOptions(outputNameOverride: ExpressionCompilerUtilities.GenerateUniqueName());
string? runtimeMetadataVersion = compilation.GetRuntimeMetadataVersion(emitOptions, diagnostics);
var serializationProperties = compilation.ConstructModuleSerializationProperties(emitOptions, runtimeMetadataVersion);
return new EEAssemblyBuilder(
compilation.SourceAssembly,
emitOptions,
serializationProperties,
additionalTypes,
contextType => GetNonDisplayClassContainer(((EENamedTypeSymbol)contextType).SubstitutedSourceType),
testData);
}
internal EEMethodSymbol CreateMethod(
EENamedTypeSymbol container,
string methodName,
CSharpSyntaxNode syntax,
GenerateMethodBody generateMethodBody)
{
return new EEMethodSymbol(
container,
methodName,
syntax.Location,
_currentFrame,
_locals,
_localsForBinding,
_displayClassVariables,
generateMethodBody);
}
private EEMethodSymbol GetLocalMethod(EENamedTypeSymbol container, string methodName, string localName, int localIndex)
{
var syntax = SyntaxFactory.IdentifierName(localName);
return CreateMethod(container, methodName, syntax, (EEMethodSymbol method, DiagnosticBag diagnostics, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) =>
{
declaredLocals = ImmutableArray<LocalSymbol>.Empty;
var local = method.LocalsForBinding[localIndex];
var expression = new BoundLocal(syntax, local, constantValueOpt: local.GetConstantValue(null, null, new BindingDiagnosticBag(diagnostics)), type: local.Type);
properties = default;
return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true };
});
}
private EEMethodSymbol GetParameterMethod(EENamedTypeSymbol container, string methodName, string parameterName, int parameterIndex)
{
var syntax = SyntaxFactory.IdentifierName(parameterName);
return CreateMethod(container, methodName, syntax, (EEMethodSymbol method, DiagnosticBag diagnostics, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) =>
{
declaredLocals = ImmutableArray<LocalSymbol>.Empty;
var parameter = method.Parameters[parameterIndex];
var expression = new BoundParameter(syntax, parameter);
properties = default;
return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true };
});
}
private EEMethodSymbol GetThisMethod(EENamedTypeSymbol container, string methodName)
{
var syntax = SyntaxFactory.ThisExpression();
return CreateMethod(container, methodName, syntax, (EEMethodSymbol method, DiagnosticBag diagnostics, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) =>
{
declaredLocals = ImmutableArray<LocalSymbol>.Empty;
var expression = new BoundThisReference(syntax, GetNonDisplayClassContainer(container.SubstitutedSourceType));
properties = default;
return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true };
});
}
private EEMethodSymbol GetTypeVariablesMethod(EENamedTypeSymbol container, string methodName, NamedTypeSymbol typeVariablesType)
{
var syntax = SyntaxFactory.IdentifierName(SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken));
return CreateMethod(container, methodName, syntax, (EEMethodSymbol method, DiagnosticBag diagnostics, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) =>
{
declaredLocals = ImmutableArray<LocalSymbol>.Empty;
var type = method.TypeMap.SubstituteNamedType(typeVariablesType);
var expression = new BoundObjectCreationExpression(syntax, type.InstanceConstructors[0]);
var statement = new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true };
properties = default;
return statement;
});
}
private static BoundStatement? BindExpression(Binder binder, ExpressionSyntax syntax, DiagnosticBag diagnostics, out ResultProperties resultProperties)
{
var flags = DkmClrCompilationResultFlags.None;
var bindingDiagnostics = new BindingDiagnosticBag(diagnostics);
// In addition to C# expressions, the native EE also supports
// type names which are bound to a representation of the type
// (but not System.Type) that the user can expand to see the
// base type. Instead, we only allow valid C# expressions.
var expression = IsDeconstruction(syntax)
? binder.BindDeconstruction((AssignmentExpressionSyntax)syntax, bindingDiagnostics, resultIsUsedOverride: true)
: binder.BindRValueWithoutTargetType(syntax, bindingDiagnostics);
if (diagnostics.HasAnyErrors())
{
resultProperties = default;
return null;
}
try
{
if (MayHaveSideEffectsVisitor.MayHaveSideEffects(expression))
{
flags |= DkmClrCompilationResultFlags.PotentialSideEffect;
}
}
catch (BoundTreeVisitor.CancelledByStackGuardException ex)
{
ex.AddAnError(diagnostics);
resultProperties = default;
return null;
}
var expressionType = expression.Type;
if (expressionType is null)
{
expression = binder.CreateReturnConversion(
syntax,
bindingDiagnostics,
expression,
RefKind.None,
binder.Compilation.GetSpecialType(SpecialType.System_Object));
if (diagnostics.HasAnyErrors())
{
resultProperties = default;
return null;
}
}
else if (expressionType.SpecialType == SpecialType.System_Void)
{
flags |= DkmClrCompilationResultFlags.ReadOnlyResult;
Debug.Assert(expression.ConstantValue == null);
resultProperties = expression.ExpressionSymbol.GetResultProperties(flags, isConstant: false);
return new BoundExpressionStatement(syntax, expression) { WasCompilerGenerated = true };
}
else if (expressionType.SpecialType == SpecialType.System_Boolean)
{
flags |= DkmClrCompilationResultFlags.BoolResult;
}
if (!IsAssignableExpression(binder, expression))
{
flags |= DkmClrCompilationResultFlags.ReadOnlyResult;
}
resultProperties = expression.ExpressionSymbol.GetResultProperties(flags, expression.ConstantValue != null);
return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true };
}
private static bool IsDeconstruction(ExpressionSyntax syntax)
{
if (syntax.Kind() != SyntaxKind.SimpleAssignmentExpression)
{
return false;
}
var node = (AssignmentExpressionSyntax)syntax;
return node.Left.Kind() == SyntaxKind.TupleExpression || node.Left.Kind() == SyntaxKind.DeclarationExpression;
}
private static BoundStatement BindStatement(Binder binder, StatementSyntax syntax, DiagnosticBag diagnostics, out ResultProperties properties)
{
properties = new ResultProperties(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult);
return binder.BindStatement(syntax, new BindingDiagnosticBag(diagnostics));
}
private static bool IsAssignableExpression(Binder binder, BoundExpression expression)
{
var result = binder.CheckValueKind(expression.Syntax, expression, Binder.BindValueKind.Assignable, checkingReceiver: false, BindingDiagnosticBag.Discarded);
return result;
}
private static BoundStatement? BindAssignment(Binder binder, ExpressionSyntax syntax, DiagnosticBag diagnostics)
{
var expression = binder.BindValue(syntax, new BindingDiagnosticBag(diagnostics), Binder.BindValueKind.RValue);
if (diagnostics.HasAnyErrors())
{
return null;
}
return new BoundExpressionStatement(expression.Syntax, expression) { WasCompilerGenerated = true };
}
private static Binder CreateBinderChain(
CSharpCompilation compilation,
NamespaceSymbol @namespace,
ImmutableArray<ImmutableArray<ImportRecord>> importRecordGroups)
{
var stack = ArrayBuilder<string>.GetInstance();
while (@namespace is object)
{
stack.Push(@namespace.Name);
@namespace = @namespace.ContainingNamespace;
}
Binder binder = new BuckStopsHereBinder(compilation);
var hasImports = !importRecordGroups.IsDefaultOrEmpty;
var numImportStringGroups = hasImports ? importRecordGroups.Length : 0;
var currentStringGroup = numImportStringGroups - 1;
// PERF: We used to call compilation.GetCompilationNamespace on every iteration,
// but that involved walking up to the global namespace, which we have to do
// anyway. Instead, we'll inline the functionality into our own walk of the
// namespace chain.
@namespace = compilation.GlobalNamespace;
while (stack.Count > 0)
{
var namespaceName = stack.Pop();
if (namespaceName.Length > 0)
{
// We're re-getting the namespace, rather than using the one containing
// the current frame method, because we want the merged namespace.
@namespace = @namespace.GetNestedNamespace(namespaceName);
RoslynDebug.AssertNotNull(@namespace);
}
else
{
Debug.Assert((object)@namespace == compilation.GlobalNamespace);
}
if (hasImports)
{
if (currentStringGroup < 0)
{
Debug.WriteLine($"No import string group for namespace '{@namespace}'");
break;
}
var importsBinder = new InContainerBinder(@namespace, binder);
Imports imports = BuildImports(compilation, importRecordGroups[currentStringGroup], importsBinder);
currentStringGroup--;
binder = WithExternAndUsingAliasesBinder.Create(imports.ExternAliases, imports.UsingAliases, WithUsingNamespacesAndTypesBinder.Create(imports.Usings, binder));
}
binder = new InContainerBinder(@namespace, binder);
}
stack.Free();
if (currentStringGroup >= 0)
{
// CONSIDER: We could lump these into the outermost namespace. It's probably not worthwhile since
// the usings are already for the wrong method.
Debug.WriteLine($"Found {currentStringGroup + 1} import string groups without corresponding namespaces");
}
return binder;
}
private static CSharpCompilation GetCompilationWithExternAliases(CSharpCompilation compilation, ImmutableArray<ExternAliasRecord> externAliasRecords)
{
if (externAliasRecords.IsDefaultOrEmpty)
{
return compilation.Clone();
}
var updatedReferences = ArrayBuilder<MetadataReference>.GetInstance();
var assembliesAndModulesBuilder = ArrayBuilder<Symbol>.GetInstance();
foreach (var reference in compilation.References)
{
updatedReferences.Add(reference);
assembliesAndModulesBuilder.Add(compilation.GetAssemblyOrModuleSymbol(reference)!);
}
Debug.Assert(assembliesAndModulesBuilder.Count == updatedReferences.Count);
var assembliesAndModules = assembliesAndModulesBuilder.ToImmutableAndFree();
foreach (var externAliasRecord in externAliasRecords)
{
var targetAssembly = externAliasRecord.TargetAssembly as AssemblySymbol;
int index;
if (targetAssembly != null)
{
index = assembliesAndModules.IndexOf(targetAssembly);
}
else
{
index = IndexOfMatchingAssembly((AssemblyIdentity)externAliasRecord.TargetAssembly, assembliesAndModules, compilation.Options.AssemblyIdentityComparer);
}
if (index < 0)
{
Debug.WriteLine($"Unable to find corresponding assembly reference for extern alias '{externAliasRecord}'");
continue;
}
var externAlias = externAliasRecord.Alias;
var assemblyReference = updatedReferences[index];
var oldAliases = assemblyReference.Properties.Aliases;
var newAliases = oldAliases.IsEmpty
? ImmutableArray.Create(MetadataReferenceProperties.GlobalAlias, externAlias)
: oldAliases.Concat(ImmutableArray.Create(externAlias));
// NOTE: Dev12 didn't emit custom debug info about "global", so we don't have
// a good way to distinguish between a module aliased with both (e.g.) "X" and
// "global" and a module aliased with only "X". As in Dev12, we assume that
// "global" is a valid alias to remain at least as permissive as source.
// NOTE: In the event that this introduces ambiguities between two assemblies
// (e.g. because one was "global" in source and the other was "X"), it should be
// possible to disambiguate as long as each assembly has a distinct extern alias,
// not necessarily used in source.
Debug.Assert(newAliases.Contains(MetadataReferenceProperties.GlobalAlias));
// Replace the value in the map with the updated reference.
updatedReferences[index] = assemblyReference.WithAliases(newAliases);
}
compilation = compilation.WithReferences(updatedReferences);
updatedReferences.Free();
return compilation;
}
private static int IndexOfMatchingAssembly(AssemblyIdentity referenceIdentity, ImmutableArray<Symbol> assembliesAndModules, AssemblyIdentityComparer assemblyIdentityComparer)
{
for (int i = 0; i < assembliesAndModules.Length; i++)
{
if (assembliesAndModules[i] is AssemblySymbol assembly && assemblyIdentityComparer.ReferenceMatchesDefinition(referenceIdentity, assembly.Identity))
{
return i;
}
}
return -1;
}
private static Binder ExtendBinderChain(
CSharpSyntaxNode syntax,
ImmutableArray<Alias> aliases,
EEMethodSymbol method,
Binder binder,
bool hasDisplayClassThis,
bool methodNotType,
out ImmutableArray<LocalSymbol> declaredLocals)
{
var substitutedSourceMethod = GetSubstitutedSourceMethod(method.SubstitutedSourceMethod, hasDisplayClassThis);
var substitutedSourceType = substitutedSourceMethod.ContainingType;
var stack = ArrayBuilder<NamedTypeSymbol>.GetInstance();
for (var type = substitutedSourceType; type is object; type = type.ContainingType)
{
stack.Add(type);
}
while (stack.Count > 0)
{
substitutedSourceType = stack.Pop();
binder = new InContainerBinder(substitutedSourceType, binder);
if (substitutedSourceType.Arity > 0)
{
binder = new WithTypeArgumentsBinder(substitutedSourceType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics, binder);
}
}
stack.Free();
if (substitutedSourceMethod.Arity > 0)
{
binder = new WithTypeArgumentsBinder(substitutedSourceMethod.TypeArgumentsWithAnnotations, binder);
}
// Method locals and parameters shadow pseudo-variables.
// That is why we place PlaceholderLocalBinder and ExecutableCodeBinder before EEMethodBinder.
if (methodNotType)
{
var typeNameDecoder = new EETypeNameDecoder(binder.Compilation, (PEModuleSymbol)substitutedSourceMethod.ContainingModule);
binder = new PlaceholderLocalBinder(
syntax,
aliases,
method,
typeNameDecoder,
binder);
}
binder = new EEMethodBinder(method, substitutedSourceMethod, binder);
if (methodNotType)
{
binder = new SimpleLocalScopeBinder(method.LocalsForBinding, binder);
}
Binder? actualRootBinder = null;
SyntaxNode? declaredLocalsScopeDesignator = null;
var executableBinder = new ExecutableCodeBinder(syntax, substitutedSourceMethod, binder,
(rootBinder, declaredLocalsScopeDesignatorOpt) =>
{
actualRootBinder = rootBinder;
declaredLocalsScopeDesignator = declaredLocalsScopeDesignatorOpt;
});
// We just need to trigger the process of building the binder map
// so that the lambda above was executed.
executableBinder.GetBinder(syntax);
RoslynDebug.AssertNotNull(actualRootBinder);
if (declaredLocalsScopeDesignator != null)
{
declaredLocals = actualRootBinder.GetDeclaredLocalsForScope(declaredLocalsScopeDesignator);
}
else
{
declaredLocals = ImmutableArray<LocalSymbol>.Empty;
}
return actualRootBinder;
}
private static Imports BuildImports(CSharpCompilation compilation, ImmutableArray<ImportRecord> importRecords, InContainerBinder binder)
{
// We make a first pass to extract all of the extern aliases because other imports may depend on them.
var externsBuilder = ArrayBuilder<AliasAndExternAliasDirective>.GetInstance();
foreach (var importRecord in importRecords)
{
if (importRecord.TargetKind != ImportTargetKind.Assembly)
{
continue;
}
var alias = importRecord.Alias;
RoslynDebug.AssertNotNull(alias);
if (!TryParseIdentifierNameSyntax(alias, out var aliasNameSyntax))
{
Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid extern alias '{alias}'");
continue;
}
NamespaceSymbol target;
compilation.GetExternAliasTarget(aliasNameSyntax.Identifier.ValueText, out target);
Debug.Assert(target.IsGlobalNamespace);
var aliasSymbol = AliasSymbol.CreateCustomDebugInfoAlias(target, aliasNameSyntax.Identifier, binder.ContainingMemberOrLambda, isExtern: true);
externsBuilder.Add(new AliasAndExternAliasDirective(aliasSymbol, externAliasDirective: null, skipInLookup: false));
}
var externs = externsBuilder.ToImmutableAndFree();
if (externs.Any())
{
// NB: This binder (and corresponding Imports) is only used to bind the other imports.
// We'll merge the externs into a final Imports object and return that to be used in
// the actual binder chain.
binder = new InContainerBinder(
binder.Container,
WithExternAliasesBinder.Create(externs, binder));
}
var usingAliases = ImmutableDictionary.CreateBuilder<string, AliasAndUsingDirective>();
var usingsBuilder = ArrayBuilder<NamespaceOrTypeAndUsingDirective>.GetInstance();
foreach (var importRecord in importRecords)
{
switch (importRecord.TargetKind)
{
case ImportTargetKind.Type:
{
var typeSymbol = (TypeSymbol?)importRecord.TargetType;
RoslynDebug.AssertNotNull(typeSymbol);
if (typeSymbol.IsErrorType())
{
// Type is unrecognized. The import may have been
// valid in the original source but unnecessary.
continue; // Don't add anything for this import.
}
else if (importRecord.Alias == null && !typeSymbol.IsStatic)
{
// Only static types can be directly imported.
continue;
}
if (!TryAddImport(importRecord.Alias, typeSymbol, usingsBuilder, usingAliases, binder, importRecord))
{
continue;
}
break;
}
case ImportTargetKind.Namespace:
{
var namespaceName = importRecord.TargetString;
RoslynDebug.AssertNotNull(namespaceName);
if (!SyntaxHelpers.TryParseDottedName(namespaceName, out _))
{
// DevDiv #999086: Some previous version of VS apparently generated type aliases as "UA{alias} T{alias-qualified type name}".
// Neither Roslyn nor Dev12 parses such imports. However, Roslyn discards them, rather than interpreting them as "UA{alias}"
// (which will rarely work and never be correct).
Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid target '{importRecord.TargetString}'");
continue;
}
NamespaceSymbol globalNamespace;
var targetAssembly = (AssemblySymbol?)importRecord.TargetAssembly;
if (targetAssembly is object)
{
if (targetAssembly.IsMissing)
{
Debug.WriteLine($"Import record '{importRecord}' has invalid assembly reference '{targetAssembly.Identity}'");
continue;
}
globalNamespace = targetAssembly.GlobalNamespace;
}
else if (importRecord.TargetAssemblyAlias != null)
{
if (!TryParseIdentifierNameSyntax(importRecord.TargetAssemblyAlias, out var externAliasSyntax))
{
Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid extern alias '{importRecord.TargetAssemblyAlias}'");
continue;
}
var aliasSymbol = (AliasSymbol)binder.BindNamespaceAliasSymbol(externAliasSyntax, BindingDiagnosticBag.Discarded);
if (aliasSymbol is null)
{
Debug.WriteLine($"Import record '{importRecord}' requires unknown extern alias '{importRecord.TargetAssemblyAlias}'");
continue;
}
globalNamespace = (NamespaceSymbol)aliasSymbol.Target;
}
else
{
globalNamespace = compilation.GlobalNamespace;
}
var namespaceSymbol = BindNamespace(namespaceName, globalNamespace);
if (namespaceSymbol is null)
{
// Namespace is unrecognized. The import may have been
// valid in the original source but unnecessary.
continue; // Don't add anything for this import.
}
if (!TryAddImport(importRecord.Alias, namespaceSymbol, usingsBuilder, usingAliases, binder, importRecord))
{
continue;
}
break;
}
case ImportTargetKind.Assembly:
// Handled in first pass (above).
break;
default:
throw ExceptionUtilities.UnexpectedValue(importRecord.TargetKind);
}
}
return Imports.Create(usingAliases.ToImmutableDictionary(), usingsBuilder.ToImmutableAndFree(), externs);
}
private static NamespaceSymbol? BindNamespace(string namespaceName, NamespaceSymbol globalNamespace)
{
NamespaceSymbol? namespaceSymbol = globalNamespace;
foreach (var name in namespaceName.Split('.'))
{
var members = namespaceSymbol.GetMembers(name);
namespaceSymbol = (members.Length == 1) ? members[0] as NamespaceSymbol : null;
if (namespaceSymbol is null)
{
break;
}
}
return namespaceSymbol;
}
private static bool TryAddImport(
string? alias,
NamespaceOrTypeSymbol targetSymbol,
ArrayBuilder<NamespaceOrTypeAndUsingDirective> usingsBuilder,
ImmutableDictionary<string, AliasAndUsingDirective>.Builder usingAliases,
InContainerBinder binder,
ImportRecord importRecord)
{
if (alias == null)
{
usingsBuilder.Add(new NamespaceOrTypeAndUsingDirective(targetSymbol, usingDirective: null, dependencies: default));
}
else
{
if (!TryParseIdentifierNameSyntax(alias, out var aliasSyntax))
{
Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid alias '{alias}'");
return false;
}
var aliasSymbol = AliasSymbol.CreateCustomDebugInfoAlias(targetSymbol, aliasSyntax.Identifier, binder.ContainingMemberOrLambda, isExtern: false);
usingAliases.Add(alias, new AliasAndUsingDirective(aliasSymbol, usingDirective: null));
}
return true;
}
private static bool TryParseIdentifierNameSyntax(string name, [NotNullWhen(true)] out IdentifierNameSyntax? syntax)
{
if (name == MetadataReferenceProperties.GlobalAlias)
{
syntax = SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword));
return true;
}
if (!SyntaxHelpers.TryParseDottedName(name, out var nameSyntax) || nameSyntax.Kind() != SyntaxKind.IdentifierName)
{
syntax = null;
return false;
}
syntax = (IdentifierNameSyntax)nameSyntax;
return true;
}
internal CommonMessageProvider MessageProvider
{
get { return Compilation.MessageProvider; }
}
private static DkmClrCompilationResultFlags GetLocalResultFlags(LocalSymbol local)
{
// CONSIDER: We might want to prevent the user from modifying pinned locals -
// that's pretty dangerous.
return local.IsConst
? DkmClrCompilationResultFlags.ReadOnlyResult
: DkmClrCompilationResultFlags.None;
}
/// <summary>
/// Generate the set of locals to use for binding.
/// </summary>
private static ImmutableArray<LocalSymbol> GetLocalsForBinding(
ImmutableArray<LocalSymbol> locals,
ImmutableArray<string> displayClassVariableNamesInOrder,
ImmutableDictionary<string, DisplayClassVariable> displayClassVariables)
{
var builder = ArrayBuilder<LocalSymbol>.GetInstance();
foreach (var local in locals)
{
var name = local.Name;
if (name == null)
{
continue;
}
if (GeneratedNames.GetKind(name) != GeneratedNameKind.None)
{
continue;
}
// Although Roslyn doesn't name synthesized locals unless they are well-known to EE,
// Dev12 did so we need to skip them here.
if (GeneratedNames.IsSynthesizedLocalName(name))
{
continue;
}
builder.Add(local);
}
foreach (var variableName in displayClassVariableNamesInOrder)
{
var variable = displayClassVariables[variableName];
switch (variable.Kind)
{
case DisplayClassVariableKind.Local:
case DisplayClassVariableKind.Parameter:
builder.Add(new EEDisplayClassFieldLocalSymbol(variable));
break;
}
}
return builder.ToImmutableAndFree();
}
private static ImmutableArray<string> GetSourceMethodParametersInOrder(
MethodSymbol method,
MethodSymbol? sourceMethod)
{
var containingType = method.ContainingType;
bool isIteratorOrAsyncMethod = IsDisplayClassType(containingType) &&
GeneratedNames.GetKind(containingType.Name) == GeneratedNameKind.StateMachineType;
var parameterNamesInOrder = ArrayBuilder<string>.GetInstance();
// For version before .NET 4.5, we cannot find the sourceMethod properly:
// The source method coincides with the original method in the case.
// Therefore, for iterators and async state machines, we have to get parameters from the containingType.
// This does not guarantee the proper order of parameters.
if (isIteratorOrAsyncMethod && method == sourceMethod)
{
Debug.Assert(IsDisplayClassType(containingType));
foreach (var member in containingType.GetMembers())
{
if (member.Kind != SymbolKind.Field)
{
continue;
}
var field = (FieldSymbol)member;
var fieldName = field.Name;
if (GeneratedNames.GetKind(fieldName) == GeneratedNameKind.None)
{
parameterNamesInOrder.Add(fieldName);
}
}
}
else
{
if (sourceMethod is object)
{
foreach (var p in sourceMethod.Parameters)
{
parameterNamesInOrder.Add(p.Name);
}
}
}
return parameterNamesInOrder.ToImmutableAndFree();
}
/// <summary>
/// Return a mapping of captured variables (parameters, locals, and
/// "this") to locals. The mapping is needed to expose the original
/// local identifiers (those from source) in the binder.
/// </summary>
private static void GetDisplayClassVariables(
MethodSymbol method,
ImmutableArray<LocalSymbol> locals,
ImmutableSortedSet<int> inScopeHoistedLocalSlots,
ImmutableArray<string> parameterNamesInOrder,
out ImmutableArray<string> displayClassVariableNamesInOrder,
out ImmutableDictionary<string, DisplayClassVariable> displayClassVariables)
{
// Calculate the shortest paths from locals to instances of display
// classes. There should not be two instances of the same display
// class immediately within any particular method.
var displayClassInstances = ArrayBuilder<DisplayClassInstanceAndFields>.GetInstance();
foreach (var parameter in method.Parameters)
{
if (GeneratedNames.GetKind(parameter.Name) == GeneratedNameKind.TransparentIdentifier ||
IsDisplayClassParameter(parameter))
{
var instance = new DisplayClassInstanceFromParameter(parameter);
displayClassInstances.Add(new DisplayClassInstanceAndFields(instance));
}
}
if (IsDisplayClassType(method.ContainingType) && !method.IsStatic)
{
// Add "this" display class instance.
var instance = new DisplayClassInstanceFromParameter(method.ThisParameter);
displayClassInstances.Add(new DisplayClassInstanceAndFields(instance));
}
var displayClassTypes = PooledHashSet<TypeSymbol>.GetInstance();
foreach (var instance in displayClassInstances)
{
displayClassTypes.Add(instance.Instance.Type);
}
// Find any additional display class instances.
GetAdditionalDisplayClassInstances(displayClassTypes, displayClassInstances, startIndex: 0);
// Add any display class instances from locals (these will contain any hoisted locals).
// Locals are only added after finding all display class instances reachable from
// parameters because locals may be null (temporary locals in async state machine
// for instance) so we prefer parameters to locals.
int startIndex = displayClassInstances.Count;
foreach (var local in locals)
{
var name = local.Name;
if (name != null && GeneratedNames.GetKind(name) == GeneratedNameKind.DisplayClassLocalOrField)
{
var localType = local.Type;
if (localType is object && displayClassTypes.Add(localType))
{
var instance = new DisplayClassInstanceFromLocal((EELocalSymbol)local);
displayClassInstances.Add(new DisplayClassInstanceAndFields(instance));
}
}
}
GetAdditionalDisplayClassInstances(displayClassTypes, displayClassInstances, startIndex);
displayClassTypes.Free();
if (displayClassInstances.Any())
{
var parameterNames = PooledHashSet<string>.GetInstance();
foreach (var name in parameterNamesInOrder)
{
parameterNames.Add(name);
}
// The locals are the set of all fields from the display classes.
var displayClassVariableNamesInOrderBuilder = ArrayBuilder<string>.GetInstance();
var displayClassVariablesBuilder = PooledDictionary<string, DisplayClassVariable>.GetInstance();
foreach (var instance in displayClassInstances)
{
GetDisplayClassVariables(
displayClassVariableNamesInOrderBuilder,
displayClassVariablesBuilder,
parameterNames,
inScopeHoistedLocalSlots,
instance);
}
displayClassVariableNamesInOrder = displayClassVariableNamesInOrderBuilder.ToImmutableAndFree();
displayClassVariables = displayClassVariablesBuilder.ToImmutableDictionary();
displayClassVariablesBuilder.Free();
parameterNames.Free();
}
else
{
displayClassVariableNamesInOrder = ImmutableArray<string>.Empty;
displayClassVariables = ImmutableDictionary<string, DisplayClassVariable>.Empty;
}
displayClassInstances.Free();
}
private static void GetAdditionalDisplayClassInstances(
HashSet<TypeSymbol> displayClassTypes,
ArrayBuilder<DisplayClassInstanceAndFields> displayClassInstances,
int startIndex)
{
// Find any additional display class instances breadth first.
for (int i = startIndex; i < displayClassInstances.Count; i++)
{
GetDisplayClassInstances(displayClassTypes, displayClassInstances, displayClassInstances[i]);
}
}
private static void GetDisplayClassInstances(
HashSet<TypeSymbol> displayClassTypes,
ArrayBuilder<DisplayClassInstanceAndFields> displayClassInstances,
DisplayClassInstanceAndFields instance)
{
// Display class instance. The display class fields are variables.
foreach (var member in instance.Type.GetMembers())
{
if (member.Kind != SymbolKind.Field)
{
continue;
}
var field = (FieldSymbol)member;
var fieldType = field.Type;
var fieldName = field.Name;
TryParseGeneratedName(fieldName, out var fieldKind, out var part);
switch (fieldKind)
{
case GeneratedNameKind.DisplayClassLocalOrField:
case GeneratedNameKind.TransparentIdentifier:
break;
case GeneratedNameKind.AnonymousTypeField:
if (GeneratedNames.GetKind(part) != GeneratedNameKind.TransparentIdentifier)
{
continue;
}
break;
case GeneratedNameKind.ThisProxyField:
if (GeneratedNames.GetKind(fieldType.Name) != GeneratedNameKind.LambdaDisplayClass)
{
continue;
}
// Async lambda case.
break;
default:
continue;
}
Debug.Assert(!field.IsStatic);
// A hoisted local that is itself a display class instance.
if (displayClassTypes.Add(fieldType))
{
var other = instance.FromField(field);
displayClassInstances.Add(other);
}
}
}
/// <summary>
/// Returns true if the parameter is a synthesized parameter representing
/// a display class instance (used to pass hoisted symbols to local functions).
/// </summary>
private static bool IsDisplayClassParameter(ParameterSymbol parameter)
{
var type = parameter.Type;
var result = type.Kind == SymbolKind.NamedType && IsDisplayClassType((NamedTypeSymbol)type);
Debug.Assert(!result || parameter.MetadataName == "");
return result;
}
private static void GetDisplayClassVariables(
ArrayBuilder<string> displayClassVariableNamesInOrderBuilder,
Dictionary<string, DisplayClassVariable> displayClassVariablesBuilder,
HashSet<string> parameterNames,
ImmutableSortedSet<int> inScopeHoistedLocalSlots,
DisplayClassInstanceAndFields instance)
{
// Display class instance. The display class fields are variables.
foreach (var member in instance.Type.GetMembers())
{
if (member.Kind != SymbolKind.Field)
{
continue;
}
var field = (FieldSymbol)member;
var fieldName = field.Name;
REPARSE:
DisplayClassVariableKind variableKind;
string variableName;
TryParseGeneratedName(fieldName, out var fieldKind, out var part);
switch (fieldKind)
{
case GeneratedNameKind.AnonymousTypeField:
RoslynDebug.AssertNotNull(part);
Debug.Assert(fieldName == field.Name); // This only happens once.
fieldName = part;
goto REPARSE;
case GeneratedNameKind.TransparentIdentifier:
// A transparent identifier (field) in an anonymous type synthesized for a transparent identifier.
Debug.Assert(!field.IsStatic);
continue;
case GeneratedNameKind.DisplayClassLocalOrField:
// A local that is itself a display class instance.
Debug.Assert(!field.IsStatic);
continue;
case GeneratedNameKind.HoistedLocalField:
RoslynDebug.AssertNotNull(part);
// Filter out hoisted locals that are known to be out-of-scope at the current IL offset.
// Hoisted locals with invalid indices will be included since more information is better
// than less in error scenarios.
if (GeneratedNames.TryParseSlotIndex(fieldName, out int slotIndex) &&
!inScopeHoistedLocalSlots.Contains(slotIndex))
{
continue;
}
variableName = part;
variableKind = DisplayClassVariableKind.Local;
Debug.Assert(!field.IsStatic);
break;
case GeneratedNameKind.ThisProxyField:
// A reference to "this".
variableName = ""; // Should not be referenced by name.
variableKind = DisplayClassVariableKind.This;
Debug.Assert(!field.IsStatic);
break;
case GeneratedNameKind.None:
// A reference to a parameter or local.
variableName = fieldName;
variableKind = parameterNames.Contains(variableName) ? DisplayClassVariableKind.Parameter : DisplayClassVariableKind.Local;
Debug.Assert(!field.IsStatic);
break;
default:
continue;
}
if (displayClassVariablesBuilder.ContainsKey(variableName))
{
// Only expecting duplicates for async state machine
// fields (that should be at the top-level).
Debug.Assert(displayClassVariablesBuilder[variableName].DisplayClassFields.Count() == 1);
if (!instance.Fields.Any())
{
// Prefer parameters over locals.
Debug.Assert(instance.Instance is DisplayClassInstanceFromLocal);
}
else
{
Debug.Assert(instance.Fields.Count() >= 1); // greater depth
Debug.Assert(variableKind == DisplayClassVariableKind.Parameter || variableKind == DisplayClassVariableKind.This);
if (variableKind == DisplayClassVariableKind.Parameter && GeneratedNames.GetKind(instance.Type.Name) == GeneratedNameKind.LambdaDisplayClass)
{
displayClassVariablesBuilder[variableName] = instance.ToVariable(variableName, variableKind, field);
}
}
}
else if (variableKind != DisplayClassVariableKind.This || GeneratedNames.GetKind(instance.Type.ContainingType.Name) != GeneratedNameKind.LambdaDisplayClass)
{
// In async lambdas, the hoisted "this" field in the state machine type will point to the display class instance, if there is one.
// In such cases, we want to add the display class "this" to the map instead (or nothing, if it lacks one).
displayClassVariableNamesInOrderBuilder.Add(variableName);
displayClassVariablesBuilder.Add(variableName, instance.ToVariable(variableName, variableKind, field));
}
}
}
private static void TryParseGeneratedName(string name, out GeneratedNameKind kind, out string? part)
{
_ = GeneratedNames.TryParseGeneratedName(name, out kind, out int openBracketOffset, out int closeBracketOffset);
switch (kind)
{
case GeneratedNameKind.AnonymousTypeField:
case GeneratedNameKind.HoistedLocalField:
part = name.Substring(openBracketOffset + 1, closeBracketOffset - openBracketOffset - 1);
break;
default:
part = null;
break;
}
}
private static bool IsDisplayClassType(TypeSymbol type)
{
switch (GeneratedNames.GetKind(type.Name))
{
case GeneratedNameKind.LambdaDisplayClass:
case GeneratedNameKind.StateMachineType:
return true;
default:
return false;
}
}
internal static DisplayClassVariable GetThisProxy(ImmutableDictionary<string, DisplayClassVariable> displayClassVariables)
{
return displayClassVariables.Values.FirstOrDefault(v => v.Kind == DisplayClassVariableKind.This);
}
private static NamedTypeSymbol GetNonDisplayClassContainer(NamedTypeSymbol type)
{
// 1) Display class and state machine types are always nested within the types
// that use them (so that they can access private members of those types).
// 2) The native compiler used to produce nested display classes for nested lambdas,
// so we may have to walk out more than one level.
while (IsDisplayClassType(type))
{
type = type.ContainingType!;
}
return type;
}
/// <summary>
/// Identifies the method in which binding should occur.
/// </summary>
/// <param name="candidateSubstitutedSourceMethod">
/// The symbol of the method that is currently on top of the callstack, with
/// EE type parameters substituted in place of the original type parameters.
/// </param>
/// <param name="sourceMethodMustBeInstance">
/// True if "this" is available via a display class in the current context.
/// </param>
/// <returns>
/// If <paramref name="candidateSubstitutedSourceMethod"/> is compiler-generated,
/// then we will attempt to determine which user-defined method caused it to be
/// generated. For example, if <paramref name="candidateSubstitutedSourceMethod"/>
/// is a state machine MoveNext method, then we will try to find the iterator or
/// async method for which it was generated. If we are able to find the original
/// method, then we will substitute in the EE type parameters. Otherwise, we will
/// return <paramref name="candidateSubstitutedSourceMethod"/>.
/// </returns>
/// <remarks>
/// In the event that the original method is overloaded, we may not be able to determine
/// which overload actually corresponds to the state machine. In particular, we do not
/// have information about the signature of the original method (i.e. number of parameters,
/// parameter types and ref-kinds, return type). However, we conjecture that this
/// level of uncertainty is acceptable, since parameters are managed by a separate binder
/// in the synthesized binder chain and we have enough information to check the other method
/// properties that are used during binding (e.g. static-ness, generic arity, type parameter
/// constraints).
/// </remarks>
internal static MethodSymbol GetSubstitutedSourceMethod(
MethodSymbol candidateSubstitutedSourceMethod,
bool sourceMethodMustBeInstance)
{
var candidateSubstitutedSourceType = candidateSubstitutedSourceMethod.ContainingType;
string desiredMethodName;
if (GeneratedNames.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceType.Name, GeneratedNameKind.StateMachineType, out desiredMethodName) ||
GeneratedNames.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceMethod.Name, GeneratedNameKind.LambdaMethod, out desiredMethodName) ||
GeneratedNames.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceMethod.Name, GeneratedNameKind.LocalFunction, out desiredMethodName))
{
// We could be in the MoveNext method of an async lambda.
string tempMethodName;
if (GeneratedNames.TryParseSourceMethodNameFromGeneratedName(desiredMethodName, GeneratedNameKind.LambdaMethod, out tempMethodName) ||
GeneratedNames.TryParseSourceMethodNameFromGeneratedName(desiredMethodName, GeneratedNameKind.LocalFunction, out tempMethodName))
{
desiredMethodName = tempMethodName;
var containing = candidateSubstitutedSourceType.ContainingType;
RoslynDebug.AssertNotNull(containing);
if (GeneratedNames.GetKind(containing.Name) == GeneratedNameKind.LambdaDisplayClass)
{
candidateSubstitutedSourceType = containing;
sourceMethodMustBeInstance = candidateSubstitutedSourceType.MemberNames.Select(GeneratedNames.GetKind).Contains(GeneratedNameKind.ThisProxyField);
}
}
var desiredTypeParameters = candidateSubstitutedSourceType.OriginalDefinition.TypeParameters;
// Type containing the original iterator, async, or lambda-containing method.
var substitutedSourceType = GetNonDisplayClassContainer(candidateSubstitutedSourceType);
foreach (var candidateMethod in substitutedSourceType.GetMembers().OfType<MethodSymbol>())
{
if (IsViableSourceMethod(candidateMethod, desiredMethodName, desiredTypeParameters, sourceMethodMustBeInstance))
{
return desiredTypeParameters.Length == 0
? candidateMethod
: candidateMethod.Construct(candidateSubstitutedSourceType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics);
}
}
Debug.Fail("Why didn't we find a substituted source method for " + candidateSubstitutedSourceMethod + "?");
}
return candidateSubstitutedSourceMethod;
}
private static bool IsViableSourceMethod(
MethodSymbol candidateMethod,
string desiredMethodName,
ImmutableArray<TypeParameterSymbol> desiredTypeParameters,
bool desiredMethodMustBeInstance)
{
return
!candidateMethod.IsAbstract &&
!(desiredMethodMustBeInstance && candidateMethod.IsStatic) &&
candidateMethod.Name == desiredMethodName &&
HaveSameConstraints(candidateMethod.TypeParameters, desiredTypeParameters);
}
private static bool HaveSameConstraints(ImmutableArray<TypeParameterSymbol> candidateTypeParameters, ImmutableArray<TypeParameterSymbol> desiredTypeParameters)
{
int arity = candidateTypeParameters.Length;
if (arity != desiredTypeParameters.Length)
{
return false;
}
if (arity == 0)
{
return true;
}
var indexedTypeParameters = IndexedTypeParameterSymbol.Take(arity);
var candidateTypeMap = new TypeMap(candidateTypeParameters, indexedTypeParameters, allowAlpha: true);
var desiredTypeMap = new TypeMap(desiredTypeParameters, indexedTypeParameters, allowAlpha: true);
return MemberSignatureComparer.HaveSameConstraints(candidateTypeParameters, candidateTypeMap, desiredTypeParameters, desiredTypeMap);
}
[DebuggerDisplay("{GetDebuggerDisplay(), nq}")]
private readonly struct DisplayClassInstanceAndFields
{
internal readonly DisplayClassInstance Instance;
internal readonly ConsList<FieldSymbol> Fields;
internal DisplayClassInstanceAndFields(DisplayClassInstance instance)
: this(instance, ConsList<FieldSymbol>.Empty)
{
Debug.Assert(IsDisplayClassType(instance.Type) ||
GeneratedNames.GetKind(instance.Type.Name) == GeneratedNameKind.AnonymousType);
}
private DisplayClassInstanceAndFields(DisplayClassInstance instance, ConsList<FieldSymbol> fields)
{
Instance = instance;
Fields = fields;
}
internal TypeSymbol Type
=> Fields.Any() ? Fields.Head.Type : Instance.Type;
internal int Depth
=> Fields.Count();
internal DisplayClassInstanceAndFields FromField(FieldSymbol field)
{
Debug.Assert(IsDisplayClassType(field.Type) ||
GeneratedNames.GetKind(field.Type.Name) == GeneratedNameKind.AnonymousType);
return new DisplayClassInstanceAndFields(Instance, Fields.Prepend(field));
}
internal DisplayClassVariable ToVariable(string name, DisplayClassVariableKind kind, FieldSymbol field)
{
return new DisplayClassVariable(name, kind, Instance, Fields.Prepend(field));
}
private string GetDebuggerDisplay()
{
return Instance.GetDebuggerDisplay(Fields);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Utilities;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal sealed class CompilationContext
{
internal readonly CSharpCompilation Compilation;
internal readonly Binder NamespaceBinder; // Internal for test purposes.
private readonly MethodSymbol _currentFrame;
private readonly ImmutableArray<LocalSymbol> _locals;
private readonly ImmutableDictionary<string, DisplayClassVariable> _displayClassVariables;
private readonly ImmutableArray<string> _sourceMethodParametersInOrder;
private readonly ImmutableArray<LocalSymbol> _localsForBinding;
private readonly bool _methodNotType;
/// <summary>
/// Create a context to compile expressions within a method scope.
/// </summary>
internal CompilationContext(
CSharpCompilation compilation,
MethodSymbol currentFrame,
MethodSymbol? currentSourceMethod,
ImmutableArray<LocalSymbol> locals,
ImmutableSortedSet<int> inScopeHoistedLocalSlots,
MethodDebugInfo<TypeSymbol, LocalSymbol> methodDebugInfo)
{
_currentFrame = currentFrame;
_methodNotType = !locals.IsDefault;
// NOTE: Since this is done within CompilationContext, it will not be cached.
// CONSIDER: The values should be the same everywhere in the module, so they
// could be cached.
// (Catch: what happens in a type context without a method def?)
Compilation = GetCompilationWithExternAliases(compilation, methodDebugInfo.ExternAliasRecords);
// Each expression compile should use a unique compilation
// to ensure expression-specific synthesized members can be
// added (anonymous types, for instance).
Debug.Assert(Compilation != compilation);
NamespaceBinder = CreateBinderChain(
Compilation,
currentFrame.ContainingNamespace,
methodDebugInfo.ImportRecordGroups);
if (_methodNotType)
{
_locals = locals;
_sourceMethodParametersInOrder = GetSourceMethodParametersInOrder(currentFrame, currentSourceMethod);
GetDisplayClassVariables(
currentFrame,
_locals,
inScopeHoistedLocalSlots,
_sourceMethodParametersInOrder,
out var displayClassVariableNamesInOrder,
out _displayClassVariables);
Debug.Assert(displayClassVariableNamesInOrder.Length == _displayClassVariables.Count);
_localsForBinding = GetLocalsForBinding(_locals, displayClassVariableNamesInOrder, _displayClassVariables);
}
else
{
_locals = ImmutableArray<LocalSymbol>.Empty;
_displayClassVariables = ImmutableDictionary<string, DisplayClassVariable>.Empty;
_localsForBinding = ImmutableArray<LocalSymbol>.Empty;
}
// Assert that the cheap check for "this" is equivalent to the expensive check for "this".
Debug.Assert(
(GetThisProxy(_displayClassVariables) != null) ==
_displayClassVariables.Values.Any(v => v.Kind == DisplayClassVariableKind.This));
}
internal bool TryCompileExpressions(
ImmutableArray<CSharpSyntaxNode> syntaxNodes,
string typeNameBase,
string methodName,
DiagnosticBag diagnostics,
[NotNullWhen(true)] out CommonPEModuleBuilder? module)
{
// Create a separate synthesized type for each evaluation method.
// (Necessary for VB in particular since the EENamedTypeSymbol.Locations
// is tied to the expression syntax in VB.)
var synthesizedTypes = syntaxNodes.SelectAsArray(
(syntax, i, _) => (NamedTypeSymbol)CreateSynthesizedType(syntax, typeNameBase + i, methodName, ImmutableArray<Alias>.Empty),
arg: (object?)null);
if (synthesizedTypes.Length == 0)
{
module = null;
return false;
}
module = CreateModuleBuilder(
Compilation,
additionalTypes: synthesizedTypes,
testData: null,
diagnostics: diagnostics);
Compilation.Compile(
module,
emittingPdb: false,
diagnostics: diagnostics,
filterOpt: null,
CancellationToken.None);
return !diagnostics.HasAnyErrors();
}
internal bool TryCompileExpression(
CSharpSyntaxNode syntax,
string typeName,
string methodName,
ImmutableArray<Alias> aliases,
CompilationTestData? testData,
DiagnosticBag diagnostics,
[NotNullWhen(true)] out CommonPEModuleBuilder? module,
[NotNullWhen(true)] out EEMethodSymbol? synthesizedMethod)
{
var synthesizedType = CreateSynthesizedType(syntax, typeName, methodName, aliases);
module = CreateModuleBuilder(
Compilation,
additionalTypes: ImmutableArray.Create((NamedTypeSymbol)synthesizedType),
testData,
diagnostics);
Compilation.Compile(
module,
emittingPdb: false,
diagnostics,
filterOpt: null,
CancellationToken.None);
if (diagnostics.HasAnyErrors())
{
module = null;
synthesizedMethod = null;
return false;
}
synthesizedMethod = GetSynthesizedMethod(synthesizedType);
return true;
}
private EENamedTypeSymbol CreateSynthesizedType(
CSharpSyntaxNode syntax,
string typeName,
string methodName,
ImmutableArray<Alias> aliases)
{
var objectType = Compilation.GetSpecialType(SpecialType.System_Object);
var synthesizedType = new EENamedTypeSymbol(
Compilation.SourceModule.GlobalNamespace,
objectType,
syntax,
_currentFrame,
typeName,
methodName,
this,
(EEMethodSymbol method, DiagnosticBag diags, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) =>
{
var hasDisplayClassThis = GetThisProxy(_displayClassVariables) != null;
var binder = ExtendBinderChain(
syntax,
aliases,
method,
NamespaceBinder,
hasDisplayClassThis,
_methodNotType,
out declaredLocals);
return (syntax is StatementSyntax statementSyntax) ?
BindStatement(binder, statementSyntax, diags, out properties) :
BindExpression(binder, (ExpressionSyntax)syntax, diags, out properties);
});
return synthesizedType;
}
internal bool TryCompileAssignment(
ExpressionSyntax syntax,
string typeName,
string methodName,
ImmutableArray<Alias> aliases,
CompilationTestData? testData,
DiagnosticBag diagnostics,
[NotNullWhen(true)] out CommonPEModuleBuilder? module,
[NotNullWhen(true)] out EEMethodSymbol? synthesizedMethod)
{
var objectType = Compilation.GetSpecialType(SpecialType.System_Object);
var synthesizedType = new EENamedTypeSymbol(
Compilation.SourceModule.GlobalNamespace,
objectType,
syntax,
_currentFrame,
typeName,
methodName,
this,
(EEMethodSymbol method, DiagnosticBag diags, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) =>
{
var hasDisplayClassThis = GetThisProxy(_displayClassVariables) != null;
var binder = ExtendBinderChain(
syntax,
aliases,
method,
NamespaceBinder,
hasDisplayClassThis,
methodNotType: true,
out declaredLocals);
properties = new ResultProperties(DkmClrCompilationResultFlags.PotentialSideEffect);
return BindAssignment(binder, syntax, diags);
});
module = CreateModuleBuilder(
Compilation,
additionalTypes: ImmutableArray.Create((NamedTypeSymbol)synthesizedType),
testData,
diagnostics);
Compilation.Compile(
module,
emittingPdb: false,
diagnostics,
filterOpt: null,
CancellationToken.None);
if (diagnostics.HasAnyErrors())
{
module = null;
synthesizedMethod = null;
return false;
}
synthesizedMethod = GetSynthesizedMethod(synthesizedType);
return true;
}
private static EEMethodSymbol GetSynthesizedMethod(EENamedTypeSymbol synthesizedType)
=> (EEMethodSymbol)synthesizedType.Methods[0];
private static string GetNextMethodName(ArrayBuilder<MethodSymbol> builder)
=> "<>m" + builder.Count;
/// <summary>
/// Generate a class containing methods that represent
/// the set of arguments and locals at the current scope.
/// </summary>
internal CommonPEModuleBuilder? CompileGetLocals(
string typeName,
ArrayBuilder<LocalAndMethod> localBuilder,
bool argumentsOnly,
ImmutableArray<Alias> aliases,
CompilationTestData? testData,
DiagnosticBag diagnostics)
{
var objectType = Compilation.GetSpecialType(SpecialType.System_Object);
var allTypeParameters = _currentFrame.GetAllTypeParameters();
var additionalTypes = ArrayBuilder<NamedTypeSymbol>.GetInstance();
EENamedTypeSymbol? typeVariablesType = null;
if (!argumentsOnly && allTypeParameters.Length > 0)
{
// Generate a generic type with matching type parameters.
// A null instance of the type will be used to represent the
// "Type variables" local.
typeVariablesType = new EENamedTypeSymbol(
Compilation.SourceModule.GlobalNamespace,
objectType,
_currentFrame,
ExpressionCompilerConstants.TypeVariablesClassName,
(m, t) => ImmutableArray.Create<MethodSymbol>(new EEConstructorSymbol(t)),
allTypeParameters,
(t1, t2) => allTypeParameters.SelectAsArray((tp, i, t) => (TypeParameterSymbol)new SimpleTypeParameterSymbol(t, i, tp.Name), t2));
additionalTypes.Add(typeVariablesType);
}
var synthesizedType = new EENamedTypeSymbol(
Compilation.SourceModule.GlobalNamespace,
objectType,
_currentFrame,
typeName,
(m, container) =>
{
var methodBuilder = ArrayBuilder<MethodSymbol>.GetInstance();
if (!argumentsOnly)
{
// Pseudo-variables: $exception, $ReturnValue, etc.
if (aliases.Length > 0)
{
var sourceAssembly = Compilation.SourceAssembly;
var typeNameDecoder = new EETypeNameDecoder(Compilation, (PEModuleSymbol)_currentFrame.ContainingModule);
foreach (var alias in aliases)
{
if (alias.IsReturnValueWithoutIndex())
{
Debug.Assert(aliases.Count(a => a.Kind == DkmClrAliasKind.ReturnValue) > 1);
continue;
}
var local = PlaceholderLocalSymbol.Create(
typeNameDecoder,
_currentFrame,
sourceAssembly,
alias);
// Skip pseudo-variables with errors.
if (local.HasUseSiteError)
{
continue;
}
var methodName = GetNextMethodName(methodBuilder);
var syntax = SyntaxFactory.IdentifierName(SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken));
var aliasMethod = CreateMethod(
container,
methodName,
syntax,
(EEMethodSymbol method, DiagnosticBag diags, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) =>
{
declaredLocals = ImmutableArray<LocalSymbol>.Empty;
var expression = new BoundLocal(syntax, local, constantValueOpt: null, type: local.Type);
properties = default;
return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true };
});
var flags = local.IsWritableVariable ? DkmClrCompilationResultFlags.None : DkmClrCompilationResultFlags.ReadOnlyResult;
localBuilder.Add(MakeLocalAndMethod(local, aliasMethod, flags));
methodBuilder.Add(aliasMethod);
}
}
// "this" for non-static methods that are not display class methods or
// display class methods where the display class contains "<>4__this".
if (!m.IsStatic && !IsDisplayClassType(m.ContainingType) ||
GetThisProxy(_displayClassVariables) != null)
{
var methodName = GetNextMethodName(methodBuilder);
var method = GetThisMethod(container, methodName);
localBuilder.Add(new CSharpLocalAndMethod("this", "this", method, DkmClrCompilationResultFlags.None)); // Note: writable in dev11.
methodBuilder.Add(method);
}
}
var itemsAdded = PooledHashSet<string>.GetInstance();
// Method parameters
int parameterIndex = m.IsStatic ? 0 : 1;
foreach (var parameter in m.Parameters)
{
var parameterName = parameter.Name;
if (GeneratedNames.GetKind(parameterName) == GeneratedNameKind.None &&
!IsDisplayClassParameter(parameter))
{
itemsAdded.Add(parameterName);
AppendParameterAndMethod(localBuilder, methodBuilder, parameter, container, parameterIndex);
}
parameterIndex++;
}
// In case of iterator or async state machine, the 'm' method has no parameters
// but the source method can have parameters to iterate over.
if (itemsAdded.Count == 0 && _sourceMethodParametersInOrder.Length != 0)
{
var localsDictionary = PooledDictionary<string, (LocalSymbol, int)>.GetInstance();
int localIndex = 0;
foreach (var local in _localsForBinding)
{
localsDictionary.Add(local.Name, (local, localIndex));
localIndex++;
}
foreach (var argumentName in _sourceMethodParametersInOrder)
{
(LocalSymbol local, int localIndex) localSymbolAndIndex;
if (localsDictionary.TryGetValue(argumentName, out localSymbolAndIndex))
{
itemsAdded.Add(argumentName);
var local = localSymbolAndIndex.local;
AppendLocalAndMethod(localBuilder, methodBuilder, local, container, localSymbolAndIndex.localIndex, GetLocalResultFlags(local));
}
}
localsDictionary.Free();
}
if (!argumentsOnly)
{
// Locals which were not added as parameters or parameters of the source method.
int localIndex = 0;
foreach (var local in _localsForBinding)
{
if (!itemsAdded.Contains(local.Name))
{
AppendLocalAndMethod(localBuilder, methodBuilder, local, container, localIndex, GetLocalResultFlags(local));
}
localIndex++;
}
// "Type variables".
if (typeVariablesType is object)
{
var methodName = GetNextMethodName(methodBuilder);
var returnType = typeVariablesType.Construct(allTypeParameters.Cast<TypeParameterSymbol, TypeSymbol>());
var method = GetTypeVariablesMethod(container, methodName, returnType);
localBuilder.Add(new CSharpLocalAndMethod(
ExpressionCompilerConstants.TypeVariablesLocalName,
ExpressionCompilerConstants.TypeVariablesLocalName,
method,
DkmClrCompilationResultFlags.ReadOnlyResult));
methodBuilder.Add(method);
}
}
itemsAdded.Free();
return methodBuilder.ToImmutableAndFree();
});
additionalTypes.Add(synthesizedType);
var module = CreateModuleBuilder(
Compilation,
additionalTypes.ToImmutableAndFree(),
testData,
diagnostics);
RoslynDebug.AssertNotNull(module);
Compilation.Compile(
module,
emittingPdb: false,
diagnostics,
filterOpt: null,
CancellationToken.None);
return diagnostics.HasAnyErrors() ? null : module;
}
private void AppendLocalAndMethod(
ArrayBuilder<LocalAndMethod> localBuilder,
ArrayBuilder<MethodSymbol> methodBuilder,
LocalSymbol local,
EENamedTypeSymbol container,
int localIndex,
DkmClrCompilationResultFlags resultFlags)
{
var methodName = GetNextMethodName(methodBuilder);
var method = GetLocalMethod(container, methodName, local.Name, localIndex);
localBuilder.Add(MakeLocalAndMethod(local, method, resultFlags));
methodBuilder.Add(method);
}
private void AppendParameterAndMethod(
ArrayBuilder<LocalAndMethod> localBuilder,
ArrayBuilder<MethodSymbol> methodBuilder,
ParameterSymbol parameter,
EENamedTypeSymbol container,
int parameterIndex)
{
// Note: The native EE doesn't do this, but if we don't escape keyword identifiers,
// the ResultProvider needs to be able to disambiguate cases like "this" and "@this",
// which it can't do correctly without semantic information.
var name = SyntaxHelpers.EscapeKeywordIdentifiers(parameter.Name);
var methodName = GetNextMethodName(methodBuilder);
var method = GetParameterMethod(container, methodName, name, parameterIndex);
localBuilder.Add(new CSharpLocalAndMethod(name, name, method, DkmClrCompilationResultFlags.None));
methodBuilder.Add(method);
}
private static LocalAndMethod MakeLocalAndMethod(LocalSymbol local, MethodSymbol method, DkmClrCompilationResultFlags flags)
{
// Note: The native EE doesn't do this, but if we don't escape keyword identifiers,
// the ResultProvider needs to be able to disambiguate cases like "this" and "@this",
// which it can't do correctly without semantic information.
var escapedName = SyntaxHelpers.EscapeKeywordIdentifiers(local.Name);
var displayName = (local as PlaceholderLocalSymbol)?.DisplayName ?? escapedName;
return new CSharpLocalAndMethod(escapedName, displayName, method, flags);
}
private static EEAssemblyBuilder CreateModuleBuilder(
CSharpCompilation compilation,
ImmutableArray<NamedTypeSymbol> additionalTypes,
CompilationTestData? testData,
DiagnosticBag diagnostics)
{
// Each assembly must have a unique name.
var emitOptions = new EmitOptions(outputNameOverride: ExpressionCompilerUtilities.GenerateUniqueName());
string? runtimeMetadataVersion = compilation.GetRuntimeMetadataVersion(emitOptions, diagnostics);
var serializationProperties = compilation.ConstructModuleSerializationProperties(emitOptions, runtimeMetadataVersion);
return new EEAssemblyBuilder(
compilation.SourceAssembly,
emitOptions,
serializationProperties,
additionalTypes,
contextType => GetNonDisplayClassContainer(((EENamedTypeSymbol)contextType).SubstitutedSourceType),
testData);
}
internal EEMethodSymbol CreateMethod(
EENamedTypeSymbol container,
string methodName,
CSharpSyntaxNode syntax,
GenerateMethodBody generateMethodBody)
{
return new EEMethodSymbol(
container,
methodName,
syntax.Location,
_currentFrame,
_locals,
_localsForBinding,
_displayClassVariables,
generateMethodBody);
}
private EEMethodSymbol GetLocalMethod(EENamedTypeSymbol container, string methodName, string localName, int localIndex)
{
var syntax = SyntaxFactory.IdentifierName(localName);
return CreateMethod(container, methodName, syntax, (EEMethodSymbol method, DiagnosticBag diagnostics, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) =>
{
declaredLocals = ImmutableArray<LocalSymbol>.Empty;
var local = method.LocalsForBinding[localIndex];
var expression = new BoundLocal(syntax, local, constantValueOpt: local.GetConstantValue(null, null, new BindingDiagnosticBag(diagnostics)), type: local.Type);
properties = default;
return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true };
});
}
private EEMethodSymbol GetParameterMethod(EENamedTypeSymbol container, string methodName, string parameterName, int parameterIndex)
{
var syntax = SyntaxFactory.IdentifierName(parameterName);
return CreateMethod(container, methodName, syntax, (EEMethodSymbol method, DiagnosticBag diagnostics, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) =>
{
declaredLocals = ImmutableArray<LocalSymbol>.Empty;
var parameter = method.Parameters[parameterIndex];
var expression = new BoundParameter(syntax, parameter);
properties = default;
return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true };
});
}
private EEMethodSymbol GetThisMethod(EENamedTypeSymbol container, string methodName)
{
var syntax = SyntaxFactory.ThisExpression();
return CreateMethod(container, methodName, syntax, (EEMethodSymbol method, DiagnosticBag diagnostics, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) =>
{
declaredLocals = ImmutableArray<LocalSymbol>.Empty;
var expression = new BoundThisReference(syntax, GetNonDisplayClassContainer(container.SubstitutedSourceType));
properties = default;
return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true };
});
}
private EEMethodSymbol GetTypeVariablesMethod(EENamedTypeSymbol container, string methodName, NamedTypeSymbol typeVariablesType)
{
var syntax = SyntaxFactory.IdentifierName(SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken));
return CreateMethod(container, methodName, syntax, (EEMethodSymbol method, DiagnosticBag diagnostics, out ImmutableArray<LocalSymbol> declaredLocals, out ResultProperties properties) =>
{
declaredLocals = ImmutableArray<LocalSymbol>.Empty;
var type = method.TypeMap.SubstituteNamedType(typeVariablesType);
var expression = new BoundObjectCreationExpression(syntax, type.InstanceConstructors[0]);
var statement = new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true };
properties = default;
return statement;
});
}
private static BoundStatement? BindExpression(Binder binder, ExpressionSyntax syntax, DiagnosticBag diagnostics, out ResultProperties resultProperties)
{
var flags = DkmClrCompilationResultFlags.None;
var bindingDiagnostics = new BindingDiagnosticBag(diagnostics);
// In addition to C# expressions, the native EE also supports
// type names which are bound to a representation of the type
// (but not System.Type) that the user can expand to see the
// base type. Instead, we only allow valid C# expressions.
var expression = IsDeconstruction(syntax)
? binder.BindDeconstruction((AssignmentExpressionSyntax)syntax, bindingDiagnostics, resultIsUsedOverride: true)
: binder.BindRValueWithoutTargetType(syntax, bindingDiagnostics);
if (diagnostics.HasAnyErrors())
{
resultProperties = default;
return null;
}
try
{
if (MayHaveSideEffectsVisitor.MayHaveSideEffects(expression))
{
flags |= DkmClrCompilationResultFlags.PotentialSideEffect;
}
}
catch (BoundTreeVisitor.CancelledByStackGuardException ex)
{
ex.AddAnError(diagnostics);
resultProperties = default;
return null;
}
var expressionType = expression.Type;
if (expressionType is null)
{
expression = binder.CreateReturnConversion(
syntax,
bindingDiagnostics,
expression,
RefKind.None,
binder.Compilation.GetSpecialType(SpecialType.System_Object));
if (diagnostics.HasAnyErrors())
{
resultProperties = default;
return null;
}
}
else if (expressionType.SpecialType == SpecialType.System_Void)
{
flags |= DkmClrCompilationResultFlags.ReadOnlyResult;
Debug.Assert(expression.ConstantValue == null);
resultProperties = expression.ExpressionSymbol.GetResultProperties(flags, isConstant: false);
return new BoundExpressionStatement(syntax, expression) { WasCompilerGenerated = true };
}
else if (expressionType.SpecialType == SpecialType.System_Boolean)
{
flags |= DkmClrCompilationResultFlags.BoolResult;
}
if (!IsAssignableExpression(binder, expression))
{
flags |= DkmClrCompilationResultFlags.ReadOnlyResult;
}
resultProperties = expression.ExpressionSymbol.GetResultProperties(flags, expression.ConstantValue != null);
return new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true };
}
private static bool IsDeconstruction(ExpressionSyntax syntax)
{
if (syntax.Kind() != SyntaxKind.SimpleAssignmentExpression)
{
return false;
}
var node = (AssignmentExpressionSyntax)syntax;
return node.Left.Kind() == SyntaxKind.TupleExpression || node.Left.Kind() == SyntaxKind.DeclarationExpression;
}
private static BoundStatement BindStatement(Binder binder, StatementSyntax syntax, DiagnosticBag diagnostics, out ResultProperties properties)
{
properties = new ResultProperties(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult);
return binder.BindStatement(syntax, new BindingDiagnosticBag(diagnostics));
}
private static bool IsAssignableExpression(Binder binder, BoundExpression expression)
{
var result = binder.CheckValueKind(expression.Syntax, expression, Binder.BindValueKind.Assignable, checkingReceiver: false, BindingDiagnosticBag.Discarded);
return result;
}
private static BoundStatement? BindAssignment(Binder binder, ExpressionSyntax syntax, DiagnosticBag diagnostics)
{
var expression = binder.BindValue(syntax, new BindingDiagnosticBag(diagnostics), Binder.BindValueKind.RValue);
if (diagnostics.HasAnyErrors())
{
return null;
}
return new BoundExpressionStatement(expression.Syntax, expression) { WasCompilerGenerated = true };
}
private static Binder CreateBinderChain(
CSharpCompilation compilation,
NamespaceSymbol @namespace,
ImmutableArray<ImmutableArray<ImportRecord>> importRecordGroups)
{
var stack = ArrayBuilder<string>.GetInstance();
while (@namespace is object)
{
stack.Push(@namespace.Name);
@namespace = @namespace.ContainingNamespace;
}
Binder binder = new BuckStopsHereBinder(compilation);
var hasImports = !importRecordGroups.IsDefaultOrEmpty;
var numImportStringGroups = hasImports ? importRecordGroups.Length : 0;
var currentStringGroup = numImportStringGroups - 1;
// PERF: We used to call compilation.GetCompilationNamespace on every iteration,
// but that involved walking up to the global namespace, which we have to do
// anyway. Instead, we'll inline the functionality into our own walk of the
// namespace chain.
@namespace = compilation.GlobalNamespace;
while (stack.Count > 0)
{
var namespaceName = stack.Pop();
if (namespaceName.Length > 0)
{
// We're re-getting the namespace, rather than using the one containing
// the current frame method, because we want the merged namespace.
@namespace = @namespace.GetNestedNamespace(namespaceName);
RoslynDebug.AssertNotNull(@namespace);
}
else
{
Debug.Assert((object)@namespace == compilation.GlobalNamespace);
}
if (hasImports)
{
if (currentStringGroup < 0)
{
Debug.WriteLine($"No import string group for namespace '{@namespace}'");
break;
}
var importsBinder = new InContainerBinder(@namespace, binder);
Imports imports = BuildImports(compilation, importRecordGroups[currentStringGroup], importsBinder);
currentStringGroup--;
binder = WithExternAndUsingAliasesBinder.Create(imports.ExternAliases, imports.UsingAliases, WithUsingNamespacesAndTypesBinder.Create(imports.Usings, binder));
}
binder = new InContainerBinder(@namespace, binder);
}
stack.Free();
if (currentStringGroup >= 0)
{
// CONSIDER: We could lump these into the outermost namespace. It's probably not worthwhile since
// the usings are already for the wrong method.
Debug.WriteLine($"Found {currentStringGroup + 1} import string groups without corresponding namespaces");
}
return binder;
}
private static CSharpCompilation GetCompilationWithExternAliases(CSharpCompilation compilation, ImmutableArray<ExternAliasRecord> externAliasRecords)
{
if (externAliasRecords.IsDefaultOrEmpty)
{
return compilation.Clone();
}
var updatedReferences = ArrayBuilder<MetadataReference>.GetInstance();
var assembliesAndModulesBuilder = ArrayBuilder<Symbol>.GetInstance();
foreach (var reference in compilation.References)
{
updatedReferences.Add(reference);
assembliesAndModulesBuilder.Add(compilation.GetAssemblyOrModuleSymbol(reference)!);
}
Debug.Assert(assembliesAndModulesBuilder.Count == updatedReferences.Count);
var assembliesAndModules = assembliesAndModulesBuilder.ToImmutableAndFree();
foreach (var externAliasRecord in externAliasRecords)
{
var targetAssembly = externAliasRecord.TargetAssembly as AssemblySymbol;
int index;
if (targetAssembly != null)
{
index = assembliesAndModules.IndexOf(targetAssembly);
}
else
{
index = IndexOfMatchingAssembly((AssemblyIdentity)externAliasRecord.TargetAssembly, assembliesAndModules, compilation.Options.AssemblyIdentityComparer);
}
if (index < 0)
{
Debug.WriteLine($"Unable to find corresponding assembly reference for extern alias '{externAliasRecord}'");
continue;
}
var externAlias = externAliasRecord.Alias;
var assemblyReference = updatedReferences[index];
var oldAliases = assemblyReference.Properties.Aliases;
var newAliases = oldAliases.IsEmpty
? ImmutableArray.Create(MetadataReferenceProperties.GlobalAlias, externAlias)
: oldAliases.Concat(ImmutableArray.Create(externAlias));
// NOTE: Dev12 didn't emit custom debug info about "global", so we don't have
// a good way to distinguish between a module aliased with both (e.g.) "X" and
// "global" and a module aliased with only "X". As in Dev12, we assume that
// "global" is a valid alias to remain at least as permissive as source.
// NOTE: In the event that this introduces ambiguities between two assemblies
// (e.g. because one was "global" in source and the other was "X"), it should be
// possible to disambiguate as long as each assembly has a distinct extern alias,
// not necessarily used in source.
Debug.Assert(newAliases.Contains(MetadataReferenceProperties.GlobalAlias));
// Replace the value in the map with the updated reference.
updatedReferences[index] = assemblyReference.WithAliases(newAliases);
}
compilation = compilation.WithReferences(updatedReferences);
updatedReferences.Free();
return compilation;
}
private static int IndexOfMatchingAssembly(AssemblyIdentity referenceIdentity, ImmutableArray<Symbol> assembliesAndModules, AssemblyIdentityComparer assemblyIdentityComparer)
{
for (int i = 0; i < assembliesAndModules.Length; i++)
{
if (assembliesAndModules[i] is AssemblySymbol assembly && assemblyIdentityComparer.ReferenceMatchesDefinition(referenceIdentity, assembly.Identity))
{
return i;
}
}
return -1;
}
private static Binder ExtendBinderChain(
CSharpSyntaxNode syntax,
ImmutableArray<Alias> aliases,
EEMethodSymbol method,
Binder binder,
bool hasDisplayClassThis,
bool methodNotType,
out ImmutableArray<LocalSymbol> declaredLocals)
{
var substitutedSourceMethod = GetSubstitutedSourceMethod(method.SubstitutedSourceMethod, hasDisplayClassThis);
var substitutedSourceType = substitutedSourceMethod.ContainingType;
var stack = ArrayBuilder<NamedTypeSymbol>.GetInstance();
for (var type = substitutedSourceType; type is object; type = type.ContainingType)
{
stack.Add(type);
}
while (stack.Count > 0)
{
substitutedSourceType = stack.Pop();
binder = new InContainerBinder(substitutedSourceType, binder);
if (substitutedSourceType.Arity > 0)
{
binder = new WithTypeArgumentsBinder(substitutedSourceType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics, binder);
}
}
stack.Free();
if (substitutedSourceMethod.Arity > 0)
{
binder = new WithTypeArgumentsBinder(substitutedSourceMethod.TypeArgumentsWithAnnotations, binder);
}
// Method locals and parameters shadow pseudo-variables.
// That is why we place PlaceholderLocalBinder and ExecutableCodeBinder before EEMethodBinder.
if (methodNotType)
{
var typeNameDecoder = new EETypeNameDecoder(binder.Compilation, (PEModuleSymbol)substitutedSourceMethod.ContainingModule);
binder = new PlaceholderLocalBinder(
syntax,
aliases,
method,
typeNameDecoder,
binder);
}
binder = new EEMethodBinder(method, substitutedSourceMethod, binder);
if (methodNotType)
{
binder = new SimpleLocalScopeBinder(method.LocalsForBinding, binder);
}
Binder? actualRootBinder = null;
SyntaxNode? declaredLocalsScopeDesignator = null;
var executableBinder = new ExecutableCodeBinder(syntax, substitutedSourceMethod, binder,
(rootBinder, declaredLocalsScopeDesignatorOpt) =>
{
actualRootBinder = rootBinder;
declaredLocalsScopeDesignator = declaredLocalsScopeDesignatorOpt;
});
// We just need to trigger the process of building the binder map
// so that the lambda above was executed.
executableBinder.GetBinder(syntax);
RoslynDebug.AssertNotNull(actualRootBinder);
if (declaredLocalsScopeDesignator != null)
{
declaredLocals = actualRootBinder.GetDeclaredLocalsForScope(declaredLocalsScopeDesignator);
}
else
{
declaredLocals = ImmutableArray<LocalSymbol>.Empty;
}
return actualRootBinder;
}
private static Imports BuildImports(CSharpCompilation compilation, ImmutableArray<ImportRecord> importRecords, InContainerBinder binder)
{
// We make a first pass to extract all of the extern aliases because other imports may depend on them.
var externsBuilder = ArrayBuilder<AliasAndExternAliasDirective>.GetInstance();
foreach (var importRecord in importRecords)
{
if (importRecord.TargetKind != ImportTargetKind.Assembly)
{
continue;
}
var alias = importRecord.Alias;
RoslynDebug.AssertNotNull(alias);
if (!TryParseIdentifierNameSyntax(alias, out var aliasNameSyntax))
{
Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid extern alias '{alias}'");
continue;
}
NamespaceSymbol target;
compilation.GetExternAliasTarget(aliasNameSyntax.Identifier.ValueText, out target);
Debug.Assert(target.IsGlobalNamespace);
var aliasSymbol = AliasSymbol.CreateCustomDebugInfoAlias(target, aliasNameSyntax.Identifier, binder.ContainingMemberOrLambda, isExtern: true);
externsBuilder.Add(new AliasAndExternAliasDirective(aliasSymbol, externAliasDirective: null, skipInLookup: false));
}
var externs = externsBuilder.ToImmutableAndFree();
if (externs.Any())
{
// NB: This binder (and corresponding Imports) is only used to bind the other imports.
// We'll merge the externs into a final Imports object and return that to be used in
// the actual binder chain.
binder = new InContainerBinder(
binder.Container,
WithExternAliasesBinder.Create(externs, binder));
}
var usingAliases = ImmutableDictionary.CreateBuilder<string, AliasAndUsingDirective>();
var usingsBuilder = ArrayBuilder<NamespaceOrTypeAndUsingDirective>.GetInstance();
foreach (var importRecord in importRecords)
{
switch (importRecord.TargetKind)
{
case ImportTargetKind.Type:
{
var typeSymbol = (TypeSymbol?)importRecord.TargetType;
RoslynDebug.AssertNotNull(typeSymbol);
if (typeSymbol.IsErrorType())
{
// Type is unrecognized. The import may have been
// valid in the original source but unnecessary.
continue; // Don't add anything for this import.
}
else if (importRecord.Alias == null && !typeSymbol.IsStatic)
{
// Only static types can be directly imported.
continue;
}
if (!TryAddImport(importRecord.Alias, typeSymbol, usingsBuilder, usingAliases, binder, importRecord))
{
continue;
}
break;
}
case ImportTargetKind.Namespace:
{
var namespaceName = importRecord.TargetString;
RoslynDebug.AssertNotNull(namespaceName);
if (!SyntaxHelpers.TryParseDottedName(namespaceName, out _))
{
// DevDiv #999086: Some previous version of VS apparently generated type aliases as "UA{alias} T{alias-qualified type name}".
// Neither Roslyn nor Dev12 parses such imports. However, Roslyn discards them, rather than interpreting them as "UA{alias}"
// (which will rarely work and never be correct).
Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid target '{importRecord.TargetString}'");
continue;
}
NamespaceSymbol globalNamespace;
var targetAssembly = (AssemblySymbol?)importRecord.TargetAssembly;
if (targetAssembly is object)
{
if (targetAssembly.IsMissing)
{
Debug.WriteLine($"Import record '{importRecord}' has invalid assembly reference '{targetAssembly.Identity}'");
continue;
}
globalNamespace = targetAssembly.GlobalNamespace;
}
else if (importRecord.TargetAssemblyAlias != null)
{
if (!TryParseIdentifierNameSyntax(importRecord.TargetAssemblyAlias, out var externAliasSyntax))
{
Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid extern alias '{importRecord.TargetAssemblyAlias}'");
continue;
}
var aliasSymbol = (AliasSymbol)binder.BindNamespaceAliasSymbol(externAliasSyntax, BindingDiagnosticBag.Discarded);
if (aliasSymbol is null)
{
Debug.WriteLine($"Import record '{importRecord}' requires unknown extern alias '{importRecord.TargetAssemblyAlias}'");
continue;
}
globalNamespace = (NamespaceSymbol)aliasSymbol.Target;
}
else
{
globalNamespace = compilation.GlobalNamespace;
}
var namespaceSymbol = BindNamespace(namespaceName, globalNamespace);
if (namespaceSymbol is null)
{
// Namespace is unrecognized. The import may have been
// valid in the original source but unnecessary.
continue; // Don't add anything for this import.
}
if (!TryAddImport(importRecord.Alias, namespaceSymbol, usingsBuilder, usingAliases, binder, importRecord))
{
continue;
}
break;
}
case ImportTargetKind.Assembly:
// Handled in first pass (above).
break;
default:
throw ExceptionUtilities.UnexpectedValue(importRecord.TargetKind);
}
}
return Imports.Create(usingAliases.ToImmutableDictionary(), usingsBuilder.ToImmutableAndFree(), externs);
}
private static NamespaceSymbol? BindNamespace(string namespaceName, NamespaceSymbol globalNamespace)
{
NamespaceSymbol? namespaceSymbol = globalNamespace;
foreach (var name in namespaceName.Split('.'))
{
var members = namespaceSymbol.GetMembers(name);
namespaceSymbol = (members.Length == 1) ? members[0] as NamespaceSymbol : null;
if (namespaceSymbol is null)
{
break;
}
}
return namespaceSymbol;
}
private static bool TryAddImport(
string? alias,
NamespaceOrTypeSymbol targetSymbol,
ArrayBuilder<NamespaceOrTypeAndUsingDirective> usingsBuilder,
ImmutableDictionary<string, AliasAndUsingDirective>.Builder usingAliases,
InContainerBinder binder,
ImportRecord importRecord)
{
if (alias == null)
{
usingsBuilder.Add(new NamespaceOrTypeAndUsingDirective(targetSymbol, usingDirective: null, dependencies: default));
}
else
{
if (!TryParseIdentifierNameSyntax(alias, out var aliasSyntax))
{
Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid alias '{alias}'");
return false;
}
var aliasSymbol = AliasSymbol.CreateCustomDebugInfoAlias(targetSymbol, aliasSyntax.Identifier, binder.ContainingMemberOrLambda, isExtern: false);
usingAliases.Add(alias, new AliasAndUsingDirective(aliasSymbol, usingDirective: null));
}
return true;
}
private static bool TryParseIdentifierNameSyntax(string name, [NotNullWhen(true)] out IdentifierNameSyntax? syntax)
{
if (name == MetadataReferenceProperties.GlobalAlias)
{
syntax = SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword));
return true;
}
if (!SyntaxHelpers.TryParseDottedName(name, out var nameSyntax) || nameSyntax.Kind() != SyntaxKind.IdentifierName)
{
syntax = null;
return false;
}
syntax = (IdentifierNameSyntax)nameSyntax;
return true;
}
internal CommonMessageProvider MessageProvider
{
get { return Compilation.MessageProvider; }
}
private static DkmClrCompilationResultFlags GetLocalResultFlags(LocalSymbol local)
{
// CONSIDER: We might want to prevent the user from modifying pinned locals -
// that's pretty dangerous.
return local.IsConst
? DkmClrCompilationResultFlags.ReadOnlyResult
: DkmClrCompilationResultFlags.None;
}
/// <summary>
/// Generate the set of locals to use for binding.
/// </summary>
private static ImmutableArray<LocalSymbol> GetLocalsForBinding(
ImmutableArray<LocalSymbol> locals,
ImmutableArray<string> displayClassVariableNamesInOrder,
ImmutableDictionary<string, DisplayClassVariable> displayClassVariables)
{
var builder = ArrayBuilder<LocalSymbol>.GetInstance();
foreach (var local in locals)
{
var name = local.Name;
if (name == null)
{
continue;
}
if (GeneratedNames.GetKind(name) != GeneratedNameKind.None)
{
continue;
}
// Although Roslyn doesn't name synthesized locals unless they are well-known to EE,
// Dev12 did so we need to skip them here.
if (GeneratedNames.IsSynthesizedLocalName(name))
{
continue;
}
builder.Add(local);
}
foreach (var variableName in displayClassVariableNamesInOrder)
{
var variable = displayClassVariables[variableName];
switch (variable.Kind)
{
case DisplayClassVariableKind.Local:
case DisplayClassVariableKind.Parameter:
builder.Add(new EEDisplayClassFieldLocalSymbol(variable));
break;
}
}
return builder.ToImmutableAndFree();
}
private static ImmutableArray<string> GetSourceMethodParametersInOrder(
MethodSymbol method,
MethodSymbol? sourceMethod)
{
var containingType = method.ContainingType;
bool isIteratorOrAsyncMethod = IsDisplayClassType(containingType) &&
GeneratedNames.GetKind(containingType.Name) == GeneratedNameKind.StateMachineType;
var parameterNamesInOrder = ArrayBuilder<string>.GetInstance();
// For version before .NET 4.5, we cannot find the sourceMethod properly:
// The source method coincides with the original method in the case.
// Therefore, for iterators and async state machines, we have to get parameters from the containingType.
// This does not guarantee the proper order of parameters.
if (isIteratorOrAsyncMethod && method == sourceMethod)
{
Debug.Assert(IsDisplayClassType(containingType));
foreach (var member in containingType.GetMembers())
{
if (member.Kind != SymbolKind.Field)
{
continue;
}
var field = (FieldSymbol)member;
var fieldName = field.Name;
if (GeneratedNames.GetKind(fieldName) == GeneratedNameKind.None)
{
parameterNamesInOrder.Add(fieldName);
}
}
}
else
{
if (sourceMethod is object)
{
foreach (var p in sourceMethod.Parameters)
{
parameterNamesInOrder.Add(p.Name);
}
}
}
return parameterNamesInOrder.ToImmutableAndFree();
}
/// <summary>
/// Return a mapping of captured variables (parameters, locals, and
/// "this") to locals. The mapping is needed to expose the original
/// local identifiers (those from source) in the binder.
/// </summary>
private static void GetDisplayClassVariables(
MethodSymbol method,
ImmutableArray<LocalSymbol> locals,
ImmutableSortedSet<int> inScopeHoistedLocalSlots,
ImmutableArray<string> parameterNamesInOrder,
out ImmutableArray<string> displayClassVariableNamesInOrder,
out ImmutableDictionary<string, DisplayClassVariable> displayClassVariables)
{
// Calculate the shortest paths from locals to instances of display
// classes. There should not be two instances of the same display
// class immediately within any particular method.
var displayClassInstances = ArrayBuilder<DisplayClassInstanceAndFields>.GetInstance();
foreach (var parameter in method.Parameters)
{
if (GeneratedNames.GetKind(parameter.Name) == GeneratedNameKind.TransparentIdentifier ||
IsDisplayClassParameter(parameter))
{
var instance = new DisplayClassInstanceFromParameter(parameter);
displayClassInstances.Add(new DisplayClassInstanceAndFields(instance));
}
}
if (IsDisplayClassType(method.ContainingType) && !method.IsStatic)
{
// Add "this" display class instance.
var instance = new DisplayClassInstanceFromParameter(method.ThisParameter);
displayClassInstances.Add(new DisplayClassInstanceAndFields(instance));
}
var displayClassTypes = PooledHashSet<TypeSymbol>.GetInstance();
foreach (var instance in displayClassInstances)
{
displayClassTypes.Add(instance.Instance.Type);
}
// Find any additional display class instances.
GetAdditionalDisplayClassInstances(displayClassTypes, displayClassInstances, startIndex: 0);
// Add any display class instances from locals (these will contain any hoisted locals).
// Locals are only added after finding all display class instances reachable from
// parameters because locals may be null (temporary locals in async state machine
// for instance) so we prefer parameters to locals.
int startIndex = displayClassInstances.Count;
foreach (var local in locals)
{
var name = local.Name;
if (name != null && GeneratedNames.GetKind(name) == GeneratedNameKind.DisplayClassLocalOrField)
{
var localType = local.Type;
if (localType is object && displayClassTypes.Add(localType))
{
var instance = new DisplayClassInstanceFromLocal((EELocalSymbol)local);
displayClassInstances.Add(new DisplayClassInstanceAndFields(instance));
}
}
}
GetAdditionalDisplayClassInstances(displayClassTypes, displayClassInstances, startIndex);
displayClassTypes.Free();
if (displayClassInstances.Any())
{
var parameterNames = PooledHashSet<string>.GetInstance();
foreach (var name in parameterNamesInOrder)
{
parameterNames.Add(name);
}
// The locals are the set of all fields from the display classes.
var displayClassVariableNamesInOrderBuilder = ArrayBuilder<string>.GetInstance();
var displayClassVariablesBuilder = PooledDictionary<string, DisplayClassVariable>.GetInstance();
foreach (var instance in displayClassInstances)
{
GetDisplayClassVariables(
displayClassVariableNamesInOrderBuilder,
displayClassVariablesBuilder,
parameterNames,
inScopeHoistedLocalSlots,
instance);
}
displayClassVariableNamesInOrder = displayClassVariableNamesInOrderBuilder.ToImmutableAndFree();
displayClassVariables = displayClassVariablesBuilder.ToImmutableDictionary();
displayClassVariablesBuilder.Free();
parameterNames.Free();
}
else
{
displayClassVariableNamesInOrder = ImmutableArray<string>.Empty;
displayClassVariables = ImmutableDictionary<string, DisplayClassVariable>.Empty;
}
displayClassInstances.Free();
}
private static void GetAdditionalDisplayClassInstances(
HashSet<TypeSymbol> displayClassTypes,
ArrayBuilder<DisplayClassInstanceAndFields> displayClassInstances,
int startIndex)
{
// Find any additional display class instances breadth first.
for (int i = startIndex; i < displayClassInstances.Count; i++)
{
GetDisplayClassInstances(displayClassTypes, displayClassInstances, displayClassInstances[i]);
}
}
private static void GetDisplayClassInstances(
HashSet<TypeSymbol> displayClassTypes,
ArrayBuilder<DisplayClassInstanceAndFields> displayClassInstances,
DisplayClassInstanceAndFields instance)
{
// Display class instance. The display class fields are variables.
foreach (var member in instance.Type.GetMembers())
{
if (member.Kind != SymbolKind.Field)
{
continue;
}
var field = (FieldSymbol)member;
var fieldType = field.Type;
var fieldName = field.Name;
TryParseGeneratedName(fieldName, out var fieldKind, out var part);
switch (fieldKind)
{
case GeneratedNameKind.DisplayClassLocalOrField:
case GeneratedNameKind.TransparentIdentifier:
break;
case GeneratedNameKind.AnonymousTypeField:
if (GeneratedNames.GetKind(part) != GeneratedNameKind.TransparentIdentifier)
{
continue;
}
break;
case GeneratedNameKind.ThisProxyField:
if (GeneratedNames.GetKind(fieldType.Name) != GeneratedNameKind.LambdaDisplayClass)
{
continue;
}
// Async lambda case.
break;
default:
continue;
}
Debug.Assert(!field.IsStatic);
// A hoisted local that is itself a display class instance.
if (displayClassTypes.Add(fieldType))
{
var other = instance.FromField(field);
displayClassInstances.Add(other);
}
}
}
/// <summary>
/// Returns true if the parameter is a synthesized parameter representing
/// a display class instance (used to pass hoisted symbols to local functions).
/// </summary>
private static bool IsDisplayClassParameter(ParameterSymbol parameter)
{
var type = parameter.Type;
var result = type.Kind == SymbolKind.NamedType && IsDisplayClassType((NamedTypeSymbol)type);
Debug.Assert(!result || parameter.MetadataName == "");
return result;
}
private static void GetDisplayClassVariables(
ArrayBuilder<string> displayClassVariableNamesInOrderBuilder,
Dictionary<string, DisplayClassVariable> displayClassVariablesBuilder,
HashSet<string> parameterNames,
ImmutableSortedSet<int> inScopeHoistedLocalSlots,
DisplayClassInstanceAndFields instance)
{
// Display class instance. The display class fields are variables.
foreach (var member in instance.Type.GetMembers())
{
if (member.Kind != SymbolKind.Field)
{
continue;
}
var field = (FieldSymbol)member;
var fieldName = field.Name;
REPARSE:
DisplayClassVariableKind variableKind;
string variableName;
TryParseGeneratedName(fieldName, out var fieldKind, out var part);
switch (fieldKind)
{
case GeneratedNameKind.AnonymousTypeField:
RoslynDebug.AssertNotNull(part);
Debug.Assert(fieldName == field.Name); // This only happens once.
fieldName = part;
goto REPARSE;
case GeneratedNameKind.TransparentIdentifier:
// A transparent identifier (field) in an anonymous type synthesized for a transparent identifier.
Debug.Assert(!field.IsStatic);
continue;
case GeneratedNameKind.DisplayClassLocalOrField:
// A local that is itself a display class instance.
Debug.Assert(!field.IsStatic);
continue;
case GeneratedNameKind.HoistedLocalField:
RoslynDebug.AssertNotNull(part);
// Filter out hoisted locals that are known to be out-of-scope at the current IL offset.
// Hoisted locals with invalid indices will be included since more information is better
// than less in error scenarios.
if (GeneratedNames.TryParseSlotIndex(fieldName, out int slotIndex) &&
!inScopeHoistedLocalSlots.Contains(slotIndex))
{
continue;
}
variableName = part;
variableKind = DisplayClassVariableKind.Local;
Debug.Assert(!field.IsStatic);
break;
case GeneratedNameKind.ThisProxyField:
// A reference to "this".
variableName = ""; // Should not be referenced by name.
variableKind = DisplayClassVariableKind.This;
Debug.Assert(!field.IsStatic);
break;
case GeneratedNameKind.None:
// A reference to a parameter or local.
variableName = fieldName;
variableKind = parameterNames.Contains(variableName) ? DisplayClassVariableKind.Parameter : DisplayClassVariableKind.Local;
Debug.Assert(!field.IsStatic);
break;
default:
continue;
}
if (displayClassVariablesBuilder.ContainsKey(variableName))
{
// Only expecting duplicates for async state machine
// fields (that should be at the top-level).
Debug.Assert(displayClassVariablesBuilder[variableName].DisplayClassFields.Count() == 1);
if (!instance.Fields.Any())
{
// Prefer parameters over locals.
Debug.Assert(instance.Instance is DisplayClassInstanceFromLocal);
}
else
{
Debug.Assert(instance.Fields.Count() >= 1); // greater depth
Debug.Assert(variableKind == DisplayClassVariableKind.Parameter || variableKind == DisplayClassVariableKind.This);
if (variableKind == DisplayClassVariableKind.Parameter && GeneratedNames.GetKind(instance.Type.Name) == GeneratedNameKind.LambdaDisplayClass)
{
displayClassVariablesBuilder[variableName] = instance.ToVariable(variableName, variableKind, field);
}
}
}
else if (variableKind != DisplayClassVariableKind.This || GeneratedNames.GetKind(instance.Type.ContainingType.Name) != GeneratedNameKind.LambdaDisplayClass)
{
// In async lambdas, the hoisted "this" field in the state machine type will point to the display class instance, if there is one.
// In such cases, we want to add the display class "this" to the map instead (or nothing, if it lacks one).
displayClassVariableNamesInOrderBuilder.Add(variableName);
displayClassVariablesBuilder.Add(variableName, instance.ToVariable(variableName, variableKind, field));
}
}
}
private static void TryParseGeneratedName(string name, out GeneratedNameKind kind, out string? part)
{
_ = GeneratedNames.TryParseGeneratedName(name, out kind, out int openBracketOffset, out int closeBracketOffset);
switch (kind)
{
case GeneratedNameKind.AnonymousTypeField:
case GeneratedNameKind.HoistedLocalField:
part = name.Substring(openBracketOffset + 1, closeBracketOffset - openBracketOffset - 1);
break;
default:
part = null;
break;
}
}
private static bool IsDisplayClassType(TypeSymbol type)
{
switch (GeneratedNames.GetKind(type.Name))
{
case GeneratedNameKind.LambdaDisplayClass:
case GeneratedNameKind.StateMachineType:
return true;
default:
return false;
}
}
internal static DisplayClassVariable GetThisProxy(ImmutableDictionary<string, DisplayClassVariable> displayClassVariables)
{
return displayClassVariables.Values.FirstOrDefault(v => v.Kind == DisplayClassVariableKind.This);
}
private static NamedTypeSymbol GetNonDisplayClassContainer(NamedTypeSymbol type)
{
// 1) Display class and state machine types are always nested within the types
// that use them (so that they can access private members of those types).
// 2) The native compiler used to produce nested display classes for nested lambdas,
// so we may have to walk out more than one level.
while (IsDisplayClassType(type))
{
type = type.ContainingType!;
}
return type;
}
/// <summary>
/// Identifies the method in which binding should occur.
/// </summary>
/// <param name="candidateSubstitutedSourceMethod">
/// The symbol of the method that is currently on top of the callstack, with
/// EE type parameters substituted in place of the original type parameters.
/// </param>
/// <param name="sourceMethodMustBeInstance">
/// True if "this" is available via a display class in the current context.
/// </param>
/// <returns>
/// If <paramref name="candidateSubstitutedSourceMethod"/> is compiler-generated,
/// then we will attempt to determine which user-defined method caused it to be
/// generated. For example, if <paramref name="candidateSubstitutedSourceMethod"/>
/// is a state machine MoveNext method, then we will try to find the iterator or
/// async method for which it was generated. If we are able to find the original
/// method, then we will substitute in the EE type parameters. Otherwise, we will
/// return <paramref name="candidateSubstitutedSourceMethod"/>.
/// </returns>
/// <remarks>
/// In the event that the original method is overloaded, we may not be able to determine
/// which overload actually corresponds to the state machine. In particular, we do not
/// have information about the signature of the original method (i.e. number of parameters,
/// parameter types and ref-kinds, return type). However, we conjecture that this
/// level of uncertainty is acceptable, since parameters are managed by a separate binder
/// in the synthesized binder chain and we have enough information to check the other method
/// properties that are used during binding (e.g. static-ness, generic arity, type parameter
/// constraints).
/// </remarks>
internal static MethodSymbol GetSubstitutedSourceMethod(
MethodSymbol candidateSubstitutedSourceMethod,
bool sourceMethodMustBeInstance)
{
var candidateSubstitutedSourceType = candidateSubstitutedSourceMethod.ContainingType;
string desiredMethodName;
if (GeneratedNames.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceType.Name, GeneratedNameKind.StateMachineType, out desiredMethodName) ||
GeneratedNames.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceMethod.Name, GeneratedNameKind.LambdaMethod, out desiredMethodName) ||
GeneratedNames.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceMethod.Name, GeneratedNameKind.LocalFunction, out desiredMethodName))
{
// We could be in the MoveNext method of an async lambda.
string tempMethodName;
if (GeneratedNames.TryParseSourceMethodNameFromGeneratedName(desiredMethodName, GeneratedNameKind.LambdaMethod, out tempMethodName) ||
GeneratedNames.TryParseSourceMethodNameFromGeneratedName(desiredMethodName, GeneratedNameKind.LocalFunction, out tempMethodName))
{
desiredMethodName = tempMethodName;
var containing = candidateSubstitutedSourceType.ContainingType;
RoslynDebug.AssertNotNull(containing);
if (GeneratedNames.GetKind(containing.Name) == GeneratedNameKind.LambdaDisplayClass)
{
candidateSubstitutedSourceType = containing;
sourceMethodMustBeInstance = candidateSubstitutedSourceType.MemberNames.Select(GeneratedNames.GetKind).Contains(GeneratedNameKind.ThisProxyField);
}
}
var desiredTypeParameters = candidateSubstitutedSourceType.OriginalDefinition.TypeParameters;
// Type containing the original iterator, async, or lambda-containing method.
var substitutedSourceType = GetNonDisplayClassContainer(candidateSubstitutedSourceType);
foreach (var candidateMethod in substitutedSourceType.GetMembers().OfType<MethodSymbol>())
{
if (IsViableSourceMethod(candidateMethod, desiredMethodName, desiredTypeParameters, sourceMethodMustBeInstance))
{
return desiredTypeParameters.Length == 0
? candidateMethod
: candidateMethod.Construct(candidateSubstitutedSourceType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics);
}
}
Debug.Fail("Why didn't we find a substituted source method for " + candidateSubstitutedSourceMethod + "?");
}
return candidateSubstitutedSourceMethod;
}
private static bool IsViableSourceMethod(
MethodSymbol candidateMethod,
string desiredMethodName,
ImmutableArray<TypeParameterSymbol> desiredTypeParameters,
bool desiredMethodMustBeInstance)
{
return
!candidateMethod.IsAbstract &&
!(desiredMethodMustBeInstance && candidateMethod.IsStatic) &&
candidateMethod.Name == desiredMethodName &&
HaveSameConstraints(candidateMethod.TypeParameters, desiredTypeParameters);
}
private static bool HaveSameConstraints(ImmutableArray<TypeParameterSymbol> candidateTypeParameters, ImmutableArray<TypeParameterSymbol> desiredTypeParameters)
{
int arity = candidateTypeParameters.Length;
if (arity != desiredTypeParameters.Length)
{
return false;
}
if (arity == 0)
{
return true;
}
var indexedTypeParameters = IndexedTypeParameterSymbol.Take(arity);
var candidateTypeMap = new TypeMap(candidateTypeParameters, indexedTypeParameters, allowAlpha: true);
var desiredTypeMap = new TypeMap(desiredTypeParameters, indexedTypeParameters, allowAlpha: true);
return MemberSignatureComparer.HaveSameConstraints(candidateTypeParameters, candidateTypeMap, desiredTypeParameters, desiredTypeMap);
}
[DebuggerDisplay("{GetDebuggerDisplay(), nq}")]
private readonly struct DisplayClassInstanceAndFields
{
internal readonly DisplayClassInstance Instance;
internal readonly ConsList<FieldSymbol> Fields;
internal DisplayClassInstanceAndFields(DisplayClassInstance instance)
: this(instance, ConsList<FieldSymbol>.Empty)
{
Debug.Assert(IsDisplayClassType(instance.Type) ||
GeneratedNames.GetKind(instance.Type.Name) == GeneratedNameKind.AnonymousType);
}
private DisplayClassInstanceAndFields(DisplayClassInstance instance, ConsList<FieldSymbol> fields)
{
Instance = instance;
Fields = fields;
}
internal TypeSymbol Type
=> Fields.Any() ? Fields.Head.Type : Instance.Type;
internal int Depth
=> Fields.Count();
internal DisplayClassInstanceAndFields FromField(FieldSymbol field)
{
Debug.Assert(IsDisplayClassType(field.Type) ||
GeneratedNames.GetKind(field.Type.Name) == GeneratedNameKind.AnonymousType);
return new DisplayClassInstanceAndFields(Instance, Fields.Prepend(field));
}
internal DisplayClassVariable ToVariable(string name, DisplayClassVariableKind kind, FieldSymbol field)
{
return new DisplayClassVariable(name, kind, Instance, Fields.Prepend(field));
}
private string GetDebuggerDisplay()
{
return Instance.GetDebuggerDisplay(Fields);
}
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./docs/contributing/Building, Debugging, and Testing on Unix.md | # Building, Debugging and Testing on Unix
This guide is meant to help developers setup an environment for debugging / contributing to Roslyn from Linux.
Particularly for developers who aren't experienced with .NET Core development on Linux.
## Working with the code
1. Ensure the commands `git` and `curl` are available
1. Clone [email protected]:dotnet/roslyn.git
1. Run `./build.sh --restore`
1. Run `./build.sh --build`
## Working in Visual Studio Code
1. Install [VS Code](https://code.visualstudio.com/Download)
- After you install VS Code, install the [C# extension](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csharp)
- Important tip: You can look up editor commands by name by hitting *Ctrl+Shift+P*, or by hitting *Ctrl+P* and typing a `>` character. This will help you get familiar with editor commands mentioned below. On a Mac, use *⌘* instead of *Ctrl*.
2. Install a recent preview [.NET Core SDK](https://dotnet.microsoft.com/download/dotnet-core). At time of writing, Roslyn uses .NET 5 preview 8. The exact version in use is recorded in our [global.json](https://github.com/dotnet/roslyn/blob/main/global.json) file.
3. You can build from VS Code by running the *Run Build Task* command, then selecting an appropriate task such as *build* or *build current project* (the latter builds the containing project for the current file you're viewing in the editor).
4. You can run tests from VS Code by opening a test class in the editor, then using the *Run Tests in Context* and *Debug Tests in Context* editor commands. You may want to bind these commands to keyboard shortcuts that match their Visual Studio equivalents (**Ctrl+R, T** for *Run Tests in Context* and **Ctrl+R, Ctrl+T** for *Debug Tests in Context*).
## Running Tests
The unit tests can be executed by running `./build.sh --test`.
To run all tests in a single project, it's recommended to use the `dotnet test path/to/project` command.
## GitHub
The best way to clone and push is to use SSH. On Windows you typically use HTTPS and this is not directly compatible
with two factor authentication (requires a PAT). The SSH setup is much simpler and GitHub has a great HOWTO for
getting this setup.
https://help.github.com/articles/connecting-to-github-with-ssh/
## Debugging test failures
The best way to debug is using lldb with the SOS plugin. This is the same SOS as used in WinDbg and if you're familiar
with it then lldb debugging will be pretty straight forward.
The [dotnet/diagnostics](https://github.com/dotnet/diagnostics) repo has more information:
- [Getting LLDB](https://github.com/dotnet/diagnostics/blob/main/documentation/lldb/linux-instructions.md)
- [Installing SOS](https://github.com/dotnet/diagnostics/blob/main/documentation/installing-sos-instructions.md)
- [Using SOS](https://github.com/dotnet/diagnostics/blob/main/documentation/sos-debugging-extension.md)
CoreCLR also has some guidelines for specific Linux debugging scenarios:
- https://github.com/dotnet/coreclr/blob/main/Documentation/botr/xplat-minidump-generation.md
- https://github.com/dotnet/coreclr/blob/main/Documentation/building/debugging-instructions.md#debugging-core-dumps-with-lldb.
Corrections:
- LLDB and createdump must be run as root
- `dotnet tool install -g dotnet-symbol` must be run from `$HOME`
### Core Dumps
The CoreClr does not used the standard core dumping mechanisms on Linux. Instead you must specify via
environment variables that you want a core dump to be produced. The simplest setup is to do the following:
```
> export COMPlus_DbgEnableMiniDump=1
> export COMPlus_DbgMiniDumpType=4
```
This will cause full memory dumps to be produced which can then be loaded into LLDB.
A preview of [dotnet-dump](https://github.com/dotnet/diagnostics/blob/main/documentation/dotnet-dump-instructions.md) is also available for interactively creating and analyzing dumps.
### GC stress failures
When you suspect there is a GC failure related to your test then you can use the following environment variables
to help track it down.
```
> export COMPlus_HeapVerify=1
> export COMPlus_gcConcurrent=1
```
The `COMPlus_HeapVerify` variable causes GC to run a verification routine on every entry and exit. Will crash with
a more actionable trace for the GC team.
The `COMPlus_gcConcurrent` variable removes concurrency in the GC. This helps isolate whether this is a GC failure
or memory corruption outside the GC. This should be set after you use `COMPLUS_HeapVerify` to determine it is
indeed crashing in the GC.
Note: this variables can also be used on Windows as well.
## Ubuntu 18.04
The recommended OS for developing Roslyn is Ubuntu 18.04. This guide was written using Ubuntu 18.04 but should be
applicable to most Linux environments. Ubuntu 18.04 was chosen here due to it's support for enhanced VMs in Hyper-V.
This makes it easier to use from a Windows machine: full screen, copy / paste, etc ...
### Hyper-V
Hyper-V has a builtin Ubuntu 18.04 image which supports enhanced mode. Here is a tutorial for creating
such an image:
https://docs.microsoft.com/en-us/virtualization/hyper-v-on-windows/quick-start/quick-create-virtual-machine
When following this make sure to:
1. Click Installation Source and uncheck "Windows Secure Boot"
1. Complete the Ubuntu installation wizard. Full screen mode won't be available until this is done.
Overall this takes about 5-10 minutes to complete.
### Source Link
Many of the repositories that need to be built use source link and it crashes on Ubuntu 18.04 due to dependency changes.
To disable source link add the following to the `Directory.Build.props` file in the root of the repository.
``` xml
<EnableSourceControlManagerQueries>false</EnableSourceControlManagerQueries>
<EnableSourceLink>false</EnableSourceLink>
<DeterministicSourcePaths>false</DeterministicSourcePaths>
```
### Prerequisites
Make sure to install the following via `apt install`
- clang
- lldb
- cmake
- xrdp
| # Building, Debugging and Testing on Unix
This guide is meant to help developers setup an environment for debugging / contributing to Roslyn from Linux.
Particularly for developers who aren't experienced with .NET Core development on Linux.
## Working with the code
1. Ensure the commands `git` and `curl` are available
1. Clone [email protected]:dotnet/roslyn.git
1. Run `./build.sh --restore`
1. Run `./build.sh --build`
## Working in Visual Studio Code
1. Install [VS Code](https://code.visualstudio.com/Download)
- After you install VS Code, install the [C# extension](https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csharp)
- Important tip: You can look up editor commands by name by hitting *Ctrl+Shift+P*, or by hitting *Ctrl+P* and typing a `>` character. This will help you get familiar with editor commands mentioned below. On a Mac, use *⌘* instead of *Ctrl*.
2. Install a recent preview [.NET Core SDK](https://dotnet.microsoft.com/download/dotnet-core). At time of writing, Roslyn uses .NET 5 preview 8. The exact version in use is recorded in our [global.json](https://github.com/dotnet/roslyn/blob/main/global.json) file.
3. You can build from VS Code by running the *Run Build Task* command, then selecting an appropriate task such as *build* or *build current project* (the latter builds the containing project for the current file you're viewing in the editor).
4. You can run tests from VS Code by opening a test class in the editor, then using the *Run Tests in Context* and *Debug Tests in Context* editor commands. You may want to bind these commands to keyboard shortcuts that match their Visual Studio equivalents (**Ctrl+R, T** for *Run Tests in Context* and **Ctrl+R, Ctrl+T** for *Debug Tests in Context*).
## Running Tests
The unit tests can be executed by running `./build.sh --test`.
To run all tests in a single project, it's recommended to use the `dotnet test path/to/project` command.
## GitHub
The best way to clone and push is to use SSH. On Windows you typically use HTTPS and this is not directly compatible
with two factor authentication (requires a PAT). The SSH setup is much simpler and GitHub has a great HOWTO for
getting this setup.
https://help.github.com/articles/connecting-to-github-with-ssh/
## Debugging test failures
The best way to debug is using lldb with the SOS plugin. This is the same SOS as used in WinDbg and if you're familiar
with it then lldb debugging will be pretty straight forward.
The [dotnet/diagnostics](https://github.com/dotnet/diagnostics) repo has more information:
- [Getting LLDB](https://github.com/dotnet/diagnostics/blob/main/documentation/lldb/linux-instructions.md)
- [Installing SOS](https://github.com/dotnet/diagnostics/blob/main/documentation/installing-sos-instructions.md)
- [Using SOS](https://github.com/dotnet/diagnostics/blob/main/documentation/sos-debugging-extension.md)
CoreCLR also has some guidelines for specific Linux debugging scenarios:
- https://github.com/dotnet/coreclr/blob/main/Documentation/botr/xplat-minidump-generation.md
- https://github.com/dotnet/coreclr/blob/main/Documentation/building/debugging-instructions.md#debugging-core-dumps-with-lldb.
Corrections:
- LLDB and createdump must be run as root
- `dotnet tool install -g dotnet-symbol` must be run from `$HOME`
### Core Dumps
The CoreClr does not used the standard core dumping mechanisms on Linux. Instead you must specify via
environment variables that you want a core dump to be produced. The simplest setup is to do the following:
```
> export COMPlus_DbgEnableMiniDump=1
> export COMPlus_DbgMiniDumpType=4
```
This will cause full memory dumps to be produced which can then be loaded into LLDB.
A preview of [dotnet-dump](https://github.com/dotnet/diagnostics/blob/main/documentation/dotnet-dump-instructions.md) is also available for interactively creating and analyzing dumps.
### GC stress failures
When you suspect there is a GC failure related to your test then you can use the following environment variables
to help track it down.
```
> export COMPlus_HeapVerify=1
> export COMPlus_gcConcurrent=1
```
The `COMPlus_HeapVerify` variable causes GC to run a verification routine on every entry and exit. Will crash with
a more actionable trace for the GC team.
The `COMPlus_gcConcurrent` variable removes concurrency in the GC. This helps isolate whether this is a GC failure
or memory corruption outside the GC. This should be set after you use `COMPLUS_HeapVerify` to determine it is
indeed crashing in the GC.
Note: this variables can also be used on Windows as well.
## Ubuntu 18.04
The recommended OS for developing Roslyn is Ubuntu 18.04. This guide was written using Ubuntu 18.04 but should be
applicable to most Linux environments. Ubuntu 18.04 was chosen here due to it's support for enhanced VMs in Hyper-V.
This makes it easier to use from a Windows machine: full screen, copy / paste, etc ...
### Hyper-V
Hyper-V has a builtin Ubuntu 18.04 image which supports enhanced mode. Here is a tutorial for creating
such an image:
https://docs.microsoft.com/en-us/virtualization/hyper-v-on-windows/quick-start/quick-create-virtual-machine
When following this make sure to:
1. Click Installation Source and uncheck "Windows Secure Boot"
1. Complete the Ubuntu installation wizard. Full screen mode won't be available until this is done.
Overall this takes about 5-10 minutes to complete.
### Source Link
Many of the repositories that need to be built use source link and it crashes on Ubuntu 18.04 due to dependency changes.
To disable source link add the following to the `Directory.Build.props` file in the root of the repository.
``` xml
<EnableSourceControlManagerQueries>false</EnableSourceControlManagerQueries>
<EnableSourceLink>false</EnableSourceLink>
<DeterministicSourcePaths>false</DeterministicSourcePaths>
```
### Prerequisites
Make sure to install the following via `apt install`
- clang
- lldb
- cmake
- xrdp
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Interactive/HostTest/TestUtils.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
namespace Microsoft.CodeAnalysis.UnitTests.Interactive
{
internal static class TestUtils
{
public static readonly string HostRootPath = Path.Combine(Path.GetDirectoryName(typeof(TestUtils).Assembly.Location)!, "Host");
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
namespace Microsoft.CodeAnalysis.UnitTests.Interactive
{
internal static class TestUtils
{
public static readonly string HostRootPath = Path.Combine(Path.GetDirectoryName(typeof(TestUtils).Assembly.Location)!, "Host");
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/ExpressionEvaluator/Core/Source/ExpressionCompiler/PDB/ImportRecord.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Debugging;
using Microsoft.CodeAnalysis.Symbols;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal readonly struct ImportRecord
{
public readonly ImportTargetKind TargetKind;
public readonly string? Alias;
// target type of a type import (C#)
public readonly ITypeSymbolInternal? TargetType;
// target of an import (type, namespace or XML namespace) that needs to be bound (C#, VB)
public readonly string? TargetString;
// target assembly of a namespace import (C#, Portable)
public readonly IAssemblySymbolInternal? TargetAssembly;
// target assembly of a namespace import is identified by an extern alias which needs to be bound in the context (C#, native PDB)
public readonly string? TargetAssemblyAlias;
public ImportRecord(
ImportTargetKind targetKind,
string? alias = null,
ITypeSymbolInternal? targetType = null,
string? targetString = null,
IAssemblySymbolInternal? targetAssembly = null,
string? targetAssemblyAlias = null)
{
TargetKind = targetKind;
Alias = alias;
TargetType = targetType;
TargetString = targetString;
TargetAssembly = targetAssembly;
TargetAssemblyAlias = targetAssemblyAlias;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Debugging;
using Microsoft.CodeAnalysis.Symbols;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal readonly struct ImportRecord
{
public readonly ImportTargetKind TargetKind;
public readonly string? Alias;
// target type of a type import (C#)
public readonly ITypeSymbolInternal? TargetType;
// target of an import (type, namespace or XML namespace) that needs to be bound (C#, VB)
public readonly string? TargetString;
// target assembly of a namespace import (C#, Portable)
public readonly IAssemblySymbolInternal? TargetAssembly;
// target assembly of a namespace import is identified by an extern alias which needs to be bound in the context (C#, native PDB)
public readonly string? TargetAssemblyAlias;
public ImportRecord(
ImportTargetKind targetKind,
string? alias = null,
ITypeSymbolInternal? targetType = null,
string? targetString = null,
IAssemblySymbolInternal? targetAssembly = null,
string? targetAssemblyAlias = null)
{
TargetKind = targetKind;
Alias = alias;
TargetType = targetType;
TargetString = targetString;
TargetAssembly = targetAssembly;
TargetAssemblyAlias = targetAssemblyAlias;
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/VisualBasic/Portable/Diagnostics/Analyzers/VisualBasicUnboundIdentifiersDiagnosticAnalyzer.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.Diagnostics
Imports Microsoft.CodeAnalysis.Diagnostics.AddImport
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Diagnostics
<DiagnosticAnalyzer(LanguageNames.VisualBasic)>
Friend NotInheritable Class VisualBasicUnboundIdentifiersDiagnosticAnalyzer
Inherits UnboundIdentifiersDiagnosticAnalyzerBase(Of SyntaxKind, SimpleNameSyntax, QualifiedNameSyntax, IncompleteMemberSyntax)
Private ReadOnly _messageFormat As LocalizableString = New LocalizableResourceString(NameOf(VBFeaturesResources.Type_0_is_not_defined), VBFeaturesResources.ResourceManager, GetType(VBFeaturesResources))
Private Shared ReadOnly s_kindsOfInterest As ImmutableArray(Of SyntaxKind) = ImmutableArray.Create(SyntaxKind.IncompleteMember)
Protected Overrides ReadOnly Property SyntaxKindsOfInterest As ImmutableArray(Of SyntaxKind) = s_kindsOfInterest
Protected Overrides ReadOnly Property DiagnosticDescriptor As DiagnosticDescriptor
Get
Return GetDiagnosticDescriptor(IDEDiagnosticIds.UnboundIdentifierId, _messageFormat)
End Get
End Property
Protected Overrides Function IsNameOf(node As SyntaxNode) As Boolean
Return node.Kind() = SyntaxKind.NameOfKeyword
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.Diagnostics.AddImport
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Diagnostics
<DiagnosticAnalyzer(LanguageNames.VisualBasic)>
Friend NotInheritable Class VisualBasicUnboundIdentifiersDiagnosticAnalyzer
Inherits UnboundIdentifiersDiagnosticAnalyzerBase(Of SyntaxKind, SimpleNameSyntax, QualifiedNameSyntax, IncompleteMemberSyntax)
Private ReadOnly _messageFormat As LocalizableString = New LocalizableResourceString(NameOf(VBFeaturesResources.Type_0_is_not_defined), VBFeaturesResources.ResourceManager, GetType(VBFeaturesResources))
Private Shared ReadOnly s_kindsOfInterest As ImmutableArray(Of SyntaxKind) = ImmutableArray.Create(SyntaxKind.IncompleteMember)
Protected Overrides ReadOnly Property SyntaxKindsOfInterest As ImmutableArray(Of SyntaxKind) = s_kindsOfInterest
Protected Overrides ReadOnly Property DiagnosticDescriptor As DiagnosticDescriptor
Get
Return GetDiagnosticDescriptor(IDEDiagnosticIds.UnboundIdentifierId, _messageFormat)
End Get
End Property
Protected Overrides Function IsNameOf(node As SyntaxNode) As Boolean
Return node.Kind() = SyntaxKind.NameOfKeyword
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationArrayTypeSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Shared.Utilities;
namespace Microsoft.CodeAnalysis.CodeGeneration
{
internal class CodeGenerationArrayTypeSymbol : CodeGenerationTypeSymbol, IArrayTypeSymbol
{
public CodeGenerationArrayTypeSymbol(ITypeSymbol elementType, int rank, NullableAnnotation nullableAnnotation)
: base(null, null, default, Accessibility.NotApplicable, default, string.Empty, SpecialType.None, nullableAnnotation)
{
this.ElementType = elementType;
this.Rank = rank;
}
public ITypeSymbol ElementType { get; }
public int Rank { get; }
public bool IsSZArray
{
get
{
return Rank == 1;
}
}
public ImmutableArray<int> Sizes
{
get
{
return ImmutableArray<int>.Empty;
}
}
public ImmutableArray<int> LowerBounds
{
get
{
return default;
}
}
protected override CodeGenerationTypeSymbol CloneWithNullableAnnotation(NullableAnnotation nullableAnnotation)
=> new CodeGenerationArrayTypeSymbol(this.ElementType, this.Rank, nullableAnnotation);
public override TypeKind TypeKind => TypeKind.Array;
public override SymbolKind Kind => SymbolKind.ArrayType;
public override void Accept(SymbolVisitor visitor)
=> visitor.VisitArrayType(this);
public override TResult? Accept<TResult>(SymbolVisitor<TResult> visitor)
where TResult : default
=> visitor.VisitArrayType(this);
public ImmutableArray<CustomModifier> CustomModifiers
{
get
{
return ImmutableArray.Create<CustomModifier>();
}
}
public NullableAnnotation ElementNullableAnnotation => ElementType.NullableAnnotation;
public bool Equals(IArrayTypeSymbol? other)
=> SymbolEquivalenceComparer.Instance.Equals(this, other);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Shared.Utilities;
namespace Microsoft.CodeAnalysis.CodeGeneration
{
internal class CodeGenerationArrayTypeSymbol : CodeGenerationTypeSymbol, IArrayTypeSymbol
{
public CodeGenerationArrayTypeSymbol(ITypeSymbol elementType, int rank, NullableAnnotation nullableAnnotation)
: base(null, null, default, Accessibility.NotApplicable, default, string.Empty, SpecialType.None, nullableAnnotation)
{
this.ElementType = elementType;
this.Rank = rank;
}
public ITypeSymbol ElementType { get; }
public int Rank { get; }
public bool IsSZArray
{
get
{
return Rank == 1;
}
}
public ImmutableArray<int> Sizes
{
get
{
return ImmutableArray<int>.Empty;
}
}
public ImmutableArray<int> LowerBounds
{
get
{
return default;
}
}
protected override CodeGenerationTypeSymbol CloneWithNullableAnnotation(NullableAnnotation nullableAnnotation)
=> new CodeGenerationArrayTypeSymbol(this.ElementType, this.Rank, nullableAnnotation);
public override TypeKind TypeKind => TypeKind.Array;
public override SymbolKind Kind => SymbolKind.ArrayType;
public override void Accept(SymbolVisitor visitor)
=> visitor.VisitArrayType(this);
public override TResult? Accept<TResult>(SymbolVisitor<TResult> visitor)
where TResult : default
=> visitor.VisitArrayType(this);
public ImmutableArray<CustomModifier> CustomModifiers
{
get
{
return ImmutableArray.Create<CustomModifier>();
}
}
public NullableAnnotation ElementNullableAnnotation => ElementType.NullableAnnotation;
public bool Equals(IArrayTypeSymbol? other)
=> SymbolEquivalenceComparer.Instance.Equals(this, other);
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/ClsComplianceTests.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.PooledObjects
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class ClsComplianceTests
Inherits BasicTestBase
<Fact>
Public Sub NoAssemblyLevelAttributeRequired()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<CLSCompliant(True)>
Public Class A
End Class
<CLSCompliant(False)>
Public Class B
End Class
]]>
</file>
</compilation>
' In C#, an assembly-level attribute is required. In VB, that is not the case.
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub AssemblyLevelAttributeAllowed()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
<Module: CLSCompliant(True)>
<CLSCompliant(True)>
Public Class A
End Class
<CLSCompliant(False)>
Public Class B
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub AttributeAllowedOnPrivate()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<CLSCompliant(True)>
Public Class Outer
<CLSCompliant(True)>
Private Class A
End Class
<CLSCompliant(True)>
Friend Class B
End Class
<CLSCompliant(True)>
Protected Class C
End Class
<CLSCompliant(True)>
Friend Protected Class D
End Class
<CLSCompliant(True)>
Public Class E
End Class
End Class
]]>
</file>
</compilation>
' C# warns about putting the attribute on members not visible outside the assembly.
' VB does not.
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub AttributeAllowedOnParameters()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<CLSCompliant(True)>
Public Class C
Public Function M(<CLSCompliant(True)> x As Integer) As Integer
Return 0
End Function
Public ReadOnly Property P(<CLSCompliant(True)> x As Integer) As Integer
Get
Return 0
End Get
End Property
End Class
]]>
</file>
</compilation>
' C# warns about putting the attribute on parameters. VB does not.
' C# also warns about putting the attribute on return types, but VB
' does not support the "return" attribute target.
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub WRN_CLSMemberInNonCLSType3_Explicit()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<CLSCompliant(False)>
Public Class Kinds
<CLSCompliant(True)>
Public Sub M()
End Sub
<CLSCompliant(True)>
Public Property P As Integer
<CLSCompliant(True)>
Public Event E As ND
<CLSCompliant(True)>
Public F As Integer
<CLSCompliant(True)>
Public Class NC
End Class
<CLSCompliant(True)>
Public Interface NI
End Interface
<CLSCompliant(True)>
Public Structure NS
End Structure
<CLSCompliant(True)>
Public Delegate Sub ND()
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40030: sub 'Public Sub M()' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Sub M()
~
BC40030: property 'Public Property P As Integer' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Property P As Integer
~
BC40030: event 'Public Event E As Kinds.ND' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Event E As ND
~
BC40030: variable 'Public F As Integer' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public F As Integer
~
BC40030: class 'Kinds.NC' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Class NC
~~
BC40030: interface 'Kinds.NI' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Interface NI
~~
BC40030: structure 'Kinds.NS' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Structure NS
~~
BC40030: delegate Class 'Kinds.ND' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Delegate Sub ND()
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_CLSMemberInNonCLSType3_Implicit()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly:CLSCompliant(False)>
Public Class Kinds
<CLSCompliant(True)>
Public Sub M()
End Sub
<CLSCompliant(True)>
Public Property P As Integer
<CLSCompliant(True)>
Public Event E As ND
<CLSCompliant(True)>
Public F As Integer
<CLSCompliant(True)>
Public Class NC
End Class
<CLSCompliant(True)>
Public Interface NI
End Interface
<CLSCompliant(True)>
Public Structure NS
End Structure
<CLSCompliant(True)>
Public Delegate Sub ND()
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40030: sub 'Public Sub M()' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Sub M()
~
BC40030: property 'Public Property P As Integer' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Property P As Integer
~
BC40030: event 'Public Event E As Kinds.ND' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Event E As ND
~
BC40030: variable 'Public F As Integer' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public F As Integer
~
BC40030: class 'Kinds.NC' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Class NC
~~
BC40030: interface 'Kinds.NI' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Interface NI
~~
BC40030: structure 'Kinds.NS' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Structure NS
~~
BC40030: delegate Class 'Kinds.ND' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Delegate Sub ND()
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_CLSMemberInNonCLSType3_Alternating()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<CLSCompliant(True)>
Public Class A
<CLSCompliant(False)>
Public Class B
<CLSCompliant(True)>
Public Class C
<CLSCompliant(False)>
Public Class D
<CLSCompliant(True)>
Public Class E
End Class
End Class
End Class
End Class
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40030: class 'A.B.C' cannot be marked CLS-compliant because its containing type 'A.B' is not CLS-compliant.
Public Class C
~
BC40030: class 'A.B.C.D.E' cannot be marked CLS-compliant because its containing type 'A.B.C.D' is not CLS-compliant.
Public Class E
~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_BaseClassNotCLSCompliant2()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class A
Inherits Bad
End Class
<CLSCompliant(False)>
Public Class Bad
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40026: 'A' is not CLS-compliant because it derives from 'Bad', which is not CLS-compliant.
Public Class A
~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_BaseClassNotCLSCompliant2_OtherAssemblies()
Dim lib1Source =
<compilation name="lib1">
<file name="a.vb">
<![CDATA[
Public Class Bad1
End Class
]]>
</file>
</compilation>
Dim lib2Source =
<compilation name="lib2">
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
<CLSCompliant(False)>
Public Class Bad2
End Class
]]>
</file>
</compilation>
Dim lib3Source =
<compilation name="lib3">
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(False)>
Public Class Bad3
End Class
]]>
</file>
</compilation>
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class A1
Inherits Bad1
End Class
Public Class A2
Inherits Bad2
End Class
Public Class A3
Inherits Bad3
End Class
]]>
</file>
</compilation>
Dim lib1Ref = CreateCompilationWithMscorlib40(lib1Source).EmitToImageReference()
Dim lib2Ref = CreateCompilationWithMscorlib40(lib2Source).EmitToImageReference()
Dim lib3Ref = CreateCompilationWithMscorlib40(lib3Source).EmitToImageReference()
CreateCompilationWithMscorlib40AndReferences(source, {lib1Ref, lib2Ref, lib3Ref}).AssertTheseDiagnostics(<errors><![CDATA[
BC40026: 'A1' is not CLS-compliant because it derives from 'Bad1', which is not CLS-compliant.
Public Class A1
~~
BC40026: 'A2' is not CLS-compliant because it derives from 'Bad2', which is not CLS-compliant.
Public Class A2
~~
BC40026: 'A3' is not CLS-compliant because it derives from 'Bad3', which is not CLS-compliant.
Public Class A3
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_InheritedInterfaceNotCLSCompliant2_Interface()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Interface A
Inherits Bad
End Interface
Public Interface B
Inherits Bad, Good
End Interface
Public Interface C
Inherits Good, Bad
End Interface
<CLSCompliant(True)>
Public Interface Good
End Interface
<CLSCompliant(False)>
Public Interface Bad
End Interface
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40029: 'A' is not CLS-compliant because the interface 'Bad' it inherits from is not CLS-compliant.
Public Interface A
~
BC40029: 'B' is not CLS-compliant because the interface 'Bad' it inherits from is not CLS-compliant.
Public Interface B
~
BC40029: 'C' is not CLS-compliant because the interface 'Bad' it inherits from is not CLS-compliant.
Public Interface C
~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_InheritedInterfaceNotCLSCompliant2_Class()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class A
Implements Bad
End Class
Public Class B
Implements Bad, Good
End Class
Public Class C
Implements Good, Bad
End Class
<CLSCompliant(True)>
Public Interface Good
End Interface
<CLSCompliant(False)>
Public Interface Bad
End Interface
]]>
</file>
</compilation>
' Implemented interfaces are not required to be compliant - only inherited ones.
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub WRN_NonCLSMemberInCLSInterface1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Interface A
Function M1() As Bad
<CLSCompliant(False)>
Sub M2()
End Interface
Public Interface Kinds
<CLSCompliant(False)>
Sub M()
<CLSCompliant(False)>
Property P()
<CLSCompliant(False)>
Event E As Action
End Interface
<CLSCompliant(False)>
Public Class Bad
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40027: Return type of function 'M1' is not CLS-compliant.
Function M1() As Bad
~~
BC40033: Non CLS-compliant 'Sub M2()' is not allowed in a CLS-compliant interface.
Sub M2()
~~
BC40033: Non CLS-compliant 'Sub M()' is not allowed in a CLS-compliant interface.
Sub M()
~
BC40033: Non CLS-compliant 'Property P As Object' is not allowed in a CLS-compliant interface.
Property P()
~
BC40033: Non CLS-compliant 'Event E As Action' is not allowed in a CLS-compliant interface.
Event E As Action
~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_NonCLSMustOverrideInCLSType1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public MustInherit Class A
Public MustOverride Function M1() As Bad
<CLSCompliant(False)>
Public MustOverride Sub M2()
End Class
Public MustInherit Class Kinds
<CLSCompliant(False)>
Public MustOverride Sub M()
<CLSCompliant(False)>
Public MustOverride Property P()
' VB doesn't support generic events
Public MustInherit Class C
End Class
End Class
<CLSCompliant(False)>
Public Class Bad
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40027: Return type of function 'M1' is not CLS-compliant.
Public MustOverride Function M1() As Bad
~~
BC40034: Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type 'A'.
Public MustOverride Sub M2()
~~
BC40034: Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type 'Kinds'.
Public MustOverride Sub M()
~
BC40034: Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type 'Kinds'.
Public MustOverride Property P()
~
]]></errors>)
End Sub
<Fact>
Public Sub AbstractInCompliant_NoAssemblyAttribute()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<CLSCompliant(True)> Public Interface IFace
<CLSCompliant(False)> Property Prop1() As Long
<CLSCompliant(False)> Function F2() As Integer
<CLSCompliant(False)> Event EV3(ByVal i3 As Integer)
<CLSCompliant(False)> Sub Sub4()
End Interface
<CLSCompliant(True)> Public MustInherit Class QuiteCompliant
<CLSCompliant(False)> Public MustOverride Sub Sub1()
<CLSCompliant(False)> Protected MustOverride Function Fun2() As Integer
<CLSCompliant(False)> Protected Friend MustOverride Sub Sub3()
<CLSCompliant(False)> Friend MustOverride Function Fun4(ByVal x As Long) As Long
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40033: Non CLS-compliant 'Property Prop1 As Long' is not allowed in a CLS-compliant interface.
<CLSCompliant(False)> Property Prop1() As Long
~~~~~
BC40033: Non CLS-compliant 'Function F2() As Integer' is not allowed in a CLS-compliant interface.
<CLSCompliant(False)> Function F2() As Integer
~~
BC40033: Non CLS-compliant 'Event EV3(i3 As Integer)' is not allowed in a CLS-compliant interface.
<CLSCompliant(False)> Event EV3(ByVal i3 As Integer)
~~~
BC40033: Non CLS-compliant 'Sub Sub4()' is not allowed in a CLS-compliant interface.
<CLSCompliant(False)> Sub Sub4()
~~~~
BC40034: Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type 'QuiteCompliant'.
<CLSCompliant(False)> Public MustOverride Sub Sub1()
~~~~
BC40034: Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type 'QuiteCompliant'.
<CLSCompliant(False)> Protected MustOverride Function Fun2() As Integer
~~~~
BC40034: Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type 'QuiteCompliant'.
<CLSCompliant(False)> Protected Friend MustOverride Sub Sub3()
~~~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_GenericConstraintNotCLSCompliant1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C1(Of t As {Good, Bad}, u As {Bad, Good})
End Class
<CLSCompliant(False)>
Public Class C2(Of t As {Good, Bad}, u As {Bad, Good})
End Class
Public Delegate Sub D1(Of t As {Good, Bad}, u As {Bad, Good})()
<CLSCompliant(False)>
Public Delegate Sub D2(Of t As {Good, Bad}, u As {Bad, Good})()
Public Class C
Public Sub M1(Of t As {Good, Bad}, u As {Bad, Good})()
End Sub
<CLSCompliant(False)>
Public Sub M2(Of t As {Good, Bad}, u As {Bad, Good})()
End Sub
End Class
<CLSCompliant(True)>
Public Interface Good
End Interface
<CLSCompliant(False)>
Public Interface Bad
End Interface
]]>
</file>
</compilation>
' NOTE: Dev11 squiggles the problematic constraint, but we don't have enough info.
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40040: Generic parameter constraint type 'Bad' is not CLS-compliant.
Public Class C1(Of t As {Good, Bad}, u As {Bad, Good})
~
BC40040: Generic parameter constraint type 'Bad' is not CLS-compliant.
Public Class C1(Of t As {Good, Bad}, u As {Bad, Good})
~
BC40040: Generic parameter constraint type 'Bad' is not CLS-compliant.
Public Delegate Sub D1(Of t As {Good, Bad}, u As {Bad, Good})()
~
BC40040: Generic parameter constraint type 'Bad' is not CLS-compliant.
Public Delegate Sub D1(Of t As {Good, Bad}, u As {Bad, Good})()
~
BC40040: Generic parameter constraint type 'Bad' is not CLS-compliant.
Public Sub M1(Of t As {Good, Bad}, u As {Bad, Good})()
~
BC40040: Generic parameter constraint type 'Bad' is not CLS-compliant.
Public Sub M1(Of t As {Good, Bad}, u As {Bad, Good})()
~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_FieldNotCLSCompliant1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class Kinds1
Public F1 As Bad
Private F2 As Bad
End Class
<CLSCompliant(False)>
Public Class Kinds2
Public F3 As Bad
Private F4 As Bad
End Class
<CLSCompliant(False)>
Public Interface Bad
End Interface
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40025: Type of member 'F1' is not CLS-compliant.
Public F1 As Bad
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_ProcTypeNotCLSCompliant1_Method()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C1
Public Function M1() As Bad
Throw New Exception()
End Function
Public Function M2() As Generic(Of Bad)
Throw New Exception()
End Function
Public Function M3() As Generic(Of Generic(Of Bad))
Throw New Exception()
End Function
Public Function M4() As Bad()
Throw New Exception()
End Function
Public Function M5() As Bad()()
Throw New Exception()
End Function
Public Function M6() As Bad(,)
Throw New Exception()
End Function
End Class
<CLSCompliant(False)>
Public Class C2
Public Function N1() As Bad
Throw New Exception()
End Function
Public Function N2() As Generic(Of Bad)
Throw New Exception()
End Function
Public Function N3() As Generic(Of Generic(Of Bad))
Throw New Exception()
End Function
Public Function N4() As Bad()
Throw New Exception()
End Function
Public Function N5() As Bad()()
Throw New Exception()
End Function
Public Function N6() As Bad(,)
Throw New Exception()
End Function
End Class
Public Class Generic(Of T)
End Class
<CLSCompliant(False)>
Public Interface Bad
End Interface
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40027: Return type of function 'M1' is not CLS-compliant.
Public Function M1() As Bad
~~
BC40041: Type 'Bad' is not CLS-compliant.
Public Function M2() As Generic(Of Bad)
~~
BC40041: Type 'Bad' is not CLS-compliant.
Public Function M3() As Generic(Of Generic(Of Bad))
~~
BC40027: Return type of function 'M4' is not CLS-compliant.
Public Function M4() As Bad()
~~
BC40027: Return type of function 'M5' is not CLS-compliant.
Public Function M5() As Bad()()
~~
BC40027: Return type of function 'M6' is not CLS-compliant.
Public Function M6() As Bad(,)
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_ProcTypeNotCLSCompliant1_Property()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C1
Public Property P1() As Bad
Public Property P2() As Generic(Of Bad)
Public Property P3() As Generic(Of Generic(Of Bad))
Public Property P4() As Bad()
Public Property P5() As Bad()()
Public Property P6() As Bad(,)
End Class
<CLSCompliant(False)>
Public Class C2
Public Property Q1() As Bad
Public Property Q2() As Generic(Of Bad)
Public Property Q3() As Generic(Of Generic(Of Bad))
Public Property Q4() As Bad()
Public Property Q5() As Bad()()
Public Property Q6() As Bad(,)
End Class
Public Class Generic(Of T)
End Class
<CLSCompliant(False)>
Public Interface Bad
End Interface
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40027: Return type of function 'P1' is not CLS-compliant.
Public Property P1() As Bad
~~
BC40041: Type 'Bad' is not CLS-compliant.
Public Property P2() As Generic(Of Bad)
~~
BC40041: Type 'Bad' is not CLS-compliant.
Public Property P3() As Generic(Of Generic(Of Bad))
~~
BC40027: Return type of function 'P4' is not CLS-compliant.
Public Property P4() As Bad()
~~
BC40027: Return type of function 'P5' is not CLS-compliant.
Public Property P5() As Bad()()
~~
BC40027: Return type of function 'P6' is not CLS-compliant.
Public Property P6() As Bad(,)
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_ProcTypeNotCLSCompliant1_Delegate()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C1
Public Delegate Function M1() As Bad
Public Delegate Function M2() As Generic(Of Bad)
Public Delegate Function M3() As Generic(Of Generic(Of Bad))
Public Delegate Function M4() As Bad()
Public Delegate Function M5() As Bad()()
Public Delegate Function M6() As Bad(,)
End Class
<CLSCompliant(False)>
Public Class C2
Public Delegate Function N1() As Bad
Public Delegate Function N2() As Generic(Of Bad)
Public Delegate Function N3() As Generic(Of Generic(Of Bad))
Public Delegate Function N4() As Bad()
Public Delegate Function N5() As Bad()()
Public Delegate Function N6() As Bad(,)
End Class
Public Class Generic(Of T)
End Class
<CLSCompliant(False)>
Public Interface Bad
End Interface
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40027: Return type of function 'Invoke' is not CLS-compliant.
Public Delegate Function M1() As Bad
~~
BC40041: Type 'Bad' is not CLS-compliant.
Public Delegate Function M2() As Generic(Of Bad)
~~
BC40041: Type 'Bad' is not CLS-compliant.
Public Delegate Function M3() As Generic(Of Generic(Of Bad))
~~
BC40027: Return type of function 'Invoke' is not CLS-compliant.
Public Delegate Function M4() As Bad()
~~
BC40027: Return type of function 'Invoke' is not CLS-compliant.
Public Delegate Function M5() As Bad()()
~~
BC40027: Return type of function 'Invoke' is not CLS-compliant.
Public Delegate Function M6() As Bad(,)
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_ParamNotCLSCompliant1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C1
Public Function M1(p As Bad)
Throw New Exception()
End Function
Public Function M2(p As Generic(Of Bad))
Throw New Exception()
End Function
Public Function M3(p As Generic(Of Generic(Of Bad)))
Throw New Exception()
End Function
Public Function M4(p As Bad())
Throw New Exception()
End Function
Public Function M5(p As Bad()())
Throw New Exception()
End Function
Public Function M6(p As Bad(,))
Throw New Exception()
End Function
End Class
<CLSCompliant(False)>
Public Class C2
Public Function N1(p As Bad)
Throw New Exception()
End Function
Public Function N2(p As Generic(Of Bad))
Throw New Exception()
End Function
Public Function N3(p As Generic(Of Generic(Of Bad)))
Throw New Exception()
End Function
Public Function N4(p As Bad())
Throw New Exception()
End Function
Public Function N5(p As Bad()())
Throw New Exception()
End Function
Public Function N6(p As Bad(,))
Throw New Exception()
End Function
End Class
Public Class Generic(Of T)
End Class
<CLSCompliant(False)>
Public Interface Bad
End Interface
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40028: Type of parameter 'p' is not CLS-compliant.
Public Function M1(p As Bad)
~
BC40041: Type 'Bad' is not CLS-compliant.
Public Function M2(p As Generic(Of Bad))
~
BC40041: Type 'Bad' is not CLS-compliant.
Public Function M3(p As Generic(Of Generic(Of Bad)))
~
BC40028: Type of parameter 'p' is not CLS-compliant.
Public Function M4(p As Bad())
~
BC40028: Type of parameter 'p' is not CLS-compliant.
Public Function M5(p As Bad()())
~
BC40028: Type of parameter 'p' is not CLS-compliant.
Public Function M6(p As Bad(,))
~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_ParamNotCLSCompliant1_Kinds()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Interface I1
Sub M(x As Bad)
Property P(x As Bad) As Integer
Delegate Sub D(x As Bad)
End Interface
<CLSCompliant(False)>
Public Interface I2
Sub M(x As Bad)
Property P(x As Bad) As Integer
Delegate Sub D(x As Bad)
End Interface
<CLSCompliant(False)>
Public Interface Bad
End Interface
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40028: Type of parameter 'x' is not CLS-compliant.
Sub M(x As Bad)
~
BC40028: Type of parameter 'x' is not CLS-compliant.
Property P(x As Bad) As Integer
~
BC40028: Type of parameter 'x' is not CLS-compliant.
Delegate Sub D(x As Bad)
~
]]></errors>)
End Sub
' From LegacyTest\CSharp\Source\csharp\Source\ClsCompliance\generics\Rule_E_01.cs
<Fact>
Public Sub WRN_ParamNotCLSCompliant1_ConstructedTypeAccessibility()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C(Of T)
Protected Class N
End Class
' Not CLS-compliant since C(Of Integer).N is not accessible within C(Of T) in all languages.
Protected Sub M1(n As C(Of Integer).N)
End Sub
' Fine
Protected Sub M2(n As C(Of T).N)
End Sub
Protected Class N2
' Not CLS-compliant
Protected Sub M3(n As C(Of ULong).N)
End Sub
End Class
End Class
Public Class D
Inherits C(Of Long)
' Not CLS-compliant
Protected Sub M4(n As C(Of Integer).N)
End Sub
' Fine
Protected Sub M5(n As C(Of Long).N)
End Sub
End Class
]]>
</file>
</compilation>
' Dev11 produces error BC30508 for M1 and M3
' Dev11 produces error BC30389 for M4 and M5
' Roslyn dropped these errors (since they weren't helpful) and, instead, reports CLS warnings.
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub WRN_ParamNotCLSCompliant1_ProtectedContainer()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C1(Of T)
Protected Class C2(Of U)
Public Class C3(Of V)
Public Sub M(Of W)(p As C1(Of Integer).C2(Of U))
End Sub
Public Sub M(Of W)(p As C1(Of Integer).C2(Of U).C3(Of V))
End Sub
End Class
End Class
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub AttributeConstructorsWithArrayParameters()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class EmptyAttribute
Inherits Attribute
End Class
Public Class PublicAttribute
Inherits Attribute
' Not accessible
Friend Sub New()
End Sub
' Not compliant
<CLSCompliant(False)>
Public Sub New(x As Integer)
End Sub
' Array argument
Public Sub New(a As Integer(,))
End Sub
' Array argument
Public Sub New(ParamArray a As Char())
End Sub
End Class
Friend Class InternalAttribute
Inherits Attribute
' Not accessible
Public Sub New()
End Sub
End Class
<CLSCompliant(False)>
Public Class BadAttribute
Inherits Attribute
' Fine, since type isn't compliant.
Public Sub New(array As Integer())
End Sub
End Class
Public Class NotAnAttribute
' Fine, since not an attribute type.
Public Sub New(array As Integer())
End Sub
End Class
]]>
</file>
</compilation>
' NOTE: C# requires that compliant attributes have at least one
' accessible constructor with no attribute parameters.
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub AttributeConstructorsWithNonPredefinedParameters()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class MyAttribute
Inherits Attribute
Public Sub New(m As MyAttribute)
End Sub
End Class
]]>
</file>
</compilation>
' CLS only allows System.Type, string, char, bool, byte, short, int, long, float, double, and enums,
' but dev11 does not enforce this.
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub ArrayArgumentToAttribute()
Dim source =
<compilation>
<file name="a.vb">
<>
Public Class B
End Class
<InternalArray({1})>
Public Class C
End Class
<NamedArgument(O:={1})>
Public Class D
End Class
]]>
</file>
</compilation>
' CLS only allows System.Type, string, char, bool, byte, short, int, long, float, double, and enums,
' but dev11 does not enforce this.
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub WRN_NameNotCLSCompliant1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class _A
End Class
Public Class B_
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40031: Name '_A' is not CLS-compliant.
Public Class _A
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_NameNotCLSCompliant1_Kinds()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class Kinds
Public Sub _M()
End Sub
Public Property _P As Integer
Public Event _E As _ND
Public _F As Integer
Public Class _NC
End Class
Public Interface _NI
End Interface
Public Structure _NS
End Structure
Public Delegate Sub _ND()
Private _Private As Integer
<CLSCompliant(False)>
Public _NonCompliant As Integer
End Class
Namespace _NS1
End Namespace
Namespace NS1._NS2
End Namespace
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40031: Name '_M' is not CLS-compliant.
Public Sub _M()
~~
BC40031: Name '_P' is not CLS-compliant.
Public Property _P As Integer
~~
BC40031: Name '_E' is not CLS-compliant.
Public Event _E As _ND
~~
BC40031: Name '_F' is not CLS-compliant.
Public _F As Integer
~~
BC40031: Name '_NC' is not CLS-compliant.
Public Class _NC
~~~
BC40031: Name '_NI' is not CLS-compliant.
Public Interface _NI
~~~
BC40031: Name '_NS' is not CLS-compliant.
Public Structure _NS
~~~
BC40031: Name '_ND' is not CLS-compliant.
Public Delegate Sub _ND()
~~~
BC40031: Name '_NS1' is not CLS-compliant.
Namespace _NS1
~~~~
BC40031: Name '_NS2' is not CLS-compliant.
Namespace NS1._NS2
~~~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_NameNotCLSCompliant1_Overrides()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class Base
Public Overridable Sub _M()
End Sub
End Class
Public Class Derived
Inherits Base
Public Overrides Sub _M()
End Sub
End Class
]]>
</file>
</compilation>
' NOTE: C# doesn't report this warning on overrides.
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40031: Name '_M' is not CLS-compliant.
Public Overridable Sub _M()
~~
BC40031: Name '_M' is not CLS-compliant.
Public Overrides Sub _M()
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_NameNotCLSCompliant1_NotReferencable()
Dim il = <![CDATA[
.class public abstract auto ansi B
{
.custom instance void [mscorlib]System.CLSCompliantAttribute::.ctor(bool) = {bool(true)}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.method public hidebysig newslot specialname abstract virtual
instance int32 _getter() cil managed
{
}
.property instance int32 P()
{
.get instance int32 B::_getter()
}
}
]]>
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Inherits B
Public Overrides ReadOnly Property P As Integer
Get
Return 0
End Get
End Property
End Class
]]>
</file>
</compilation>
Dim comp = CreateCompilationWithCustomILSource(source, il)
comp.AssertNoDiagnostics()
Dim accessor = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").GetMember(Of PropertySymbol)("P").GetMethod
Assert.True(accessor.MetadataName.StartsWith("_", StringComparison.Ordinal))
End Sub
<Fact>
Public Sub WRN_NameNotCLSCompliant1_Parameter()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class B
Public Sub M(_p As Integer)
End Sub
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub ModuleLevel_NoAssemblyLevel()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Module: CLSCompliant(True)>
]]>
</file>
</compilation>
' C# warns.
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Module: CLSCompliant(False)>
]]>
</file>
</compilation>
' C# warns.
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub ModuleLevel_DisagreesWithAssemblyLevel()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(False)>
<Module: CLSCompliant(True)>
]]>
</file>
</compilation>
' C# warns.
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
<Module: CLSCompliant(False)>
]]>
</file>
</compilation>
' C# warns.
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub DroppedAttributes()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(False)>
<Module: CLSCompliant(True)>
]]>
</file>
</compilation>
Dim validator = Function(expectAssemblyLevel As Boolean, expectModuleLevel As Boolean) _
Sub(m As ModuleSymbol)
Dim predicate = Function(attr As VisualBasicAttributeData) attr.AttributeClass.Name = "CLSCompliantAttribute"
If expectModuleLevel Then
AssertEx.Any(m.GetAttributes(), predicate)
Else
AssertEx.None(m.GetAttributes(), predicate)
End If
If expectAssemblyLevel Then
AssertEx.Any(m.ContainingAssembly.GetAttributes(), predicate)
ElseIf m.ContainingAssembly IsNot Nothing Then
AssertEx.None(m.ContainingAssembly.GetAttributes(), predicate)
End If
End Sub
CompileAndVerify(source, options:=TestOptions.ReleaseDll, sourceSymbolValidator:=validator(True, True), symbolValidator:=validator(True, False))
CompileAndVerify(source, options:=TestOptions.ReleaseModule, sourceSymbolValidator:=validator(True, True), symbolValidator:=validator(False, True), verify:=Verification.Fails) ' PEVerify doesn't like netmodules
End Sub
<Fact>
Public Sub ConflictingAssemblyLevelAttributes_ModuleVsAssembly()
Dim source =
<compilation name="A">
<file name="a.vb">
<![CDATA[
<Assembly: System.CLSCompliant(False)>
]]>
</file>
</compilation>
Dim moduleComp = CreateCSharpCompilation("[assembly:System.CLSCompliant(true)]", compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.NetModule), assemblyName:="A")
Dim moduleRef = moduleComp.EmitToImageReference()
CreateCompilationWithMscorlib40AndReferences(source, {moduleRef}).AssertTheseDiagnostics(<errors><![CDATA[
BC36978: Attribute 'CLSCompliantAttribute' in 'A.netmodule' cannot be applied multiple times.
]]></errors>)
End Sub
<Fact>
Public Sub ConflictingAssemblyLevelAttributes_ModuleVsModule()
Dim source =
<compilation name="A">
<file name="a.vb">
</file>
</compilation>
Dim moduleComp1 = CreateCSharpCompilation("[assembly:System.CLSCompliant(true)]", compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.NetModule), assemblyName:="A")
Dim moduleRef1 = moduleComp1.EmitToImageReference()
Dim moduleComp2 = CreateCSharpCompilation("[assembly:System.CLSCompliant(false)]", compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.NetModule), assemblyName:="B")
Dim moduleRef2 = moduleComp2.EmitToImageReference()
CreateCompilationWithMscorlib40AndReferences(source, {moduleRef1, moduleRef2}).AssertTheseDiagnostics(<errors><![CDATA[
BC36978: Attribute 'CLSCompliantAttribute' in 'A.netmodule' cannot be applied multiple times.
]]></errors>)
End Sub
<Fact>
Public Sub AssemblyIgnoresModuleAttribute()
Dim source =
<compilation name="A">
<file name="a.vb">
<![CDATA[
Imports System
<Module: Clscompliant(True)>
<CLSCompliant(True)>
Public Class Test
Inherits Bad
End Class
' Doesn't inherit True from module, so not compliant.
Public Class Bad
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40026: 'Test' is not CLS-compliant because it derives from 'Bad', which is not CLS-compliant.
Public Class Test
~~~~
]]></errors>)
End Sub
<Fact>
Public Sub ModuleIgnoresAssemblyAttribute()
Dim source =
<compilation name="A">
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: Clscompliant(True)>
<CLSCompliant(True)>
Public Class Test
Inherits Bad
End Class
' Doesn't inherit True from assembly, so not compliant.
Public Class Bad
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source, OutputKind.NetModule).AssertTheseDiagnostics(<errors><![CDATA[
BC40026: 'Test' is not CLS-compliant because it derives from 'Bad', which is not CLS-compliant.
Public Class Test
~~~~
]]></errors>)
End Sub
<Fact>
Public Sub IgnoreModuleAttributeInReferencedAssembly()
Dim source =
<compilation name="A">
<file name="a.vb"><![CDATA[
Imports System
<CLSCompliant(True)>
Public Class Test
Inherits Bad
End Class
]]></file>
</compilation>
Dim assemblyLevelLibSource = <![CDATA[
[assembly:System.CLSCompliant(true)]
public class Bad { }
]]>
Dim moduleLevelLibSource = <![CDATA[
[module:System.CLSCompliant(true)]
public class Bad { }
]]>
Dim assemblyLevelLibRef = CreateCSharpCompilation(assemblyLevelLibSource).EmitToImageReference()
Dim moduleLevelLibRef = CreateCSharpCompilation(moduleLevelLibSource).EmitToImageReference(Nothing) ' suppress warning
' Attribute respected.
CreateCompilationWithMscorlib40AndReferences(source, {assemblyLevelLibRef}).AssertNoDiagnostics()
' Attribute not respected.
CreateCompilationWithMscorlib40AndReferences(source, {moduleLevelLibRef}).AssertTheseDiagnostics(<errors><![CDATA[
BC40026: 'Test' is not CLS-compliant because it derives from 'Bad', which is not CLS-compliant.
Public Class Test
~~~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_EnumUnderlyingTypeNotCLS1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Enum E1 As UInteger
A
End Enum
Friend Enum E2 As UInteger
A
End Enum
<CLSCompliant(False)>
Friend Enum E3 As UInteger
A
End Enum
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40032: Underlying type 'UInteger' of Enum is not CLS-compliant.
Public Enum E1 As UInteger
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_TypeNotCLSCompliant1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(False)>
Public Class Bad1
End Class
Public Class Bad2
End Class
Public Class BadGeneric(Of T, U)
End Class
<CLSCompliant(True)>
Public Class Good
End Class
<CLSCompliant(True)>
Public Class GoodGeneric(Of T, U)
End Class
<CLSCompliant(True)>
Public Class Test
' Reported within compliant generic types.
Public x1 As GoodGeneric(Of Good, Good) ' Fine
Public x2 As GoodGeneric(Of Good, Bad1)
Public x3 As GoodGeneric(Of Bad1, Good)
Public x4 As GoodGeneric(Of Bad1, Bad2) ' Both reported
' Reported within non-compliant generic types.
Public Property y1 As BadGeneric(Of Good, Good)
Public Property y2 As BadGeneric(Of Good, Bad1)
Public Property y3 As BadGeneric(Of Bad1, Good)
Public Property y4 As BadGeneric(Of Bad1, Bad2) ' Both reported
Public z1 As GoodGeneric(Of GoodGeneric(Of Bad1, Good), GoodGeneric(Of Bad1, Good))
Public z2 As GoodGeneric(Of BadGeneric(Of Bad1, Good), BadGeneric(Of Bad1, Good)) ' Reported at multiple levels
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40041: Type 'Bad1' is not CLS-compliant.
Public x2 As GoodGeneric(Of Good, Bad1)
~~
BC40041: Type 'Bad1' is not CLS-compliant.
Public x3 As GoodGeneric(Of Bad1, Good)
~~
BC40041: Type 'Bad1' is not CLS-compliant.
Public x4 As GoodGeneric(Of Bad1, Bad2) ' Both reported
~~
BC40041: Type 'Bad2' is not CLS-compliant.
Public x4 As GoodGeneric(Of Bad1, Bad2) ' Both reported
~~
BC40027: Return type of function 'y1' is not CLS-compliant.
Public Property y1 As BadGeneric(Of Good, Good)
~~
BC40027: Return type of function 'y2' is not CLS-compliant.
Public Property y2 As BadGeneric(Of Good, Bad1)
~~
BC40041: Type 'Bad1' is not CLS-compliant.
Public Property y2 As BadGeneric(Of Good, Bad1)
~~
BC40027: Return type of function 'y3' is not CLS-compliant.
Public Property y3 As BadGeneric(Of Bad1, Good)
~~
BC40041: Type 'Bad1' is not CLS-compliant.
Public Property y3 As BadGeneric(Of Bad1, Good)
~~
BC40027: Return type of function 'y4' is not CLS-compliant.
Public Property y4 As BadGeneric(Of Bad1, Bad2) ' Both reported
~~
BC40041: Type 'Bad1' is not CLS-compliant.
Public Property y4 As BadGeneric(Of Bad1, Bad2) ' Both reported
~~
BC40041: Type 'Bad2' is not CLS-compliant.
Public Property y4 As BadGeneric(Of Bad1, Bad2) ' Both reported
~~
BC40041: Type 'Bad1' is not CLS-compliant.
Public z1 As GoodGeneric(Of GoodGeneric(Of Bad1, Good), GoodGeneric(Of Bad1, Good))
~~
BC40041: Type 'Bad1' is not CLS-compliant.
Public z1 As GoodGeneric(Of GoodGeneric(Of Bad1, Good), GoodGeneric(Of Bad1, Good))
~~
BC40041: Type 'Bad1' is not CLS-compliant.
Public z2 As GoodGeneric(Of BadGeneric(Of Bad1, Good), BadGeneric(Of Bad1, Good)) ' Reported at multiple levels
~~
BC40041: Type 'Bad1' is not CLS-compliant.
Public z2 As GoodGeneric(Of BadGeneric(Of Bad1, Good), BadGeneric(Of Bad1, Good)) ' Reported at multiple levels
~~
BC40041: Type 'BadGeneric(Of Bad1, Good)' is not CLS-compliant.
Public z2 As GoodGeneric(Of BadGeneric(Of Bad1, Good), BadGeneric(Of Bad1, Good)) ' Reported at multiple levels
~~
BC40041: Type 'BadGeneric(Of Bad1, Good)' is not CLS-compliant.
Public z2 As GoodGeneric(Of BadGeneric(Of Bad1, Good), BadGeneric(Of Bad1, Good)) ' Reported at multiple levels
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_RootNamespaceNotCLSCompliant1()
Dim source1 =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(False)>
]]>
</file>
</compilation>
' Nothing reported since the namespace inherits CLSCompliant(False) from the assembly.
CreateCompilationWithMscorlib40(source1, options:=TestOptions.ReleaseDll.WithRootNamespace("_A")).AssertNoDiagnostics()
Dim source2 =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source2, options:=TestOptions.ReleaseDll.WithRootNamespace("_A")).AssertTheseDiagnostics(<errors><![CDATA[
BC40038: Root namespace '_A' is not CLS-compliant.
]]></errors>)
Dim source3 =
<compilation>
<file name="a.vb">
<![CDATA[
Public Class Test
End Class
]]>
</file>
</compilation>
Dim moduleRef = CreateCompilationWithMscorlib40(source3, options:=TestOptions.ReleaseModule).EmitToImageReference()
CreateCompilationWithMscorlib40AndReferences(source2, {moduleRef}, options:=TestOptions.ReleaseDll.WithRootNamespace("_A").WithConcurrentBuild(False)).AssertTheseDiagnostics(<errors><![CDATA[
BC40038: Root namespace '_A' is not CLS-compliant.
]]></errors>)
Dim source4 =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Module: CLSCompliant(True)>
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40AndReferences(source4, {moduleRef}, options:=TestOptions.ReleaseModule.WithRootNamespace("_A").WithConcurrentBuild(True)).AssertTheseDiagnostics(<errors><![CDATA[
BC40038: Root namespace '_A' is not CLS-compliant.
]]></errors>)
CreateCompilationWithMscorlib40AndReferences(source2, {moduleRef}, options:=TestOptions.ReleaseModule.WithRootNamespace("_A")).AssertTheseDiagnostics()
End Sub
<Fact>
Public Sub WRN_RootNamespaceNotCLSCompliant2()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll.WithRootNamespace("_A.B.C")).AssertTheseDiagnostics(<errors><![CDATA[
BC40039: Name '_A' in the root namespace '_A.B.C' is not CLS-compliant.
]]></errors>)
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll.WithRootNamespace("A._B.C")).AssertTheseDiagnostics(<errors><![CDATA[
BC40039: Name '_B' in the root namespace 'A._B.C' is not CLS-compliant.
]]></errors>)
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll.WithRootNamespace("A.B._C")).AssertTheseDiagnostics(<errors><![CDATA[
BC40039: Name '_C' in the root namespace 'A.B._C' is not CLS-compliant.
]]></errors>)
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll.WithRootNamespace("_A.B._C")).AssertTheseDiagnostics(<errors><![CDATA[
BC40039: Name '_A' in the root namespace '_A.B._C' is not CLS-compliant.
BC40039: Name '_C' in the root namespace '_A.B._C' is not CLS-compliant.
]]></errors>)
End Sub
<Fact>
Public Sub WRN_OptionalValueNotCLSCompliant1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Public Sub M(Optional x00 As Object = SByte.MaxValue,
Optional x01 As Object = Byte.MaxValue,
Optional x02 As Object = Short.MaxValue,
Optional x03 As Object = UShort.MaxValue,
Optional x04 As Object = Integer.MaxValue,
Optional x05 As Object = UInteger.MaxValue,
Optional x06 As Object = Long.MaxValue,
Optional x07 As Object = ULong.MaxValue,
Optional x08 As Object = Char.MaxValue,
Optional x09 As Object = True,
Optional x10 As Object = Single.MaxValue,
Optional x11 As Object = Double.MaxValue,
Optional x12 As Object = Decimal.MaxValue,
Optional x13 As Object = "ABC",
Optional x14 As Object = #1/1/2001#)
End Sub
End Class
]]>
</file>
</compilation>
' As in dev11, this only applies to int8, uint16, uint32, and uint64
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40042: Type of optional value for optional parameter 'x00' is not CLS-compliant.
Public Sub M(Optional x00 As Object = SByte.MaxValue,
~~~
BC40042: Type of optional value for optional parameter 'x03' is not CLS-compliant.
Optional x03 As Object = UShort.MaxValue,
~~~
BC40042: Type of optional value for optional parameter 'x05' is not CLS-compliant.
Optional x05 As Object = UInteger.MaxValue,
~~~
BC40042: Type of optional value for optional parameter 'x07' is not CLS-compliant.
Optional x07 As Object = ULong.MaxValue,
~~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_OptionalValueNotCLSCompliant1_ParameterTypeNonCompliant()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Public Sub M(Optional x00 As SByte = SByte.MaxValue)
End Sub
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40028: Type of parameter 'x00' is not CLS-compliant.
Public Sub M(Optional x00 As SByte = SByte.MaxValue)
~~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_CLSAttrInvalidOnGetSet_True()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<CLSCompliant(True)>
Public Class C
<CLSCompliant(False)>
Public Property P1 As UInteger
<CLSCompliant(True)>
Get
Return 0
End Get
<CLSCompliant(True)>
Set(value As UInteger)
End Set
End Property
<CLSCompliant(False)>
Public ReadOnly Property P2 As UInteger
<CLSCompliant(True)>
Get
Return 0
End Get
End Property
<CLSCompliant(False)>
Public WriteOnly Property P3 As UInteger
<CLSCompliant(True)>
Set(value As UInteger)
End Set
End Property
End Class
]]>
</file>
</compilation>
' NOTE: No warnings about non-compliant type UInteger.
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'.
<CLSCompliant(True)>
~~~~~~~~~~~~~~~~~~
BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'.
<CLSCompliant(True)>
~~~~~~~~~~~~~~~~~~
BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'.
<CLSCompliant(True)>
~~~~~~~~~~~~~~~~~~
BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'.
<CLSCompliant(True)>
~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_CLSAttrInvalidOnGetSet_False()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<CLSCompliant(True)>
Public Class C
<CLSCompliant(True)>
Public Property P1 As UInteger
<CLSCompliant(False)>
Get
Return 0
End Get
<CLSCompliant(False)>
Set(value As UInteger)
End Set
End Property
<CLSCompliant(True)>
Public ReadOnly Property P2 As UInteger
<CLSCompliant(False)>
Get
Return 0
End Get
End Property
<CLSCompliant(True)>
Public WriteOnly Property P3 As UInteger
<CLSCompliant(False)>
Set(value As UInteger)
End Set
End Property
End Class
]]>
</file>
</compilation>
' NOTE: See warnings about non-compliant type UInteger.
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40027: Return type of function 'P1' is not CLS-compliant.
Public Property P1 As UInteger
~~
BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'.
<CLSCompliant(False)>
~~~~~~~~~~~~~~~~~~~
BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'.
<CLSCompliant(False)>
~~~~~~~~~~~~~~~~~~~
BC40027: Return type of function 'P2' is not CLS-compliant.
Public ReadOnly Property P2 As UInteger
~~
BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'.
<CLSCompliant(False)>
~~~~~~~~~~~~~~~~~~~
BC40027: Return type of function 'P3' is not CLS-compliant.
Public WriteOnly Property P3 As UInteger
~~
BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'.
<CLSCompliant(False)>
~~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_CLSEventMethodInNonCLSType3()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<CLSCompliant(False)>
Public Class C
Public Custom Event E1 As Action(Of UInteger)
<CLSCompliant(True)>
AddHandler(value As Action(Of UInteger))
End AddHandler
<CLSCompliant(True)>
RemoveHandler(value As Action(Of UInteger))
End RemoveHandler
<CLSCompliant(True)>
RaiseEvent()
End RaiseEvent
End Event
<CLSCompliant(False)>
Public Custom Event E2 As Action(Of UInteger)
<CLSCompliant(True)>
AddHandler(value As Action(Of UInteger))
End AddHandler
<CLSCompliant(True)>
RemoveHandler(value As Action(Of UInteger))
End RemoveHandler
<CLSCompliant(True)>
RaiseEvent()
End RaiseEvent
End Event
End Class
]]>
</file>
</compilation>
' NOTE: No warnings about non-compliant type UInteger.
' NOTE: No warnings about RaiseEvent accessors.
' NOTE: CLSCompliant(False) on event doesn't suppress warnings.
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40053: 'AddHandler' method for event 'E1' cannot be marked CLS compliant because its containing type 'C' is not CLS compliant.
<CLSCompliant(True)>
~~~~~~~~~~~~~~~~~~
BC40053: 'RemoveHandler' method for event 'E1' cannot be marked CLS compliant because its containing type 'C' is not CLS compliant.
<CLSCompliant(True)>
~~~~~~~~~~~~~~~~~~
BC40053: 'AddHandler' method for event 'E2' cannot be marked CLS compliant because its containing type 'C' is not CLS compliant.
<CLSCompliant(True)>
~~~~~~~~~~~~~~~~~~
BC40053: 'RemoveHandler' method for event 'E2' cannot be marked CLS compliant because its containing type 'C' is not CLS compliant.
<CLSCompliant(True)>
~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
Public Sub EventAccessors()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<CLSCompliant(True)>
Public Class C
<CLSCompliant(False)>
Public Custom Event E1 As Action(Of UInteger)
<CLSCompliant(True)>
AddHandler(value As Action(Of UInteger))
End AddHandler
<CLSCompliant(True)>
RemoveHandler(value As Action(Of UInteger))
End RemoveHandler
<CLSCompliant(True)>
RaiseEvent()
End RaiseEvent
End Event
<CLSCompliant(True)>
Public Custom Event E2 As Action(Of UInteger)
<CLSCompliant(False)>
AddHandler(value As Action(Of UInteger))
End AddHandler
<CLSCompliant(False)>
RemoveHandler(value As Action(Of UInteger))
End RemoveHandler
<CLSCompliant(False)>
RaiseEvent()
End RaiseEvent
End Event
End Class
]]>
</file>
</compilation>
' NOTE: As in dev11, we do not warn that we are ignoring CLSCompliantAttribute on event accessors.
' NOTE: See warning about non-compliant type UInteger only for E2.
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40041: Type 'UInteger' is not CLS-compliant.
Public Custom Event E2 As Action(Of UInteger)
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_EventDelegateTypeNotCLSCompliant2()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Namespace Q
<CLSCompliant(False)>
Public Delegate Sub Bad()
End Namespace
<CLSCompliant(True)>
Public Class C
Public Custom Event E1 As Q.Bad
AddHandler(value As Q.Bad)
End AddHandler
RemoveHandler(value As Q.Bad)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
Public Event E2 As Q.Bad
Public Event E3(x As UInteger)
<CLSCompliant(False)>
Public Custom Event E4 As Q.Bad
AddHandler(value As Q.Bad)
End AddHandler
RemoveHandler(value As Q.Bad)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
<CLSCompliant(False)>
Public Event E5 As Q.Bad
<CLSCompliant(False)>
Public Event E6(x As UInteger)
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40050: Delegate type 'Bad' of event 'E1' is not CLS-compliant.
Public Custom Event E1 As Q.Bad
~~
BC40050: Delegate type 'Bad' of event 'E2' is not CLS-compliant.
Public Event E2 As Q.Bad
~~
BC40028: Type of parameter 'x' is not CLS-compliant.
Public Event E3(x As UInteger)
~
]]></errors>)
End Sub
<Fact>
Public Sub TopLevelMethod_NoAssemblyAttribute()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Public Sub M()
End Sub
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC30001: Statement is not valid in a namespace.
Public Sub M()
~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
Public Sub TopLevelMethod_AttributeTrue()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Sub M()
End Sub
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC30001: Statement is not valid in a namespace.
Public Sub M()
~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
Public Sub TopLevelMethod_AttributeFalse()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Sub M()
End Sub
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC30001: Statement is not valid in a namespace.
Public Sub M()
~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
Public Sub NonCompliantInaccessible()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Private Function M(b As Bad) As Bad
Return b
End Function
Private Property P(b As Bad) As Bad
Get
Return b
End Get
Set(value As Bad)
End Set
End Property
End Class
<CLSCompliant(False)>
Public Class Bad
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub NonCompliantAbstractInNonCompliantType()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
<CLSCompliant(False)>
Public MustInherit Class Bad
Public MustOverride Function M(b As Bad) As Bad
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub SpecialTypes()
Dim sourceTemplate = <![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Public Sub M(p As {0})
End Sub
End Class
]]>.Value.Replace(vbCr, vbCrLf)
Dim helper = CreateCompilationWithMscorlib40({""}, Nothing)
Dim integerType = helper.GetSpecialType(SpecialType.System_Int32)
For Each st As SpecialType In [Enum].GetValues(GetType(SpecialType))
Select Case (st)
Case SpecialType.None, SpecialType.System_Void, SpecialType.System_Runtime_CompilerServices_IsVolatile
Continue For
End Select
Dim type = helper.GetSpecialType(st)
If type.Arity > 0 Then
type = type.Construct(ArrayBuilder(Of TypeSymbol).GetInstance(type.Arity, integerType).ToImmutableAndFree())
End If
Dim qualifiedName = type.ToTestDisplayString()
Dim source = String.Format(sourceTemplate, qualifiedName)
Dim comp = CreateCompilationWithMscorlib40({source}, Nothing)
Select Case (st)
Case SpecialType.System_SByte, SpecialType.System_UInt16, SpecialType.System_UInt32, SpecialType.System_UInt64, SpecialType.System_UIntPtr, SpecialType.System_TypedReference
Assert.Equal(ERRID.WRN_ParamNotCLSCompliant1, DirectCast(comp.GetDeclarationDiagnostics().Single().Code, ERRID))
End Select
Next
End Sub
<WorkItem(697178, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/697178")>
<Fact>
Public Sub ConstructedSpecialTypes()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections.Generic
<Assembly: CLSCompliant(True)>
Public Class C
Public Sub M(p As IEnumerable(Of UInteger))
End Sub
End Class
]]>
</file>
</compilation>
' Native C# misses this diagnostic
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40041: Type 'UInteger' is not CLS-compliant.
Public Sub M(p As IEnumerable(Of UInteger))
~
]]></errors>)
End Sub
<Fact>
Public Sub MissingAttributeType()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
<Missing>
Public Class C
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC30002: Type 'Missing' is not defined.
<Missing>
~~~~~~~
]]></errors>)
End Sub
<WorkItem(709317, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/709317")>
<Fact>
Public Sub Repro709317()
Dim libSource =
<compilation name="Lib">
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
End Class
]]>
</file>
</compilation>
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class D
Public Function M() As C
Return Nothing
End Function
End Class
]]>
</file>
</compilation>
Dim libRef = CreateCompilationWithMscorlib40(libSource).EmitToImageReference()
Dim comp = CreateCompilationWithMscorlib40AndReferences(source, {libRef})
Dim tree = comp.SyntaxTrees.Single()
comp.GetDiagnosticsForSyntaxTree(CompilationStage.Declare, tree)
End Sub
<WorkItem(709317, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/709317")>
<Fact>
Public Sub FilterTree()
Dim sourceTemplate = <![CDATA[
Imports System
Namespace N{0}
<CLSCompliant(False)>
Public Class NonCompliant
End Class
<CLSCompliant(False)>
Public Interface INonCompliant
End Interface
<CLSCompliant(True)>
Public Class Compliant
Inherits NonCompliant
Implements INonCompliant
Public Function M(Of T As NonCompliant)(n As NonCompliant)
Throw New Exception
End Function
Public F As NonCompliant
Public Property P As NonCompliant
End Class
End Namespace
]]>.Value.Replace(vbCr, vbCrLf)
Dim tree1 = VisualBasicSyntaxTree.ParseText(String.Format(sourceTemplate, 1), path:="a.vb")
Dim tree2 = VisualBasicSyntaxTree.ParseText(String.Format(sourceTemplate, 2), path:="b.vb")
Dim comp = CreateCompilationWithMscorlib40({tree1, tree2}, options:=TestOptions.ReleaseDll)
' Two copies of each diagnostic - one from each file.
comp.AssertTheseDiagnostics(<errors><![CDATA[
BC40026: 'Compliant' is not CLS-compliant because it derives from 'NonCompliant', which is not CLS-compliant.
Public Class Compliant
~~~~~~~~~
BC40040: Generic parameter constraint type 'NonCompliant' is not CLS-compliant.
Public Function M(Of T As NonCompliant)(n As NonCompliant)
~
BC40028: Type of parameter 'n' is not CLS-compliant.
Public Function M(Of T As NonCompliant)(n As NonCompliant)
~
BC40025: Type of member 'F' is not CLS-compliant.
Public F As NonCompliant
~
BC40027: Return type of function 'P' is not CLS-compliant.
Public Property P As NonCompliant
~
BC40026: 'Compliant' is not CLS-compliant because it derives from 'NonCompliant', which is not CLS-compliant.
Public Class Compliant
~~~~~~~~~
BC40040: Generic parameter constraint type 'NonCompliant' is not CLS-compliant.
Public Function M(Of T As NonCompliant)(n As NonCompliant)
~
BC40028: Type of parameter 'n' is not CLS-compliant.
Public Function M(Of T As NonCompliant)(n As NonCompliant)
~
BC40025: Type of member 'F' is not CLS-compliant.
Public F As NonCompliant
~
BC40027: Return type of function 'P' is not CLS-compliant.
Public Property P As NonCompliant
~
]]></errors>)
CompilationUtils.AssertTheseDiagnostics(comp.GetDiagnosticsForSyntaxTree(CompilationStage.Declare, tree1, filterSpanWithinTree:=Nothing, includeEarlierStages:=False),
<errors><![CDATA[
BC40026: 'Compliant' is not CLS-compliant because it derives from 'NonCompliant', which is not CLS-compliant.
Public Class Compliant
~~~~~~~~~
BC40040: Generic parameter constraint type 'NonCompliant' is not CLS-compliant.
Public Function M(Of T As NonCompliant)(n As NonCompliant)
~
BC40028: Type of parameter 'n' is not CLS-compliant.
Public Function M(Of T As NonCompliant)(n As NonCompliant)
~
BC40025: Type of member 'F' is not CLS-compliant.
Public F As NonCompliant
~
BC40027: Return type of function 'P' is not CLS-compliant.
Public Property P As NonCompliant
~
]]></errors>)
End Sub
<WorkItem(718503, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/718503")>
<Fact>
Public Sub ErrorTypeAccessibility()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Implements IError
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC30002: Type 'IError' is not defined.
Implements IError
~~~~~~
]]></errors>)
End Sub
' Make sure nothing blows up when a protected symbol has no containing type.
<Fact>
Public Sub ProtectedTopLevelType()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Protected Class C
Public F As UInteger
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC31047: Protected types can only be declared inside of a class.
Protected Class C
~
]]></errors>)
End Sub
<Fact>
Public Sub ProtectedMemberOfSealedType()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public NotInheritable Class C
Protected F As UInteger ' No warning, since not accessible outside assembly.
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub InheritedCompliance1()
Dim libSource =
<compilation name="Lib">
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(False)>
<CLSCompliant(True)>
Public Class Base
End Class
Public Class Derived
Inherits Base
End Class
]]>
</file>
</compilation>
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Public B as Base
Public D as Derived
End Class
]]>
</file>
</compilation>
' NOTE: As in dev11, we ignore the fact that Derived inherits CLSCompliant(True) from Base.
Dim libRef = CreateCompilationWithMscorlib40(libSource).EmitToImageReference()
CreateCompilationWithMscorlib40AndReferences(source, {libRef}).AssertTheseDiagnostics(<errors><![CDATA[
BC40025: Type of member 'D' is not CLS-compliant.
Public D as Derived
~
]]></errors>)
End Sub
<Fact>
Public Sub InheritedCompliance2()
Dim il = <![CDATA[.assembly extern mscorlib
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 )
.ver 4:0:0:0
}
.assembly a
{
.hash algorithm 0x00008004
.ver 0:0:0:0
.custom instance void [mscorlib]System.CLSCompliantAttribute::.ctor(bool) = {bool(true)}
}
.module a.dll
.class public auto ansi beforefieldinit Base
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.CLSCompliantAttribute::.ctor(bool) = {bool(false)}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}
.class public auto ansi beforefieldinit Derived
extends Base
{
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}]]>
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Public B as Base
Public D as Derived
End Class
]]>
</file>
</compilation>
' NOTE: As in dev11, we consider the fact that Derived inherits CLSCompliant(False) from Base
' (since it is not from the current assembly).
Dim libRef = CompileIL(il.Value, prependDefaultHeader:=False)
CreateCompilationWithMscorlib40AndReferences(source, {libRef}).AssertTheseDiagnostics(<errors><![CDATA[
BC40025: Type of member 'B' is not CLS-compliant.
Public B as Base
~
BC40025: Type of member 'D' is not CLS-compliant.
Public D as Derived
~
]]></errors>)
End Sub
<Fact>
Public Sub AllAttributeConstructorsRequireArrays()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class MyAttribute
Inherits Attribute
Public Sub New(a As Integer())
End Sub
End Class
]]>
</file>
</compilation>
' C# would warn.
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub ApplyAttributeWithArrayArgument()
Dim source =
<compilation>
<file name="a.vb">
<>
<Array({1})>
<Params(1)>
Public Class C
End Class
]]>
</file>
</compilation>
' C# would warn.
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub ApplyAttributeWithNonCompliantArgument()
Dim source =
<compilation>
<file name="a.vb">
<>
Public Class C
End Class
]]>
</file>
</compilation>
' C# would warn.
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub Overloading_ArrayRank()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class Compliant
Public Sub M1(x As Integer())
End Sub
Public Sub M1(x As Integer(,)) 'BC40035
End Sub
Public Sub M2(x As Integer(,,))
End Sub
Public Sub M2(x As Integer(,)) 'BC40035
End Sub
Public Sub M3(x As Integer())
End Sub
Private Sub M3(x As Integer(,)) ' Fine, since inaccessible.
End Sub
Public Sub M4(x As Integer())
End Sub
<CLSCompliant(False)>
Private Sub M4(x As Integer(,)) ' Fine, since flagged.
End Sub
End Class
Friend Class Internal
Public Sub M1(x As Integer())
End Sub
Public Sub M1(x As Integer(,)) ' Fine, since inaccessible.
End Sub
End Class
<CLSCompliant(False)>
Public Class NonCompliant
Public Sub M1(x As Integer())
End Sub
Public Sub M1(x As Integer(,)) ' Fine, since tagged.
End Sub
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40035: 'Public Sub M1(x As Integer(*,*))' is not CLS-compliant because it overloads 'Public Sub M1(x As Integer())' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub M1(x As Integer(,)) 'BC40035
~~
BC40035: 'Public Sub M2(x As Integer(*,*))' is not CLS-compliant because it overloads 'Public Sub M2(x As Integer(*,*,*))' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub M2(x As Integer(,)) 'BC40035
~~
]]></errors>)
End Sub
<Fact>
Public Sub Overloading_RefKind()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(False)>
Public Class Compliant
Public Sub M1(x As Integer())
End Sub
Public Sub M1(ByRef x As Integer()) 'BC30345
End Sub
End Class
]]>
</file>
</compilation>
' NOTE: Illegal, even without compliance checking.
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC30345: 'Public Sub M1(x As Integer())' and 'Public Sub M1(ByRef x As Integer())' cannot overload each other because they differ only by parameters declared 'ByRef' or 'ByVal'.
Public Sub M1(x As Integer())
~~
]]></errors>)
End Sub
<Fact>
Public Sub Overloading_ArrayOfArrays()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class Compliant
Public Sub M1(x As Long()())
End Sub
Public Sub M1(x As Char()()) 'BC40035
End Sub
Public Sub M2(x As Integer()()())
End Sub
Public Sub M2(x As Integer()()) 'BC40035
End Sub
Public Sub M3(x As Integer()())
End Sub
Public Sub M3(x As Integer()) 'Fine (C# warns)
End Sub
Public Sub M4(x As Integer(,)(,))
End Sub
Public Sub M4(x As Integer()(,)) 'BC40035
End Sub
Public Sub M5(x As Integer(,)(,))
End Sub
Public Sub M5(x As Integer(,)()) 'BC40035
End Sub
Public Sub M6(x As Long()())
End Sub
Private Sub M6(x As Char()()) ' Fine, since inaccessible.
End Sub
Public Sub M7(x As Long()())
End Sub
<CLSCompliant(False)>
Public Sub M7(x As Char()()) ' Fine, since tagged (dev11 reports BC40035)
End Sub
End Class
Friend Class Internal
Public Sub M1(x As Long()())
End Sub
Public Sub M1(x As Char()()) ' Fine, since inaccessible.
End Sub
End Class
<CLSCompliant(False)>
Public Class NonCompliant
Public Sub M1(x As Long()())
End Sub
Public Sub M1(x As Char()()) ' Fine, since tagged.
End Sub
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40035: 'Public Sub M1(x As Char()())' is not CLS-compliant because it overloads 'Public Sub M1(x As Long()())' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub M1(x As Char()()) 'BC40035
~~
BC40035: 'Public Sub M2(x As Integer()())' is not CLS-compliant because it overloads 'Public Sub M2(x As Integer()()())' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub M2(x As Integer()()) 'BC40035
~~
BC40035: 'Public Sub M4(x As Integer()(*,*))' is not CLS-compliant because it overloads 'Public Sub M4(x As Integer(*,*)(*,*))' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub M4(x As Integer()(,)) 'BC40035
~~
BC40035: 'Public Sub M5(x As Integer(*,*)())' is not CLS-compliant because it overloads 'Public Sub M5(x As Integer(*,*)(*,*))' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub M5(x As Integer(,)()) 'BC40035
~~
]]></errors>)
End Sub
<Fact>
Public Sub Overloading_Properties()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class Compliant
Public Property P1(x As Long()()) As Integer
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
Public Property P1(x As Char()()) As Integer
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
Public Property P2(x As String()) As Integer
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
Public Property P2(x As String(,)) As Integer
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40035: 'Public Property P1(x As Char()()) As Integer' is not CLS-compliant because it overloads 'Public Property P1(x As Long()()) As Integer' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Property P1(x As Char()()) As Integer
~~
BC40035: 'Public Property P2(x As String(*,*)) As Integer' is not CLS-compliant because it overloads 'Public Property P2(x As String()) As Integer' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Property P2(x As String(,)) As Integer
~~
]]></errors>)
End Sub
<Fact>
Public Sub Overloading_MethodKinds()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Public Sub New(p As Long()())
End Sub
Public Sub New(p As Char()())
End Sub
Public Shared Widening Operator CType(p As Long()) As C
Return Nothing
End Operator
Public Shared Widening Operator CType(p As Long(,)) As C ' Not reported by dev11.
Return Nothing
End Operator
Public Shared Narrowing Operator CType(p As String(,,)) As C
Return Nothing
End Operator
Public Shared Narrowing Operator CType(p As String(,)) As C ' Not reported by dev11.
Return Nothing
End Operator
' Static constructors can't be overloaded
' Destructors can't be overloaded.
' Accessors are tested separately.
End Class
]]>
</file>
</compilation>
' BREAK : Dev11 doesn't report BC40035 for operators.
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40035: 'Public Sub New(p As Char()())' is not CLS-compliant because it overloads 'Public Sub New(p As Long()())' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub New(p As Char()())
~~~
BC40035: 'Public Shared Widening Operator CType(p As Long(*,*)) As C' is not CLS-compliant because it overloads 'Public Shared Widening Operator CType(p As Long()) As C' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Shared Widening Operator CType(p As Long(,)) As C ' Not reported by dev11.
~~~~~
BC40035: 'Public Shared Narrowing Operator CType(p As String(*,*)) As C' is not CLS-compliant because it overloads 'Public Shared Narrowing Operator CType(p As String(*,*,*)) As C' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Shared Narrowing Operator CType(p As String(,)) As C ' Not reported by dev11.
~~~~~
]]></errors>)
End Sub
<Fact>
Public Sub Overloading_Operators()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Public Shared Widening Operator CType(p As C) As Integer
Return Nothing
End Operator
Public Shared Widening Operator CType(p As C) As Long
Return Nothing
End Operator
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub Overloading_TypeParameterArray()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C(Of T)
Public Sub M1(t As T())
End Sub
Public Sub M1(t As Integer())
End Sub
Public Sub M2(Of U)(t As U())
End Sub
Public Sub M2(Of U)(t As Integer())
End Sub
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub Overloading_InterfaceMember()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Interface I
Sub M(p As Long()())
End Interface
Public Class ImplementWithSameName
Implements I
Public Sub M(p()() As Long) Implements I.M
End Sub
Public Sub M(p()() As Char) 'BC40035 (twice, in roslyn)
End Sub
End Class
Public Class ImplementWithOtherName
Implements I
Public Sub I_M(p()() As Long) Implements I.M
End Sub
Public Sub M(p()() As String) 'BC40035 (roslyn only)
End Sub
End Class
Public Class Base
Implements I
Public Sub I_M(p()() As Long) Implements I.M
End Sub
End Class
Public Class Derived1
Inherits Base
Implements I
Public Sub M(p()() As Boolean) 'BC40035 (roslyn only)
End Sub
End Class
Public Class Derived2
Inherits Base
Public Sub M(p()() As Short) 'Mimic (C#) dev11 bug - don't report conflict with interface member.
End Sub
End Class
]]>
</file>
</compilation>
' BREAK : Dev11 doesn't report BC40035 for interface members.
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40035: 'Public Sub M(p As Char()())' is not CLS-compliant because it overloads 'Public Sub M(p As Long()())' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub M(p()() As Char) 'BC40035 (twice, in roslyn)
~
BC40035: 'Public Sub M(p As Char()())' is not CLS-compliant because it overloads 'Sub M(p As Long()())' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub M(p()() As Char) 'BC40035 (twice, in roslyn)
~
BC40035: 'Public Sub M(p As String()())' is not CLS-compliant because it overloads 'Sub M(p As Long()())' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub M(p()() As String) 'BC40035 (roslyn only)
~
BC40035: 'Public Sub M(p As Boolean()())' is not CLS-compliant because it overloads 'Sub M(p As Long()())' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub M(p()() As Boolean) 'BC40035 (roslyn only)
~
]]></errors>)
End Sub
<Fact>
Public Sub Overloading_BaseMember()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class Base
Public Overridable Sub M(p As Long()())
End Sub
Public Overridable WriteOnly Property P(q As Long()())
Set(value)
End Set
End Property
End Class
Public Class Derived_Overload
Inherits Base
Public Overloads Sub M(p As Char()())
End Sub
Public Overloads WriteOnly Property P(q As Char()())
Set(value)
End Set
End Property
End Class
Public Class Derived_Hide
Inherits Base
Public Shadows Sub M(p As Long()())
End Sub
Public Shadows WriteOnly Property P(q As Long()())
Set(value)
End Set
End Property
End Class
Public Class Derived_Override
Inherits Base
Public Overrides Sub M(p As Long()())
End Sub
Public Overrides WriteOnly Property P(q As Long()())
Set(value)
End Set
End Property
End Class
Public Class Derived1
Inherits Base
End Class
Public Class Derived2
Inherits Derived1
Public Overloads Sub M(p As String()())
End Sub
Public Overloads WriteOnly Property P(q As String()())
Set(value)
End Set
End Property
End Class
]]>
</file>
</compilation>
' BREAK : Dev11 doesn't report BC40035 for base type members.
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40035: 'Public Overloads Sub M(p As Char()())' is not CLS-compliant because it overloads 'Public Overridable Sub M(p As Long()())' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Overloads Sub M(p As Char()())
~
BC40035: 'Public Overloads WriteOnly Property P(q As Char()()) As Object' is not CLS-compliant because it overloads 'Public Overridable WriteOnly Property P(q As Long()()) As Object' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Overloads WriteOnly Property P(q As Char()())
~
BC40035: 'Public Overloads Sub M(p As String()())' is not CLS-compliant because it overloads 'Public Overridable Sub M(p As Long()())' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Overloads Sub M(p As String()())
~
BC40035: 'Public Overloads WriteOnly Property P(q As String()()) As Object' is not CLS-compliant because it overloads 'Public Overridable WriteOnly Property P(q As Long()()) As Object' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Overloads WriteOnly Property P(q As String()())
~
]]></errors>)
End Sub
<Fact>
Public Sub WithEventsWarning()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Public WithEvents F As Bad
End Class
<CLSCompliant(False)>
Public Class Bad
End Class
]]>
</file>
</compilation>
' Make sure we don't produce a bunch of spurious warnings for synthesized members.
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40027: Return type of function 'F' is not CLS-compliant.
Public WithEvents F As Bad
~
]]></errors>)
End Sub
<WorkItem(749432, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/749432")>
<Fact>
Public Sub InvalidAttributeArgument()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Public Module VBCoreHelperFunctionality
<CLSCompliant((New With {.anonymousField = False}).anonymousField)>
Public Function Len(ByVal Expression As SByte) As Integer
Return (New With {.anonymousField = 1}).anonymousField
End Function
<CLSCompliant((New With {.anonymousField = False}).anonymousField)>
Public Function Len(ByVal Expression As UInt16) As Integer
Return (New With {.anonymousField = 2}).anonymousField
End Function
End Module
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40AndVBRuntime(source).AssertTheseDiagnostics(<errors><![CDATA[
BC30059: Constant expression is required.
<CLSCompliant((New With {.anonymousField = False}).anonymousField)>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30059: Constant expression is required.
<CLSCompliant((New With {.anonymousField = False}).anonymousField)>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<WorkItem(749352, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/749352")>
<Fact>
Public Sub Repro749352()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Namespace ClsCompClass001f
<CLSCompliant(False)>
Public Class ContainerClass
'COMPILEWARNING: BC40030, "Scen6"
<CLSCompliant(True)>
Public Event Scen6(ByVal x As Integer)
End Class
End Namespace
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40030: event 'Public Event Scen6(x As Integer)' cannot be marked CLS-compliant because its containing type 'ContainerClass' is not CLS-compliant.
Public Event Scen6(ByVal x As Integer)
~~~~~
]]></errors>)
End Sub
<Fact, WorkItem(1026453, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1026453")>
Public Sub Bug1026453()
Dim source1 =
<compilation>
<file name="a.vb">
<![CDATA[
Namespace N1
Public Class A
End Class
End Namespace
]]>
</file>
</compilation>
Dim comp1 = CreateCompilationWithMscorlib40(source1, options:=TestOptions.ReleaseModule)
Dim source2 =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
<Module: CLSCompliant(True)>
Namespace N1
Public Class B
End Class
End Namespace
]]>
</file>
</compilation>
Dim comp2 = CreateCompilationWithMscorlib40AndReferences(source2, {comp1.EmitToImageReference()}, TestOptions.ReleaseDll.WithConcurrentBuild(False))
comp2.AssertNoDiagnostics()
comp2.WithOptions(TestOptions.ReleaseDll.WithConcurrentBuild(True)).AssertNoDiagnostics()
Dim comp3 = comp2.WithOptions(TestOptions.ReleaseModule.WithConcurrentBuild(False))
comp3.AssertNoDiagnostics()
comp3.WithOptions(TestOptions.ReleaseModule.WithConcurrentBuild(True)).AssertNoDiagnostics()
End Sub
<Fact, WorkItem(9719, "https://github.com/dotnet/roslyn/issues/9719")>
Public Sub Bug9719()
' repro was simpler than what's on the github issue - before any fixes, the below snippit triggered the crash
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Public Sub Problem(item As DummyModule)
End Sub
End Class
Public Module DummyModule
End Module
]]>
</file>
</compilation>
CreateCompilationWithMscorlib45AndVBRuntime(source).AssertTheseDiagnostics(<errors><![CDATA[
BC30371: Module 'DummyModule' cannot be used as a type.
Public Sub Problem(item As DummyModule)
~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
Public Sub TupleDefersClsComplianceToUnderlyingType()
Dim libCompliant_vb = "
Namespace System
<CLSCompliant(True)>
Public Structure ValueTuple(Of T1, T2)
Public Sub New(item1 As T1, item2 As T2)
End Sub
End Structure
End Namespace
"
Dim libNotCompliant_vb = "
Namespace System
<CLSCompliant(False)>
Public Structure ValueTuple(Of T1, T2)
Public Sub New(item1 As T1, item2 As T2)
End Sub
End Structure
End Namespace
"
Dim source = "
Imports System
<assembly:CLSCompliant(true)>
Public Class C
Public Function Method() As (Integer, Integer)
Throw New Exception()
End Function
Public Function Method2() As (Bad, Bad)
Throw New Exception()
End Function
End Class
<CLSCompliant(false)>
Public Class Bad
End Class
"
Dim libCompliant = CreateCompilationWithMscorlib40({libCompliant_vb}, options:=TestOptions.ReleaseDll).EmitToImageReference()
Dim compCompliant = CreateCompilationWithMscorlib40({source}, {libCompliant}, TestOptions.ReleaseDll)
compCompliant.AssertTheseDiagnostics(
<errors>
BC40041: Type 'Bad' is not CLS-compliant.
Public Function Method2() As (Bad, Bad)
~~~~~~~
BC40041: Type 'Bad' is not CLS-compliant.
Public Function Method2() As (Bad, Bad)
~~~~~~~
</errors>)
Dim libNotCompliant = CreateCompilationWithMscorlib40({libNotCompliant_vb}, options:=TestOptions.ReleaseDll).EmitToImageReference()
Dim compNotCompliant = CreateCompilationWithMscorlib40({source}, {libNotCompliant}, TestOptions.ReleaseDll)
compNotCompliant.AssertTheseDiagnostics(
<errors>
BC40027: Return type of function 'Method' is not CLS-compliant.
Public Function Method() As (Integer, Integer)
~~~~~~
BC40027: Return type of function 'Method2' is not CLS-compliant.
Public Function Method2() As (Bad, Bad)
~~~~~~~
BC40041: Type 'Bad' is not CLS-compliant.
Public Function Method2() As (Bad, Bad)
~~~~~~~
BC40041: Type 'Bad' is not CLS-compliant.
Public Function Method2() As (Bad, Bad)
~~~~~~~
</errors>)
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class ClsComplianceTests
Inherits BasicTestBase
<Fact>
Public Sub NoAssemblyLevelAttributeRequired()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<CLSCompliant(True)>
Public Class A
End Class
<CLSCompliant(False)>
Public Class B
End Class
]]>
</file>
</compilation>
' In C#, an assembly-level attribute is required. In VB, that is not the case.
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub AssemblyLevelAttributeAllowed()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
<Module: CLSCompliant(True)>
<CLSCompliant(True)>
Public Class A
End Class
<CLSCompliant(False)>
Public Class B
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub AttributeAllowedOnPrivate()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<CLSCompliant(True)>
Public Class Outer
<CLSCompliant(True)>
Private Class A
End Class
<CLSCompliant(True)>
Friend Class B
End Class
<CLSCompliant(True)>
Protected Class C
End Class
<CLSCompliant(True)>
Friend Protected Class D
End Class
<CLSCompliant(True)>
Public Class E
End Class
End Class
]]>
</file>
</compilation>
' C# warns about putting the attribute on members not visible outside the assembly.
' VB does not.
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub AttributeAllowedOnParameters()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<CLSCompliant(True)>
Public Class C
Public Function M(<CLSCompliant(True)> x As Integer) As Integer
Return 0
End Function
Public ReadOnly Property P(<CLSCompliant(True)> x As Integer) As Integer
Get
Return 0
End Get
End Property
End Class
]]>
</file>
</compilation>
' C# warns about putting the attribute on parameters. VB does not.
' C# also warns about putting the attribute on return types, but VB
' does not support the "return" attribute target.
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub WRN_CLSMemberInNonCLSType3_Explicit()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<CLSCompliant(False)>
Public Class Kinds
<CLSCompliant(True)>
Public Sub M()
End Sub
<CLSCompliant(True)>
Public Property P As Integer
<CLSCompliant(True)>
Public Event E As ND
<CLSCompliant(True)>
Public F As Integer
<CLSCompliant(True)>
Public Class NC
End Class
<CLSCompliant(True)>
Public Interface NI
End Interface
<CLSCompliant(True)>
Public Structure NS
End Structure
<CLSCompliant(True)>
Public Delegate Sub ND()
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40030: sub 'Public Sub M()' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Sub M()
~
BC40030: property 'Public Property P As Integer' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Property P As Integer
~
BC40030: event 'Public Event E As Kinds.ND' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Event E As ND
~
BC40030: variable 'Public F As Integer' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public F As Integer
~
BC40030: class 'Kinds.NC' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Class NC
~~
BC40030: interface 'Kinds.NI' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Interface NI
~~
BC40030: structure 'Kinds.NS' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Structure NS
~~
BC40030: delegate Class 'Kinds.ND' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Delegate Sub ND()
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_CLSMemberInNonCLSType3_Implicit()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly:CLSCompliant(False)>
Public Class Kinds
<CLSCompliant(True)>
Public Sub M()
End Sub
<CLSCompliant(True)>
Public Property P As Integer
<CLSCompliant(True)>
Public Event E As ND
<CLSCompliant(True)>
Public F As Integer
<CLSCompliant(True)>
Public Class NC
End Class
<CLSCompliant(True)>
Public Interface NI
End Interface
<CLSCompliant(True)>
Public Structure NS
End Structure
<CLSCompliant(True)>
Public Delegate Sub ND()
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40030: sub 'Public Sub M()' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Sub M()
~
BC40030: property 'Public Property P As Integer' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Property P As Integer
~
BC40030: event 'Public Event E As Kinds.ND' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Event E As ND
~
BC40030: variable 'Public F As Integer' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public F As Integer
~
BC40030: class 'Kinds.NC' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Class NC
~~
BC40030: interface 'Kinds.NI' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Interface NI
~~
BC40030: structure 'Kinds.NS' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Structure NS
~~
BC40030: delegate Class 'Kinds.ND' cannot be marked CLS-compliant because its containing type 'Kinds' is not CLS-compliant.
Public Delegate Sub ND()
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_CLSMemberInNonCLSType3_Alternating()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<CLSCompliant(True)>
Public Class A
<CLSCompliant(False)>
Public Class B
<CLSCompliant(True)>
Public Class C
<CLSCompliant(False)>
Public Class D
<CLSCompliant(True)>
Public Class E
End Class
End Class
End Class
End Class
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40030: class 'A.B.C' cannot be marked CLS-compliant because its containing type 'A.B' is not CLS-compliant.
Public Class C
~
BC40030: class 'A.B.C.D.E' cannot be marked CLS-compliant because its containing type 'A.B.C.D' is not CLS-compliant.
Public Class E
~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_BaseClassNotCLSCompliant2()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class A
Inherits Bad
End Class
<CLSCompliant(False)>
Public Class Bad
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40026: 'A' is not CLS-compliant because it derives from 'Bad', which is not CLS-compliant.
Public Class A
~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_BaseClassNotCLSCompliant2_OtherAssemblies()
Dim lib1Source =
<compilation name="lib1">
<file name="a.vb">
<![CDATA[
Public Class Bad1
End Class
]]>
</file>
</compilation>
Dim lib2Source =
<compilation name="lib2">
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
<CLSCompliant(False)>
Public Class Bad2
End Class
]]>
</file>
</compilation>
Dim lib3Source =
<compilation name="lib3">
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(False)>
Public Class Bad3
End Class
]]>
</file>
</compilation>
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class A1
Inherits Bad1
End Class
Public Class A2
Inherits Bad2
End Class
Public Class A3
Inherits Bad3
End Class
]]>
</file>
</compilation>
Dim lib1Ref = CreateCompilationWithMscorlib40(lib1Source).EmitToImageReference()
Dim lib2Ref = CreateCompilationWithMscorlib40(lib2Source).EmitToImageReference()
Dim lib3Ref = CreateCompilationWithMscorlib40(lib3Source).EmitToImageReference()
CreateCompilationWithMscorlib40AndReferences(source, {lib1Ref, lib2Ref, lib3Ref}).AssertTheseDiagnostics(<errors><![CDATA[
BC40026: 'A1' is not CLS-compliant because it derives from 'Bad1', which is not CLS-compliant.
Public Class A1
~~
BC40026: 'A2' is not CLS-compliant because it derives from 'Bad2', which is not CLS-compliant.
Public Class A2
~~
BC40026: 'A3' is not CLS-compliant because it derives from 'Bad3', which is not CLS-compliant.
Public Class A3
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_InheritedInterfaceNotCLSCompliant2_Interface()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Interface A
Inherits Bad
End Interface
Public Interface B
Inherits Bad, Good
End Interface
Public Interface C
Inherits Good, Bad
End Interface
<CLSCompliant(True)>
Public Interface Good
End Interface
<CLSCompliant(False)>
Public Interface Bad
End Interface
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40029: 'A' is not CLS-compliant because the interface 'Bad' it inherits from is not CLS-compliant.
Public Interface A
~
BC40029: 'B' is not CLS-compliant because the interface 'Bad' it inherits from is not CLS-compliant.
Public Interface B
~
BC40029: 'C' is not CLS-compliant because the interface 'Bad' it inherits from is not CLS-compliant.
Public Interface C
~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_InheritedInterfaceNotCLSCompliant2_Class()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class A
Implements Bad
End Class
Public Class B
Implements Bad, Good
End Class
Public Class C
Implements Good, Bad
End Class
<CLSCompliant(True)>
Public Interface Good
End Interface
<CLSCompliant(False)>
Public Interface Bad
End Interface
]]>
</file>
</compilation>
' Implemented interfaces are not required to be compliant - only inherited ones.
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub WRN_NonCLSMemberInCLSInterface1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Interface A
Function M1() As Bad
<CLSCompliant(False)>
Sub M2()
End Interface
Public Interface Kinds
<CLSCompliant(False)>
Sub M()
<CLSCompliant(False)>
Property P()
<CLSCompliant(False)>
Event E As Action
End Interface
<CLSCompliant(False)>
Public Class Bad
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40027: Return type of function 'M1' is not CLS-compliant.
Function M1() As Bad
~~
BC40033: Non CLS-compliant 'Sub M2()' is not allowed in a CLS-compliant interface.
Sub M2()
~~
BC40033: Non CLS-compliant 'Sub M()' is not allowed in a CLS-compliant interface.
Sub M()
~
BC40033: Non CLS-compliant 'Property P As Object' is not allowed in a CLS-compliant interface.
Property P()
~
BC40033: Non CLS-compliant 'Event E As Action' is not allowed in a CLS-compliant interface.
Event E As Action
~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_NonCLSMustOverrideInCLSType1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public MustInherit Class A
Public MustOverride Function M1() As Bad
<CLSCompliant(False)>
Public MustOverride Sub M2()
End Class
Public MustInherit Class Kinds
<CLSCompliant(False)>
Public MustOverride Sub M()
<CLSCompliant(False)>
Public MustOverride Property P()
' VB doesn't support generic events
Public MustInherit Class C
End Class
End Class
<CLSCompliant(False)>
Public Class Bad
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40027: Return type of function 'M1' is not CLS-compliant.
Public MustOverride Function M1() As Bad
~~
BC40034: Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type 'A'.
Public MustOverride Sub M2()
~~
BC40034: Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type 'Kinds'.
Public MustOverride Sub M()
~
BC40034: Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type 'Kinds'.
Public MustOverride Property P()
~
]]></errors>)
End Sub
<Fact>
Public Sub AbstractInCompliant_NoAssemblyAttribute()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<CLSCompliant(True)> Public Interface IFace
<CLSCompliant(False)> Property Prop1() As Long
<CLSCompliant(False)> Function F2() As Integer
<CLSCompliant(False)> Event EV3(ByVal i3 As Integer)
<CLSCompliant(False)> Sub Sub4()
End Interface
<CLSCompliant(True)> Public MustInherit Class QuiteCompliant
<CLSCompliant(False)> Public MustOverride Sub Sub1()
<CLSCompliant(False)> Protected MustOverride Function Fun2() As Integer
<CLSCompliant(False)> Protected Friend MustOverride Sub Sub3()
<CLSCompliant(False)> Friend MustOverride Function Fun4(ByVal x As Long) As Long
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40033: Non CLS-compliant 'Property Prop1 As Long' is not allowed in a CLS-compliant interface.
<CLSCompliant(False)> Property Prop1() As Long
~~~~~
BC40033: Non CLS-compliant 'Function F2() As Integer' is not allowed in a CLS-compliant interface.
<CLSCompliant(False)> Function F2() As Integer
~~
BC40033: Non CLS-compliant 'Event EV3(i3 As Integer)' is not allowed in a CLS-compliant interface.
<CLSCompliant(False)> Event EV3(ByVal i3 As Integer)
~~~
BC40033: Non CLS-compliant 'Sub Sub4()' is not allowed in a CLS-compliant interface.
<CLSCompliant(False)> Sub Sub4()
~~~~
BC40034: Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type 'QuiteCompliant'.
<CLSCompliant(False)> Public MustOverride Sub Sub1()
~~~~
BC40034: Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type 'QuiteCompliant'.
<CLSCompliant(False)> Protected MustOverride Function Fun2() As Integer
~~~~
BC40034: Non CLS-compliant 'MustOverride' member is not allowed in CLS-compliant type 'QuiteCompliant'.
<CLSCompliant(False)> Protected Friend MustOverride Sub Sub3()
~~~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_GenericConstraintNotCLSCompliant1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C1(Of t As {Good, Bad}, u As {Bad, Good})
End Class
<CLSCompliant(False)>
Public Class C2(Of t As {Good, Bad}, u As {Bad, Good})
End Class
Public Delegate Sub D1(Of t As {Good, Bad}, u As {Bad, Good})()
<CLSCompliant(False)>
Public Delegate Sub D2(Of t As {Good, Bad}, u As {Bad, Good})()
Public Class C
Public Sub M1(Of t As {Good, Bad}, u As {Bad, Good})()
End Sub
<CLSCompliant(False)>
Public Sub M2(Of t As {Good, Bad}, u As {Bad, Good})()
End Sub
End Class
<CLSCompliant(True)>
Public Interface Good
End Interface
<CLSCompliant(False)>
Public Interface Bad
End Interface
]]>
</file>
</compilation>
' NOTE: Dev11 squiggles the problematic constraint, but we don't have enough info.
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40040: Generic parameter constraint type 'Bad' is not CLS-compliant.
Public Class C1(Of t As {Good, Bad}, u As {Bad, Good})
~
BC40040: Generic parameter constraint type 'Bad' is not CLS-compliant.
Public Class C1(Of t As {Good, Bad}, u As {Bad, Good})
~
BC40040: Generic parameter constraint type 'Bad' is not CLS-compliant.
Public Delegate Sub D1(Of t As {Good, Bad}, u As {Bad, Good})()
~
BC40040: Generic parameter constraint type 'Bad' is not CLS-compliant.
Public Delegate Sub D1(Of t As {Good, Bad}, u As {Bad, Good})()
~
BC40040: Generic parameter constraint type 'Bad' is not CLS-compliant.
Public Sub M1(Of t As {Good, Bad}, u As {Bad, Good})()
~
BC40040: Generic parameter constraint type 'Bad' is not CLS-compliant.
Public Sub M1(Of t As {Good, Bad}, u As {Bad, Good})()
~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_FieldNotCLSCompliant1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class Kinds1
Public F1 As Bad
Private F2 As Bad
End Class
<CLSCompliant(False)>
Public Class Kinds2
Public F3 As Bad
Private F4 As Bad
End Class
<CLSCompliant(False)>
Public Interface Bad
End Interface
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40025: Type of member 'F1' is not CLS-compliant.
Public F1 As Bad
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_ProcTypeNotCLSCompliant1_Method()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C1
Public Function M1() As Bad
Throw New Exception()
End Function
Public Function M2() As Generic(Of Bad)
Throw New Exception()
End Function
Public Function M3() As Generic(Of Generic(Of Bad))
Throw New Exception()
End Function
Public Function M4() As Bad()
Throw New Exception()
End Function
Public Function M5() As Bad()()
Throw New Exception()
End Function
Public Function M6() As Bad(,)
Throw New Exception()
End Function
End Class
<CLSCompliant(False)>
Public Class C2
Public Function N1() As Bad
Throw New Exception()
End Function
Public Function N2() As Generic(Of Bad)
Throw New Exception()
End Function
Public Function N3() As Generic(Of Generic(Of Bad))
Throw New Exception()
End Function
Public Function N4() As Bad()
Throw New Exception()
End Function
Public Function N5() As Bad()()
Throw New Exception()
End Function
Public Function N6() As Bad(,)
Throw New Exception()
End Function
End Class
Public Class Generic(Of T)
End Class
<CLSCompliant(False)>
Public Interface Bad
End Interface
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40027: Return type of function 'M1' is not CLS-compliant.
Public Function M1() As Bad
~~
BC40041: Type 'Bad' is not CLS-compliant.
Public Function M2() As Generic(Of Bad)
~~
BC40041: Type 'Bad' is not CLS-compliant.
Public Function M3() As Generic(Of Generic(Of Bad))
~~
BC40027: Return type of function 'M4' is not CLS-compliant.
Public Function M4() As Bad()
~~
BC40027: Return type of function 'M5' is not CLS-compliant.
Public Function M5() As Bad()()
~~
BC40027: Return type of function 'M6' is not CLS-compliant.
Public Function M6() As Bad(,)
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_ProcTypeNotCLSCompliant1_Property()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C1
Public Property P1() As Bad
Public Property P2() As Generic(Of Bad)
Public Property P3() As Generic(Of Generic(Of Bad))
Public Property P4() As Bad()
Public Property P5() As Bad()()
Public Property P6() As Bad(,)
End Class
<CLSCompliant(False)>
Public Class C2
Public Property Q1() As Bad
Public Property Q2() As Generic(Of Bad)
Public Property Q3() As Generic(Of Generic(Of Bad))
Public Property Q4() As Bad()
Public Property Q5() As Bad()()
Public Property Q6() As Bad(,)
End Class
Public Class Generic(Of T)
End Class
<CLSCompliant(False)>
Public Interface Bad
End Interface
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40027: Return type of function 'P1' is not CLS-compliant.
Public Property P1() As Bad
~~
BC40041: Type 'Bad' is not CLS-compliant.
Public Property P2() As Generic(Of Bad)
~~
BC40041: Type 'Bad' is not CLS-compliant.
Public Property P3() As Generic(Of Generic(Of Bad))
~~
BC40027: Return type of function 'P4' is not CLS-compliant.
Public Property P4() As Bad()
~~
BC40027: Return type of function 'P5' is not CLS-compliant.
Public Property P5() As Bad()()
~~
BC40027: Return type of function 'P6' is not CLS-compliant.
Public Property P6() As Bad(,)
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_ProcTypeNotCLSCompliant1_Delegate()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C1
Public Delegate Function M1() As Bad
Public Delegate Function M2() As Generic(Of Bad)
Public Delegate Function M3() As Generic(Of Generic(Of Bad))
Public Delegate Function M4() As Bad()
Public Delegate Function M5() As Bad()()
Public Delegate Function M6() As Bad(,)
End Class
<CLSCompliant(False)>
Public Class C2
Public Delegate Function N1() As Bad
Public Delegate Function N2() As Generic(Of Bad)
Public Delegate Function N3() As Generic(Of Generic(Of Bad))
Public Delegate Function N4() As Bad()
Public Delegate Function N5() As Bad()()
Public Delegate Function N6() As Bad(,)
End Class
Public Class Generic(Of T)
End Class
<CLSCompliant(False)>
Public Interface Bad
End Interface
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40027: Return type of function 'Invoke' is not CLS-compliant.
Public Delegate Function M1() As Bad
~~
BC40041: Type 'Bad' is not CLS-compliant.
Public Delegate Function M2() As Generic(Of Bad)
~~
BC40041: Type 'Bad' is not CLS-compliant.
Public Delegate Function M3() As Generic(Of Generic(Of Bad))
~~
BC40027: Return type of function 'Invoke' is not CLS-compliant.
Public Delegate Function M4() As Bad()
~~
BC40027: Return type of function 'Invoke' is not CLS-compliant.
Public Delegate Function M5() As Bad()()
~~
BC40027: Return type of function 'Invoke' is not CLS-compliant.
Public Delegate Function M6() As Bad(,)
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_ParamNotCLSCompliant1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C1
Public Function M1(p As Bad)
Throw New Exception()
End Function
Public Function M2(p As Generic(Of Bad))
Throw New Exception()
End Function
Public Function M3(p As Generic(Of Generic(Of Bad)))
Throw New Exception()
End Function
Public Function M4(p As Bad())
Throw New Exception()
End Function
Public Function M5(p As Bad()())
Throw New Exception()
End Function
Public Function M6(p As Bad(,))
Throw New Exception()
End Function
End Class
<CLSCompliant(False)>
Public Class C2
Public Function N1(p As Bad)
Throw New Exception()
End Function
Public Function N2(p As Generic(Of Bad))
Throw New Exception()
End Function
Public Function N3(p As Generic(Of Generic(Of Bad)))
Throw New Exception()
End Function
Public Function N4(p As Bad())
Throw New Exception()
End Function
Public Function N5(p As Bad()())
Throw New Exception()
End Function
Public Function N6(p As Bad(,))
Throw New Exception()
End Function
End Class
Public Class Generic(Of T)
End Class
<CLSCompliant(False)>
Public Interface Bad
End Interface
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40028: Type of parameter 'p' is not CLS-compliant.
Public Function M1(p As Bad)
~
BC40041: Type 'Bad' is not CLS-compliant.
Public Function M2(p As Generic(Of Bad))
~
BC40041: Type 'Bad' is not CLS-compliant.
Public Function M3(p As Generic(Of Generic(Of Bad)))
~
BC40028: Type of parameter 'p' is not CLS-compliant.
Public Function M4(p As Bad())
~
BC40028: Type of parameter 'p' is not CLS-compliant.
Public Function M5(p As Bad()())
~
BC40028: Type of parameter 'p' is not CLS-compliant.
Public Function M6(p As Bad(,))
~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_ParamNotCLSCompliant1_Kinds()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Interface I1
Sub M(x As Bad)
Property P(x As Bad) As Integer
Delegate Sub D(x As Bad)
End Interface
<CLSCompliant(False)>
Public Interface I2
Sub M(x As Bad)
Property P(x As Bad) As Integer
Delegate Sub D(x As Bad)
End Interface
<CLSCompliant(False)>
Public Interface Bad
End Interface
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40028: Type of parameter 'x' is not CLS-compliant.
Sub M(x As Bad)
~
BC40028: Type of parameter 'x' is not CLS-compliant.
Property P(x As Bad) As Integer
~
BC40028: Type of parameter 'x' is not CLS-compliant.
Delegate Sub D(x As Bad)
~
]]></errors>)
End Sub
' From LegacyTest\CSharp\Source\csharp\Source\ClsCompliance\generics\Rule_E_01.cs
<Fact>
Public Sub WRN_ParamNotCLSCompliant1_ConstructedTypeAccessibility()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C(Of T)
Protected Class N
End Class
' Not CLS-compliant since C(Of Integer).N is not accessible within C(Of T) in all languages.
Protected Sub M1(n As C(Of Integer).N)
End Sub
' Fine
Protected Sub M2(n As C(Of T).N)
End Sub
Protected Class N2
' Not CLS-compliant
Protected Sub M3(n As C(Of ULong).N)
End Sub
End Class
End Class
Public Class D
Inherits C(Of Long)
' Not CLS-compliant
Protected Sub M4(n As C(Of Integer).N)
End Sub
' Fine
Protected Sub M5(n As C(Of Long).N)
End Sub
End Class
]]>
</file>
</compilation>
' Dev11 produces error BC30508 for M1 and M3
' Dev11 produces error BC30389 for M4 and M5
' Roslyn dropped these errors (since they weren't helpful) and, instead, reports CLS warnings.
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub WRN_ParamNotCLSCompliant1_ProtectedContainer()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C1(Of T)
Protected Class C2(Of U)
Public Class C3(Of V)
Public Sub M(Of W)(p As C1(Of Integer).C2(Of U))
End Sub
Public Sub M(Of W)(p As C1(Of Integer).C2(Of U).C3(Of V))
End Sub
End Class
End Class
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub AttributeConstructorsWithArrayParameters()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class EmptyAttribute
Inherits Attribute
End Class
Public Class PublicAttribute
Inherits Attribute
' Not accessible
Friend Sub New()
End Sub
' Not compliant
<CLSCompliant(False)>
Public Sub New(x As Integer)
End Sub
' Array argument
Public Sub New(a As Integer(,))
End Sub
' Array argument
Public Sub New(ParamArray a As Char())
End Sub
End Class
Friend Class InternalAttribute
Inherits Attribute
' Not accessible
Public Sub New()
End Sub
End Class
<CLSCompliant(False)>
Public Class BadAttribute
Inherits Attribute
' Fine, since type isn't compliant.
Public Sub New(array As Integer())
End Sub
End Class
Public Class NotAnAttribute
' Fine, since not an attribute type.
Public Sub New(array As Integer())
End Sub
End Class
]]>
</file>
</compilation>
' NOTE: C# requires that compliant attributes have at least one
' accessible constructor with no attribute parameters.
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub AttributeConstructorsWithNonPredefinedParameters()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class MyAttribute
Inherits Attribute
Public Sub New(m As MyAttribute)
End Sub
End Class
]]>
</file>
</compilation>
' CLS only allows System.Type, string, char, bool, byte, short, int, long, float, double, and enums,
' but dev11 does not enforce this.
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub ArrayArgumentToAttribute()
Dim source =
<compilation>
<file name="a.vb">
<>
Public Class B
End Class
<InternalArray({1})>
Public Class C
End Class
<NamedArgument(O:={1})>
Public Class D
End Class
]]>
</file>
</compilation>
' CLS only allows System.Type, string, char, bool, byte, short, int, long, float, double, and enums,
' but dev11 does not enforce this.
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub WRN_NameNotCLSCompliant1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class _A
End Class
Public Class B_
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40031: Name '_A' is not CLS-compliant.
Public Class _A
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_NameNotCLSCompliant1_Kinds()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class Kinds
Public Sub _M()
End Sub
Public Property _P As Integer
Public Event _E As _ND
Public _F As Integer
Public Class _NC
End Class
Public Interface _NI
End Interface
Public Structure _NS
End Structure
Public Delegate Sub _ND()
Private _Private As Integer
<CLSCompliant(False)>
Public _NonCompliant As Integer
End Class
Namespace _NS1
End Namespace
Namespace NS1._NS2
End Namespace
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40031: Name '_M' is not CLS-compliant.
Public Sub _M()
~~
BC40031: Name '_P' is not CLS-compliant.
Public Property _P As Integer
~~
BC40031: Name '_E' is not CLS-compliant.
Public Event _E As _ND
~~
BC40031: Name '_F' is not CLS-compliant.
Public _F As Integer
~~
BC40031: Name '_NC' is not CLS-compliant.
Public Class _NC
~~~
BC40031: Name '_NI' is not CLS-compliant.
Public Interface _NI
~~~
BC40031: Name '_NS' is not CLS-compliant.
Public Structure _NS
~~~
BC40031: Name '_ND' is not CLS-compliant.
Public Delegate Sub _ND()
~~~
BC40031: Name '_NS1' is not CLS-compliant.
Namespace _NS1
~~~~
BC40031: Name '_NS2' is not CLS-compliant.
Namespace NS1._NS2
~~~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_NameNotCLSCompliant1_Overrides()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class Base
Public Overridable Sub _M()
End Sub
End Class
Public Class Derived
Inherits Base
Public Overrides Sub _M()
End Sub
End Class
]]>
</file>
</compilation>
' NOTE: C# doesn't report this warning on overrides.
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40031: Name '_M' is not CLS-compliant.
Public Overridable Sub _M()
~~
BC40031: Name '_M' is not CLS-compliant.
Public Overrides Sub _M()
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_NameNotCLSCompliant1_NotReferencable()
Dim il = <![CDATA[
.class public abstract auto ansi B
{
.custom instance void [mscorlib]System.CLSCompliantAttribute::.ctor(bool) = {bool(true)}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.method public hidebysig newslot specialname abstract virtual
instance int32 _getter() cil managed
{
}
.property instance int32 P()
{
.get instance int32 B::_getter()
}
}
]]>
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Inherits B
Public Overrides ReadOnly Property P As Integer
Get
Return 0
End Get
End Property
End Class
]]>
</file>
</compilation>
Dim comp = CreateCompilationWithCustomILSource(source, il)
comp.AssertNoDiagnostics()
Dim accessor = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").GetMember(Of PropertySymbol)("P").GetMethod
Assert.True(accessor.MetadataName.StartsWith("_", StringComparison.Ordinal))
End Sub
<Fact>
Public Sub WRN_NameNotCLSCompliant1_Parameter()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class B
Public Sub M(_p As Integer)
End Sub
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub ModuleLevel_NoAssemblyLevel()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Module: CLSCompliant(True)>
]]>
</file>
</compilation>
' C# warns.
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Module: CLSCompliant(False)>
]]>
</file>
</compilation>
' C# warns.
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub ModuleLevel_DisagreesWithAssemblyLevel()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(False)>
<Module: CLSCompliant(True)>
]]>
</file>
</compilation>
' C# warns.
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
<Module: CLSCompliant(False)>
]]>
</file>
</compilation>
' C# warns.
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub DroppedAttributes()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(False)>
<Module: CLSCompliant(True)>
]]>
</file>
</compilation>
Dim validator = Function(expectAssemblyLevel As Boolean, expectModuleLevel As Boolean) _
Sub(m As ModuleSymbol)
Dim predicate = Function(attr As VisualBasicAttributeData) attr.AttributeClass.Name = "CLSCompliantAttribute"
If expectModuleLevel Then
AssertEx.Any(m.GetAttributes(), predicate)
Else
AssertEx.None(m.GetAttributes(), predicate)
End If
If expectAssemblyLevel Then
AssertEx.Any(m.ContainingAssembly.GetAttributes(), predicate)
ElseIf m.ContainingAssembly IsNot Nothing Then
AssertEx.None(m.ContainingAssembly.GetAttributes(), predicate)
End If
End Sub
CompileAndVerify(source, options:=TestOptions.ReleaseDll, sourceSymbolValidator:=validator(True, True), symbolValidator:=validator(True, False))
CompileAndVerify(source, options:=TestOptions.ReleaseModule, sourceSymbolValidator:=validator(True, True), symbolValidator:=validator(False, True), verify:=Verification.Fails) ' PEVerify doesn't like netmodules
End Sub
<Fact>
Public Sub ConflictingAssemblyLevelAttributes_ModuleVsAssembly()
Dim source =
<compilation name="A">
<file name="a.vb">
<![CDATA[
<Assembly: System.CLSCompliant(False)>
]]>
</file>
</compilation>
Dim moduleComp = CreateCSharpCompilation("[assembly:System.CLSCompliant(true)]", compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.NetModule), assemblyName:="A")
Dim moduleRef = moduleComp.EmitToImageReference()
CreateCompilationWithMscorlib40AndReferences(source, {moduleRef}).AssertTheseDiagnostics(<errors><![CDATA[
BC36978: Attribute 'CLSCompliantAttribute' in 'A.netmodule' cannot be applied multiple times.
]]></errors>)
End Sub
<Fact>
Public Sub ConflictingAssemblyLevelAttributes_ModuleVsModule()
Dim source =
<compilation name="A">
<file name="a.vb">
</file>
</compilation>
Dim moduleComp1 = CreateCSharpCompilation("[assembly:System.CLSCompliant(true)]", compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.NetModule), assemblyName:="A")
Dim moduleRef1 = moduleComp1.EmitToImageReference()
Dim moduleComp2 = CreateCSharpCompilation("[assembly:System.CLSCompliant(false)]", compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.NetModule), assemblyName:="B")
Dim moduleRef2 = moduleComp2.EmitToImageReference()
CreateCompilationWithMscorlib40AndReferences(source, {moduleRef1, moduleRef2}).AssertTheseDiagnostics(<errors><![CDATA[
BC36978: Attribute 'CLSCompliantAttribute' in 'A.netmodule' cannot be applied multiple times.
]]></errors>)
End Sub
<Fact>
Public Sub AssemblyIgnoresModuleAttribute()
Dim source =
<compilation name="A">
<file name="a.vb">
<![CDATA[
Imports System
<Module: Clscompliant(True)>
<CLSCompliant(True)>
Public Class Test
Inherits Bad
End Class
' Doesn't inherit True from module, so not compliant.
Public Class Bad
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40026: 'Test' is not CLS-compliant because it derives from 'Bad', which is not CLS-compliant.
Public Class Test
~~~~
]]></errors>)
End Sub
<Fact>
Public Sub ModuleIgnoresAssemblyAttribute()
Dim source =
<compilation name="A">
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: Clscompliant(True)>
<CLSCompliant(True)>
Public Class Test
Inherits Bad
End Class
' Doesn't inherit True from assembly, so not compliant.
Public Class Bad
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source, OutputKind.NetModule).AssertTheseDiagnostics(<errors><![CDATA[
BC40026: 'Test' is not CLS-compliant because it derives from 'Bad', which is not CLS-compliant.
Public Class Test
~~~~
]]></errors>)
End Sub
<Fact>
Public Sub IgnoreModuleAttributeInReferencedAssembly()
Dim source =
<compilation name="A">
<file name="a.vb"><![CDATA[
Imports System
<CLSCompliant(True)>
Public Class Test
Inherits Bad
End Class
]]></file>
</compilation>
Dim assemblyLevelLibSource = <![CDATA[
[assembly:System.CLSCompliant(true)]
public class Bad { }
]]>
Dim moduleLevelLibSource = <![CDATA[
[module:System.CLSCompliant(true)]
public class Bad { }
]]>
Dim assemblyLevelLibRef = CreateCSharpCompilation(assemblyLevelLibSource).EmitToImageReference()
Dim moduleLevelLibRef = CreateCSharpCompilation(moduleLevelLibSource).EmitToImageReference(Nothing) ' suppress warning
' Attribute respected.
CreateCompilationWithMscorlib40AndReferences(source, {assemblyLevelLibRef}).AssertNoDiagnostics()
' Attribute not respected.
CreateCompilationWithMscorlib40AndReferences(source, {moduleLevelLibRef}).AssertTheseDiagnostics(<errors><![CDATA[
BC40026: 'Test' is not CLS-compliant because it derives from 'Bad', which is not CLS-compliant.
Public Class Test
~~~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_EnumUnderlyingTypeNotCLS1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Enum E1 As UInteger
A
End Enum
Friend Enum E2 As UInteger
A
End Enum
<CLSCompliant(False)>
Friend Enum E3 As UInteger
A
End Enum
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40032: Underlying type 'UInteger' of Enum is not CLS-compliant.
Public Enum E1 As UInteger
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_TypeNotCLSCompliant1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(False)>
Public Class Bad1
End Class
Public Class Bad2
End Class
Public Class BadGeneric(Of T, U)
End Class
<CLSCompliant(True)>
Public Class Good
End Class
<CLSCompliant(True)>
Public Class GoodGeneric(Of T, U)
End Class
<CLSCompliant(True)>
Public Class Test
' Reported within compliant generic types.
Public x1 As GoodGeneric(Of Good, Good) ' Fine
Public x2 As GoodGeneric(Of Good, Bad1)
Public x3 As GoodGeneric(Of Bad1, Good)
Public x4 As GoodGeneric(Of Bad1, Bad2) ' Both reported
' Reported within non-compliant generic types.
Public Property y1 As BadGeneric(Of Good, Good)
Public Property y2 As BadGeneric(Of Good, Bad1)
Public Property y3 As BadGeneric(Of Bad1, Good)
Public Property y4 As BadGeneric(Of Bad1, Bad2) ' Both reported
Public z1 As GoodGeneric(Of GoodGeneric(Of Bad1, Good), GoodGeneric(Of Bad1, Good))
Public z2 As GoodGeneric(Of BadGeneric(Of Bad1, Good), BadGeneric(Of Bad1, Good)) ' Reported at multiple levels
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40041: Type 'Bad1' is not CLS-compliant.
Public x2 As GoodGeneric(Of Good, Bad1)
~~
BC40041: Type 'Bad1' is not CLS-compliant.
Public x3 As GoodGeneric(Of Bad1, Good)
~~
BC40041: Type 'Bad1' is not CLS-compliant.
Public x4 As GoodGeneric(Of Bad1, Bad2) ' Both reported
~~
BC40041: Type 'Bad2' is not CLS-compliant.
Public x4 As GoodGeneric(Of Bad1, Bad2) ' Both reported
~~
BC40027: Return type of function 'y1' is not CLS-compliant.
Public Property y1 As BadGeneric(Of Good, Good)
~~
BC40027: Return type of function 'y2' is not CLS-compliant.
Public Property y2 As BadGeneric(Of Good, Bad1)
~~
BC40041: Type 'Bad1' is not CLS-compliant.
Public Property y2 As BadGeneric(Of Good, Bad1)
~~
BC40027: Return type of function 'y3' is not CLS-compliant.
Public Property y3 As BadGeneric(Of Bad1, Good)
~~
BC40041: Type 'Bad1' is not CLS-compliant.
Public Property y3 As BadGeneric(Of Bad1, Good)
~~
BC40027: Return type of function 'y4' is not CLS-compliant.
Public Property y4 As BadGeneric(Of Bad1, Bad2) ' Both reported
~~
BC40041: Type 'Bad1' is not CLS-compliant.
Public Property y4 As BadGeneric(Of Bad1, Bad2) ' Both reported
~~
BC40041: Type 'Bad2' is not CLS-compliant.
Public Property y4 As BadGeneric(Of Bad1, Bad2) ' Both reported
~~
BC40041: Type 'Bad1' is not CLS-compliant.
Public z1 As GoodGeneric(Of GoodGeneric(Of Bad1, Good), GoodGeneric(Of Bad1, Good))
~~
BC40041: Type 'Bad1' is not CLS-compliant.
Public z1 As GoodGeneric(Of GoodGeneric(Of Bad1, Good), GoodGeneric(Of Bad1, Good))
~~
BC40041: Type 'Bad1' is not CLS-compliant.
Public z2 As GoodGeneric(Of BadGeneric(Of Bad1, Good), BadGeneric(Of Bad1, Good)) ' Reported at multiple levels
~~
BC40041: Type 'Bad1' is not CLS-compliant.
Public z2 As GoodGeneric(Of BadGeneric(Of Bad1, Good), BadGeneric(Of Bad1, Good)) ' Reported at multiple levels
~~
BC40041: Type 'BadGeneric(Of Bad1, Good)' is not CLS-compliant.
Public z2 As GoodGeneric(Of BadGeneric(Of Bad1, Good), BadGeneric(Of Bad1, Good)) ' Reported at multiple levels
~~
BC40041: Type 'BadGeneric(Of Bad1, Good)' is not CLS-compliant.
Public z2 As GoodGeneric(Of BadGeneric(Of Bad1, Good), BadGeneric(Of Bad1, Good)) ' Reported at multiple levels
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_RootNamespaceNotCLSCompliant1()
Dim source1 =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(False)>
]]>
</file>
</compilation>
' Nothing reported since the namespace inherits CLSCompliant(False) from the assembly.
CreateCompilationWithMscorlib40(source1, options:=TestOptions.ReleaseDll.WithRootNamespace("_A")).AssertNoDiagnostics()
Dim source2 =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source2, options:=TestOptions.ReleaseDll.WithRootNamespace("_A")).AssertTheseDiagnostics(<errors><![CDATA[
BC40038: Root namespace '_A' is not CLS-compliant.
]]></errors>)
Dim source3 =
<compilation>
<file name="a.vb">
<![CDATA[
Public Class Test
End Class
]]>
</file>
</compilation>
Dim moduleRef = CreateCompilationWithMscorlib40(source3, options:=TestOptions.ReleaseModule).EmitToImageReference()
CreateCompilationWithMscorlib40AndReferences(source2, {moduleRef}, options:=TestOptions.ReleaseDll.WithRootNamespace("_A").WithConcurrentBuild(False)).AssertTheseDiagnostics(<errors><![CDATA[
BC40038: Root namespace '_A' is not CLS-compliant.
]]></errors>)
Dim source4 =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Module: CLSCompliant(True)>
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40AndReferences(source4, {moduleRef}, options:=TestOptions.ReleaseModule.WithRootNamespace("_A").WithConcurrentBuild(True)).AssertTheseDiagnostics(<errors><![CDATA[
BC40038: Root namespace '_A' is not CLS-compliant.
]]></errors>)
CreateCompilationWithMscorlib40AndReferences(source2, {moduleRef}, options:=TestOptions.ReleaseModule.WithRootNamespace("_A")).AssertTheseDiagnostics()
End Sub
<Fact>
Public Sub WRN_RootNamespaceNotCLSCompliant2()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll.WithRootNamespace("_A.B.C")).AssertTheseDiagnostics(<errors><![CDATA[
BC40039: Name '_A' in the root namespace '_A.B.C' is not CLS-compliant.
]]></errors>)
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll.WithRootNamespace("A._B.C")).AssertTheseDiagnostics(<errors><![CDATA[
BC40039: Name '_B' in the root namespace 'A._B.C' is not CLS-compliant.
]]></errors>)
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll.WithRootNamespace("A.B._C")).AssertTheseDiagnostics(<errors><![CDATA[
BC40039: Name '_C' in the root namespace 'A.B._C' is not CLS-compliant.
]]></errors>)
CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll.WithRootNamespace("_A.B._C")).AssertTheseDiagnostics(<errors><![CDATA[
BC40039: Name '_A' in the root namespace '_A.B._C' is not CLS-compliant.
BC40039: Name '_C' in the root namespace '_A.B._C' is not CLS-compliant.
]]></errors>)
End Sub
<Fact>
Public Sub WRN_OptionalValueNotCLSCompliant1()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Public Sub M(Optional x00 As Object = SByte.MaxValue,
Optional x01 As Object = Byte.MaxValue,
Optional x02 As Object = Short.MaxValue,
Optional x03 As Object = UShort.MaxValue,
Optional x04 As Object = Integer.MaxValue,
Optional x05 As Object = UInteger.MaxValue,
Optional x06 As Object = Long.MaxValue,
Optional x07 As Object = ULong.MaxValue,
Optional x08 As Object = Char.MaxValue,
Optional x09 As Object = True,
Optional x10 As Object = Single.MaxValue,
Optional x11 As Object = Double.MaxValue,
Optional x12 As Object = Decimal.MaxValue,
Optional x13 As Object = "ABC",
Optional x14 As Object = #1/1/2001#)
End Sub
End Class
]]>
</file>
</compilation>
' As in dev11, this only applies to int8, uint16, uint32, and uint64
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40042: Type of optional value for optional parameter 'x00' is not CLS-compliant.
Public Sub M(Optional x00 As Object = SByte.MaxValue,
~~~
BC40042: Type of optional value for optional parameter 'x03' is not CLS-compliant.
Optional x03 As Object = UShort.MaxValue,
~~~
BC40042: Type of optional value for optional parameter 'x05' is not CLS-compliant.
Optional x05 As Object = UInteger.MaxValue,
~~~
BC40042: Type of optional value for optional parameter 'x07' is not CLS-compliant.
Optional x07 As Object = ULong.MaxValue,
~~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_OptionalValueNotCLSCompliant1_ParameterTypeNonCompliant()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Public Sub M(Optional x00 As SByte = SByte.MaxValue)
End Sub
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40028: Type of parameter 'x00' is not CLS-compliant.
Public Sub M(Optional x00 As SByte = SByte.MaxValue)
~~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_CLSAttrInvalidOnGetSet_True()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<CLSCompliant(True)>
Public Class C
<CLSCompliant(False)>
Public Property P1 As UInteger
<CLSCompliant(True)>
Get
Return 0
End Get
<CLSCompliant(True)>
Set(value As UInteger)
End Set
End Property
<CLSCompliant(False)>
Public ReadOnly Property P2 As UInteger
<CLSCompliant(True)>
Get
Return 0
End Get
End Property
<CLSCompliant(False)>
Public WriteOnly Property P3 As UInteger
<CLSCompliant(True)>
Set(value As UInteger)
End Set
End Property
End Class
]]>
</file>
</compilation>
' NOTE: No warnings about non-compliant type UInteger.
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'.
<CLSCompliant(True)>
~~~~~~~~~~~~~~~~~~
BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'.
<CLSCompliant(True)>
~~~~~~~~~~~~~~~~~~
BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'.
<CLSCompliant(True)>
~~~~~~~~~~~~~~~~~~
BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'.
<CLSCompliant(True)>
~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_CLSAttrInvalidOnGetSet_False()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<CLSCompliant(True)>
Public Class C
<CLSCompliant(True)>
Public Property P1 As UInteger
<CLSCompliant(False)>
Get
Return 0
End Get
<CLSCompliant(False)>
Set(value As UInteger)
End Set
End Property
<CLSCompliant(True)>
Public ReadOnly Property P2 As UInteger
<CLSCompliant(False)>
Get
Return 0
End Get
End Property
<CLSCompliant(True)>
Public WriteOnly Property P3 As UInteger
<CLSCompliant(False)>
Set(value As UInteger)
End Set
End Property
End Class
]]>
</file>
</compilation>
' NOTE: See warnings about non-compliant type UInteger.
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40027: Return type of function 'P1' is not CLS-compliant.
Public Property P1 As UInteger
~~
BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'.
<CLSCompliant(False)>
~~~~~~~~~~~~~~~~~~~
BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'.
<CLSCompliant(False)>
~~~~~~~~~~~~~~~~~~~
BC40027: Return type of function 'P2' is not CLS-compliant.
Public ReadOnly Property P2 As UInteger
~~
BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'.
<CLSCompliant(False)>
~~~~~~~~~~~~~~~~~~~
BC40027: Return type of function 'P3' is not CLS-compliant.
Public WriteOnly Property P3 As UInteger
~~
BC40043: System.CLSCompliantAttribute cannot be applied to property 'Get' or 'Set'.
<CLSCompliant(False)>
~~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_CLSEventMethodInNonCLSType3()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<CLSCompliant(False)>
Public Class C
Public Custom Event E1 As Action(Of UInteger)
<CLSCompliant(True)>
AddHandler(value As Action(Of UInteger))
End AddHandler
<CLSCompliant(True)>
RemoveHandler(value As Action(Of UInteger))
End RemoveHandler
<CLSCompliant(True)>
RaiseEvent()
End RaiseEvent
End Event
<CLSCompliant(False)>
Public Custom Event E2 As Action(Of UInteger)
<CLSCompliant(True)>
AddHandler(value As Action(Of UInteger))
End AddHandler
<CLSCompliant(True)>
RemoveHandler(value As Action(Of UInteger))
End RemoveHandler
<CLSCompliant(True)>
RaiseEvent()
End RaiseEvent
End Event
End Class
]]>
</file>
</compilation>
' NOTE: No warnings about non-compliant type UInteger.
' NOTE: No warnings about RaiseEvent accessors.
' NOTE: CLSCompliant(False) on event doesn't suppress warnings.
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40053: 'AddHandler' method for event 'E1' cannot be marked CLS compliant because its containing type 'C' is not CLS compliant.
<CLSCompliant(True)>
~~~~~~~~~~~~~~~~~~
BC40053: 'RemoveHandler' method for event 'E1' cannot be marked CLS compliant because its containing type 'C' is not CLS compliant.
<CLSCompliant(True)>
~~~~~~~~~~~~~~~~~~
BC40053: 'AddHandler' method for event 'E2' cannot be marked CLS compliant because its containing type 'C' is not CLS compliant.
<CLSCompliant(True)>
~~~~~~~~~~~~~~~~~~
BC40053: 'RemoveHandler' method for event 'E2' cannot be marked CLS compliant because its containing type 'C' is not CLS compliant.
<CLSCompliant(True)>
~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
Public Sub EventAccessors()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<CLSCompliant(True)>
Public Class C
<CLSCompliant(False)>
Public Custom Event E1 As Action(Of UInteger)
<CLSCompliant(True)>
AddHandler(value As Action(Of UInteger))
End AddHandler
<CLSCompliant(True)>
RemoveHandler(value As Action(Of UInteger))
End RemoveHandler
<CLSCompliant(True)>
RaiseEvent()
End RaiseEvent
End Event
<CLSCompliant(True)>
Public Custom Event E2 As Action(Of UInteger)
<CLSCompliant(False)>
AddHandler(value As Action(Of UInteger))
End AddHandler
<CLSCompliant(False)>
RemoveHandler(value As Action(Of UInteger))
End RemoveHandler
<CLSCompliant(False)>
RaiseEvent()
End RaiseEvent
End Event
End Class
]]>
</file>
</compilation>
' NOTE: As in dev11, we do not warn that we are ignoring CLSCompliantAttribute on event accessors.
' NOTE: See warning about non-compliant type UInteger only for E2.
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40041: Type 'UInteger' is not CLS-compliant.
Public Custom Event E2 As Action(Of UInteger)
~~
]]></errors>)
End Sub
<Fact>
Public Sub WRN_EventDelegateTypeNotCLSCompliant2()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Namespace Q
<CLSCompliant(False)>
Public Delegate Sub Bad()
End Namespace
<CLSCompliant(True)>
Public Class C
Public Custom Event E1 As Q.Bad
AddHandler(value As Q.Bad)
End AddHandler
RemoveHandler(value As Q.Bad)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
Public Event E2 As Q.Bad
Public Event E3(x As UInteger)
<CLSCompliant(False)>
Public Custom Event E4 As Q.Bad
AddHandler(value As Q.Bad)
End AddHandler
RemoveHandler(value As Q.Bad)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
<CLSCompliant(False)>
Public Event E5 As Q.Bad
<CLSCompliant(False)>
Public Event E6(x As UInteger)
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40050: Delegate type 'Bad' of event 'E1' is not CLS-compliant.
Public Custom Event E1 As Q.Bad
~~
BC40050: Delegate type 'Bad' of event 'E2' is not CLS-compliant.
Public Event E2 As Q.Bad
~~
BC40028: Type of parameter 'x' is not CLS-compliant.
Public Event E3(x As UInteger)
~
]]></errors>)
End Sub
<Fact>
Public Sub TopLevelMethod_NoAssemblyAttribute()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Public Sub M()
End Sub
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC30001: Statement is not valid in a namespace.
Public Sub M()
~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
Public Sub TopLevelMethod_AttributeTrue()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Sub M()
End Sub
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC30001: Statement is not valid in a namespace.
Public Sub M()
~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
Public Sub TopLevelMethod_AttributeFalse()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Sub M()
End Sub
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC30001: Statement is not valid in a namespace.
Public Sub M()
~~~~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
Public Sub NonCompliantInaccessible()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Private Function M(b As Bad) As Bad
Return b
End Function
Private Property P(b As Bad) As Bad
Get
Return b
End Get
Set(value As Bad)
End Set
End Property
End Class
<CLSCompliant(False)>
Public Class Bad
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub NonCompliantAbstractInNonCompliantType()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
<CLSCompliant(False)>
Public MustInherit Class Bad
Public MustOverride Function M(b As Bad) As Bad
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub SpecialTypes()
Dim sourceTemplate = <![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Public Sub M(p As {0})
End Sub
End Class
]]>.Value.Replace(vbCr, vbCrLf)
Dim helper = CreateCompilationWithMscorlib40({""}, Nothing)
Dim integerType = helper.GetSpecialType(SpecialType.System_Int32)
For Each st As SpecialType In [Enum].GetValues(GetType(SpecialType))
Select Case (st)
Case SpecialType.None, SpecialType.System_Void, SpecialType.System_Runtime_CompilerServices_IsVolatile
Continue For
End Select
Dim type = helper.GetSpecialType(st)
If type.Arity > 0 Then
type = type.Construct(ArrayBuilder(Of TypeSymbol).GetInstance(type.Arity, integerType).ToImmutableAndFree())
End If
Dim qualifiedName = type.ToTestDisplayString()
Dim source = String.Format(sourceTemplate, qualifiedName)
Dim comp = CreateCompilationWithMscorlib40({source}, Nothing)
Select Case (st)
Case SpecialType.System_SByte, SpecialType.System_UInt16, SpecialType.System_UInt32, SpecialType.System_UInt64, SpecialType.System_UIntPtr, SpecialType.System_TypedReference
Assert.Equal(ERRID.WRN_ParamNotCLSCompliant1, DirectCast(comp.GetDeclarationDiagnostics().Single().Code, ERRID))
End Select
Next
End Sub
<WorkItem(697178, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/697178")>
<Fact>
Public Sub ConstructedSpecialTypes()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections.Generic
<Assembly: CLSCompliant(True)>
Public Class C
Public Sub M(p As IEnumerable(Of UInteger))
End Sub
End Class
]]>
</file>
</compilation>
' Native C# misses this diagnostic
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40041: Type 'UInteger' is not CLS-compliant.
Public Sub M(p As IEnumerable(Of UInteger))
~
]]></errors>)
End Sub
<Fact>
Public Sub MissingAttributeType()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
<Missing>
Public Class C
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC30002: Type 'Missing' is not defined.
<Missing>
~~~~~~~
]]></errors>)
End Sub
<WorkItem(709317, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/709317")>
<Fact>
Public Sub Repro709317()
Dim libSource =
<compilation name="Lib">
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
End Class
]]>
</file>
</compilation>
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class D
Public Function M() As C
Return Nothing
End Function
End Class
]]>
</file>
</compilation>
Dim libRef = CreateCompilationWithMscorlib40(libSource).EmitToImageReference()
Dim comp = CreateCompilationWithMscorlib40AndReferences(source, {libRef})
Dim tree = comp.SyntaxTrees.Single()
comp.GetDiagnosticsForSyntaxTree(CompilationStage.Declare, tree)
End Sub
<WorkItem(709317, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/709317")>
<Fact>
Public Sub FilterTree()
Dim sourceTemplate = <![CDATA[
Imports System
Namespace N{0}
<CLSCompliant(False)>
Public Class NonCompliant
End Class
<CLSCompliant(False)>
Public Interface INonCompliant
End Interface
<CLSCompliant(True)>
Public Class Compliant
Inherits NonCompliant
Implements INonCompliant
Public Function M(Of T As NonCompliant)(n As NonCompliant)
Throw New Exception
End Function
Public F As NonCompliant
Public Property P As NonCompliant
End Class
End Namespace
]]>.Value.Replace(vbCr, vbCrLf)
Dim tree1 = VisualBasicSyntaxTree.ParseText(String.Format(sourceTemplate, 1), path:="a.vb")
Dim tree2 = VisualBasicSyntaxTree.ParseText(String.Format(sourceTemplate, 2), path:="b.vb")
Dim comp = CreateCompilationWithMscorlib40({tree1, tree2}, options:=TestOptions.ReleaseDll)
' Two copies of each diagnostic - one from each file.
comp.AssertTheseDiagnostics(<errors><![CDATA[
BC40026: 'Compliant' is not CLS-compliant because it derives from 'NonCompliant', which is not CLS-compliant.
Public Class Compliant
~~~~~~~~~
BC40040: Generic parameter constraint type 'NonCompliant' is not CLS-compliant.
Public Function M(Of T As NonCompliant)(n As NonCompliant)
~
BC40028: Type of parameter 'n' is not CLS-compliant.
Public Function M(Of T As NonCompliant)(n As NonCompliant)
~
BC40025: Type of member 'F' is not CLS-compliant.
Public F As NonCompliant
~
BC40027: Return type of function 'P' is not CLS-compliant.
Public Property P As NonCompliant
~
BC40026: 'Compliant' is not CLS-compliant because it derives from 'NonCompliant', which is not CLS-compliant.
Public Class Compliant
~~~~~~~~~
BC40040: Generic parameter constraint type 'NonCompliant' is not CLS-compliant.
Public Function M(Of T As NonCompliant)(n As NonCompliant)
~
BC40028: Type of parameter 'n' is not CLS-compliant.
Public Function M(Of T As NonCompliant)(n As NonCompliant)
~
BC40025: Type of member 'F' is not CLS-compliant.
Public F As NonCompliant
~
BC40027: Return type of function 'P' is not CLS-compliant.
Public Property P As NonCompliant
~
]]></errors>)
CompilationUtils.AssertTheseDiagnostics(comp.GetDiagnosticsForSyntaxTree(CompilationStage.Declare, tree1, filterSpanWithinTree:=Nothing, includeEarlierStages:=False),
<errors><![CDATA[
BC40026: 'Compliant' is not CLS-compliant because it derives from 'NonCompliant', which is not CLS-compliant.
Public Class Compliant
~~~~~~~~~
BC40040: Generic parameter constraint type 'NonCompliant' is not CLS-compliant.
Public Function M(Of T As NonCompliant)(n As NonCompliant)
~
BC40028: Type of parameter 'n' is not CLS-compliant.
Public Function M(Of T As NonCompliant)(n As NonCompliant)
~
BC40025: Type of member 'F' is not CLS-compliant.
Public F As NonCompliant
~
BC40027: Return type of function 'P' is not CLS-compliant.
Public Property P As NonCompliant
~
]]></errors>)
End Sub
<WorkItem(718503, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/718503")>
<Fact>
Public Sub ErrorTypeAccessibility()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Implements IError
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC30002: Type 'IError' is not defined.
Implements IError
~~~~~~
]]></errors>)
End Sub
' Make sure nothing blows up when a protected symbol has no containing type.
<Fact>
Public Sub ProtectedTopLevelType()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Protected Class C
Public F As UInteger
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC31047: Protected types can only be declared inside of a class.
Protected Class C
~
]]></errors>)
End Sub
<Fact>
Public Sub ProtectedMemberOfSealedType()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public NotInheritable Class C
Protected F As UInteger ' No warning, since not accessible outside assembly.
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub InheritedCompliance1()
Dim libSource =
<compilation name="Lib">
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(False)>
<CLSCompliant(True)>
Public Class Base
End Class
Public Class Derived
Inherits Base
End Class
]]>
</file>
</compilation>
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Public B as Base
Public D as Derived
End Class
]]>
</file>
</compilation>
' NOTE: As in dev11, we ignore the fact that Derived inherits CLSCompliant(True) from Base.
Dim libRef = CreateCompilationWithMscorlib40(libSource).EmitToImageReference()
CreateCompilationWithMscorlib40AndReferences(source, {libRef}).AssertTheseDiagnostics(<errors><![CDATA[
BC40025: Type of member 'D' is not CLS-compliant.
Public D as Derived
~
]]></errors>)
End Sub
<Fact>
Public Sub InheritedCompliance2()
Dim il = <![CDATA[.assembly extern mscorlib
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 )
.ver 4:0:0:0
}
.assembly a
{
.hash algorithm 0x00008004
.ver 0:0:0:0
.custom instance void [mscorlib]System.CLSCompliantAttribute::.ctor(bool) = {bool(true)}
}
.module a.dll
.class public auto ansi beforefieldinit Base
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.CLSCompliantAttribute::.ctor(bool) = {bool(false)}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}
.class public auto ansi beforefieldinit Derived
extends Base
{
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}]]>
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Public B as Base
Public D as Derived
End Class
]]>
</file>
</compilation>
' NOTE: As in dev11, we consider the fact that Derived inherits CLSCompliant(False) from Base
' (since it is not from the current assembly).
Dim libRef = CompileIL(il.Value, prependDefaultHeader:=False)
CreateCompilationWithMscorlib40AndReferences(source, {libRef}).AssertTheseDiagnostics(<errors><![CDATA[
BC40025: Type of member 'B' is not CLS-compliant.
Public B as Base
~
BC40025: Type of member 'D' is not CLS-compliant.
Public D as Derived
~
]]></errors>)
End Sub
<Fact>
Public Sub AllAttributeConstructorsRequireArrays()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class MyAttribute
Inherits Attribute
Public Sub New(a As Integer())
End Sub
End Class
]]>
</file>
</compilation>
' C# would warn.
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub ApplyAttributeWithArrayArgument()
Dim source =
<compilation>
<file name="a.vb">
<>
<Array({1})>
<Params(1)>
Public Class C
End Class
]]>
</file>
</compilation>
' C# would warn.
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub ApplyAttributeWithNonCompliantArgument()
Dim source =
<compilation>
<file name="a.vb">
<>
Public Class C
End Class
]]>
</file>
</compilation>
' C# would warn.
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub Overloading_ArrayRank()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class Compliant
Public Sub M1(x As Integer())
End Sub
Public Sub M1(x As Integer(,)) 'BC40035
End Sub
Public Sub M2(x As Integer(,,))
End Sub
Public Sub M2(x As Integer(,)) 'BC40035
End Sub
Public Sub M3(x As Integer())
End Sub
Private Sub M3(x As Integer(,)) ' Fine, since inaccessible.
End Sub
Public Sub M4(x As Integer())
End Sub
<CLSCompliant(False)>
Private Sub M4(x As Integer(,)) ' Fine, since flagged.
End Sub
End Class
Friend Class Internal
Public Sub M1(x As Integer())
End Sub
Public Sub M1(x As Integer(,)) ' Fine, since inaccessible.
End Sub
End Class
<CLSCompliant(False)>
Public Class NonCompliant
Public Sub M1(x As Integer())
End Sub
Public Sub M1(x As Integer(,)) ' Fine, since tagged.
End Sub
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40035: 'Public Sub M1(x As Integer(*,*))' is not CLS-compliant because it overloads 'Public Sub M1(x As Integer())' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub M1(x As Integer(,)) 'BC40035
~~
BC40035: 'Public Sub M2(x As Integer(*,*))' is not CLS-compliant because it overloads 'Public Sub M2(x As Integer(*,*,*))' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub M2(x As Integer(,)) 'BC40035
~~
]]></errors>)
End Sub
<Fact>
Public Sub Overloading_RefKind()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(False)>
Public Class Compliant
Public Sub M1(x As Integer())
End Sub
Public Sub M1(ByRef x As Integer()) 'BC30345
End Sub
End Class
]]>
</file>
</compilation>
' NOTE: Illegal, even without compliance checking.
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC30345: 'Public Sub M1(x As Integer())' and 'Public Sub M1(ByRef x As Integer())' cannot overload each other because they differ only by parameters declared 'ByRef' or 'ByVal'.
Public Sub M1(x As Integer())
~~
]]></errors>)
End Sub
<Fact>
Public Sub Overloading_ArrayOfArrays()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class Compliant
Public Sub M1(x As Long()())
End Sub
Public Sub M1(x As Char()()) 'BC40035
End Sub
Public Sub M2(x As Integer()()())
End Sub
Public Sub M2(x As Integer()()) 'BC40035
End Sub
Public Sub M3(x As Integer()())
End Sub
Public Sub M3(x As Integer()) 'Fine (C# warns)
End Sub
Public Sub M4(x As Integer(,)(,))
End Sub
Public Sub M4(x As Integer()(,)) 'BC40035
End Sub
Public Sub M5(x As Integer(,)(,))
End Sub
Public Sub M5(x As Integer(,)()) 'BC40035
End Sub
Public Sub M6(x As Long()())
End Sub
Private Sub M6(x As Char()()) ' Fine, since inaccessible.
End Sub
Public Sub M7(x As Long()())
End Sub
<CLSCompliant(False)>
Public Sub M7(x As Char()()) ' Fine, since tagged (dev11 reports BC40035)
End Sub
End Class
Friend Class Internal
Public Sub M1(x As Long()())
End Sub
Public Sub M1(x As Char()()) ' Fine, since inaccessible.
End Sub
End Class
<CLSCompliant(False)>
Public Class NonCompliant
Public Sub M1(x As Long()())
End Sub
Public Sub M1(x As Char()()) ' Fine, since tagged.
End Sub
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40035: 'Public Sub M1(x As Char()())' is not CLS-compliant because it overloads 'Public Sub M1(x As Long()())' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub M1(x As Char()()) 'BC40035
~~
BC40035: 'Public Sub M2(x As Integer()())' is not CLS-compliant because it overloads 'Public Sub M2(x As Integer()()())' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub M2(x As Integer()()) 'BC40035
~~
BC40035: 'Public Sub M4(x As Integer()(*,*))' is not CLS-compliant because it overloads 'Public Sub M4(x As Integer(*,*)(*,*))' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub M4(x As Integer()(,)) 'BC40035
~~
BC40035: 'Public Sub M5(x As Integer(*,*)())' is not CLS-compliant because it overloads 'Public Sub M5(x As Integer(*,*)(*,*))' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub M5(x As Integer(,)()) 'BC40035
~~
]]></errors>)
End Sub
<Fact>
Public Sub Overloading_Properties()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class Compliant
Public Property P1(x As Long()()) As Integer
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
Public Property P1(x As Char()()) As Integer
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
Public Property P2(x As String()) As Integer
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
Public Property P2(x As String(,)) As Integer
Get
Return 0
End Get
Set(value As Integer)
End Set
End Property
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40035: 'Public Property P1(x As Char()()) As Integer' is not CLS-compliant because it overloads 'Public Property P1(x As Long()()) As Integer' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Property P1(x As Char()()) As Integer
~~
BC40035: 'Public Property P2(x As String(*,*)) As Integer' is not CLS-compliant because it overloads 'Public Property P2(x As String()) As Integer' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Property P2(x As String(,)) As Integer
~~
]]></errors>)
End Sub
<Fact>
Public Sub Overloading_MethodKinds()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Public Sub New(p As Long()())
End Sub
Public Sub New(p As Char()())
End Sub
Public Shared Widening Operator CType(p As Long()) As C
Return Nothing
End Operator
Public Shared Widening Operator CType(p As Long(,)) As C ' Not reported by dev11.
Return Nothing
End Operator
Public Shared Narrowing Operator CType(p As String(,,)) As C
Return Nothing
End Operator
Public Shared Narrowing Operator CType(p As String(,)) As C ' Not reported by dev11.
Return Nothing
End Operator
' Static constructors can't be overloaded
' Destructors can't be overloaded.
' Accessors are tested separately.
End Class
]]>
</file>
</compilation>
' BREAK : Dev11 doesn't report BC40035 for operators.
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40035: 'Public Sub New(p As Char()())' is not CLS-compliant because it overloads 'Public Sub New(p As Long()())' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub New(p As Char()())
~~~
BC40035: 'Public Shared Widening Operator CType(p As Long(*,*)) As C' is not CLS-compliant because it overloads 'Public Shared Widening Operator CType(p As Long()) As C' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Shared Widening Operator CType(p As Long(,)) As C ' Not reported by dev11.
~~~~~
BC40035: 'Public Shared Narrowing Operator CType(p As String(*,*)) As C' is not CLS-compliant because it overloads 'Public Shared Narrowing Operator CType(p As String(*,*,*)) As C' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Shared Narrowing Operator CType(p As String(,)) As C ' Not reported by dev11.
~~~~~
]]></errors>)
End Sub
<Fact>
Public Sub Overloading_Operators()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Public Shared Widening Operator CType(p As C) As Integer
Return Nothing
End Operator
Public Shared Widening Operator CType(p As C) As Long
Return Nothing
End Operator
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub Overloading_TypeParameterArray()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C(Of T)
Public Sub M1(t As T())
End Sub
Public Sub M1(t As Integer())
End Sub
Public Sub M2(Of U)(t As U())
End Sub
Public Sub M2(Of U)(t As Integer())
End Sub
End Class
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertNoDiagnostics()
End Sub
<Fact>
Public Sub Overloading_InterfaceMember()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Interface I
Sub M(p As Long()())
End Interface
Public Class ImplementWithSameName
Implements I
Public Sub M(p()() As Long) Implements I.M
End Sub
Public Sub M(p()() As Char) 'BC40035 (twice, in roslyn)
End Sub
End Class
Public Class ImplementWithOtherName
Implements I
Public Sub I_M(p()() As Long) Implements I.M
End Sub
Public Sub M(p()() As String) 'BC40035 (roslyn only)
End Sub
End Class
Public Class Base
Implements I
Public Sub I_M(p()() As Long) Implements I.M
End Sub
End Class
Public Class Derived1
Inherits Base
Implements I
Public Sub M(p()() As Boolean) 'BC40035 (roslyn only)
End Sub
End Class
Public Class Derived2
Inherits Base
Public Sub M(p()() As Short) 'Mimic (C#) dev11 bug - don't report conflict with interface member.
End Sub
End Class
]]>
</file>
</compilation>
' BREAK : Dev11 doesn't report BC40035 for interface members.
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40035: 'Public Sub M(p As Char()())' is not CLS-compliant because it overloads 'Public Sub M(p As Long()())' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub M(p()() As Char) 'BC40035 (twice, in roslyn)
~
BC40035: 'Public Sub M(p As Char()())' is not CLS-compliant because it overloads 'Sub M(p As Long()())' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub M(p()() As Char) 'BC40035 (twice, in roslyn)
~
BC40035: 'Public Sub M(p As String()())' is not CLS-compliant because it overloads 'Sub M(p As Long()())' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub M(p()() As String) 'BC40035 (roslyn only)
~
BC40035: 'Public Sub M(p As Boolean()())' is not CLS-compliant because it overloads 'Sub M(p As Long()())' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Sub M(p()() As Boolean) 'BC40035 (roslyn only)
~
]]></errors>)
End Sub
<Fact>
Public Sub Overloading_BaseMember()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class Base
Public Overridable Sub M(p As Long()())
End Sub
Public Overridable WriteOnly Property P(q As Long()())
Set(value)
End Set
End Property
End Class
Public Class Derived_Overload
Inherits Base
Public Overloads Sub M(p As Char()())
End Sub
Public Overloads WriteOnly Property P(q As Char()())
Set(value)
End Set
End Property
End Class
Public Class Derived_Hide
Inherits Base
Public Shadows Sub M(p As Long()())
End Sub
Public Shadows WriteOnly Property P(q As Long()())
Set(value)
End Set
End Property
End Class
Public Class Derived_Override
Inherits Base
Public Overrides Sub M(p As Long()())
End Sub
Public Overrides WriteOnly Property P(q As Long()())
Set(value)
End Set
End Property
End Class
Public Class Derived1
Inherits Base
End Class
Public Class Derived2
Inherits Derived1
Public Overloads Sub M(p As String()())
End Sub
Public Overloads WriteOnly Property P(q As String()())
Set(value)
End Set
End Property
End Class
]]>
</file>
</compilation>
' BREAK : Dev11 doesn't report BC40035 for base type members.
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40035: 'Public Overloads Sub M(p As Char()())' is not CLS-compliant because it overloads 'Public Overridable Sub M(p As Long()())' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Overloads Sub M(p As Char()())
~
BC40035: 'Public Overloads WriteOnly Property P(q As Char()()) As Object' is not CLS-compliant because it overloads 'Public Overridable WriteOnly Property P(q As Long()()) As Object' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Overloads WriteOnly Property P(q As Char()())
~
BC40035: 'Public Overloads Sub M(p As String()())' is not CLS-compliant because it overloads 'Public Overridable Sub M(p As Long()())' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Overloads Sub M(p As String()())
~
BC40035: 'Public Overloads WriteOnly Property P(q As String()()) As Object' is not CLS-compliant because it overloads 'Public Overridable WriteOnly Property P(q As Long()()) As Object' which differs from it only by array of array parameter types or by the rank of the array parameter types.
Public Overloads WriteOnly Property P(q As String()())
~
]]></errors>)
End Sub
<Fact>
Public Sub WithEventsWarning()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Public WithEvents F As Bad
End Class
<CLSCompliant(False)>
Public Class Bad
End Class
]]>
</file>
</compilation>
' Make sure we don't produce a bunch of spurious warnings for synthesized members.
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40027: Return type of function 'F' is not CLS-compliant.
Public WithEvents F As Bad
~
]]></errors>)
End Sub
<WorkItem(749432, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/749432")>
<Fact>
Public Sub InvalidAttributeArgument()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Public Module VBCoreHelperFunctionality
<CLSCompliant((New With {.anonymousField = False}).anonymousField)>
Public Function Len(ByVal Expression As SByte) As Integer
Return (New With {.anonymousField = 1}).anonymousField
End Function
<CLSCompliant((New With {.anonymousField = False}).anonymousField)>
Public Function Len(ByVal Expression As UInt16) As Integer
Return (New With {.anonymousField = 2}).anonymousField
End Function
End Module
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40AndVBRuntime(source).AssertTheseDiagnostics(<errors><![CDATA[
BC30059: Constant expression is required.
<CLSCompliant((New With {.anonymousField = False}).anonymousField)>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30059: Constant expression is required.
<CLSCompliant((New With {.anonymousField = False}).anonymousField)>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]></errors>)
End Sub
<WorkItem(749352, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/749352")>
<Fact>
Public Sub Repro749352()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Namespace ClsCompClass001f
<CLSCompliant(False)>
Public Class ContainerClass
'COMPILEWARNING: BC40030, "Scen6"
<CLSCompliant(True)>
Public Event Scen6(ByVal x As Integer)
End Class
End Namespace
]]>
</file>
</compilation>
CreateCompilationWithMscorlib40(source).AssertTheseDiagnostics(<errors><![CDATA[
BC40030: event 'Public Event Scen6(x As Integer)' cannot be marked CLS-compliant because its containing type 'ContainerClass' is not CLS-compliant.
Public Event Scen6(ByVal x As Integer)
~~~~~
]]></errors>)
End Sub
<Fact, WorkItem(1026453, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1026453")>
Public Sub Bug1026453()
Dim source1 =
<compilation>
<file name="a.vb">
<![CDATA[
Namespace N1
Public Class A
End Class
End Namespace
]]>
</file>
</compilation>
Dim comp1 = CreateCompilationWithMscorlib40(source1, options:=TestOptions.ReleaseModule)
Dim source2 =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
<Module: CLSCompliant(True)>
Namespace N1
Public Class B
End Class
End Namespace
]]>
</file>
</compilation>
Dim comp2 = CreateCompilationWithMscorlib40AndReferences(source2, {comp1.EmitToImageReference()}, TestOptions.ReleaseDll.WithConcurrentBuild(False))
comp2.AssertNoDiagnostics()
comp2.WithOptions(TestOptions.ReleaseDll.WithConcurrentBuild(True)).AssertNoDiagnostics()
Dim comp3 = comp2.WithOptions(TestOptions.ReleaseModule.WithConcurrentBuild(False))
comp3.AssertNoDiagnostics()
comp3.WithOptions(TestOptions.ReleaseModule.WithConcurrentBuild(True)).AssertNoDiagnostics()
End Sub
<Fact, WorkItem(9719, "https://github.com/dotnet/roslyn/issues/9719")>
Public Sub Bug9719()
' repro was simpler than what's on the github issue - before any fixes, the below snippit triggered the crash
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
<Assembly: CLSCompliant(True)>
Public Class C
Public Sub Problem(item As DummyModule)
End Sub
End Class
Public Module DummyModule
End Module
]]>
</file>
</compilation>
CreateCompilationWithMscorlib45AndVBRuntime(source).AssertTheseDiagnostics(<errors><![CDATA[
BC30371: Module 'DummyModule' cannot be used as a type.
Public Sub Problem(item As DummyModule)
~~~~~~~~~~~
]]></errors>)
End Sub
<Fact>
Public Sub TupleDefersClsComplianceToUnderlyingType()
Dim libCompliant_vb = "
Namespace System
<CLSCompliant(True)>
Public Structure ValueTuple(Of T1, T2)
Public Sub New(item1 As T1, item2 As T2)
End Sub
End Structure
End Namespace
"
Dim libNotCompliant_vb = "
Namespace System
<CLSCompliant(False)>
Public Structure ValueTuple(Of T1, T2)
Public Sub New(item1 As T1, item2 As T2)
End Sub
End Structure
End Namespace
"
Dim source = "
Imports System
<assembly:CLSCompliant(true)>
Public Class C
Public Function Method() As (Integer, Integer)
Throw New Exception()
End Function
Public Function Method2() As (Bad, Bad)
Throw New Exception()
End Function
End Class
<CLSCompliant(false)>
Public Class Bad
End Class
"
Dim libCompliant = CreateCompilationWithMscorlib40({libCompliant_vb}, options:=TestOptions.ReleaseDll).EmitToImageReference()
Dim compCompliant = CreateCompilationWithMscorlib40({source}, {libCompliant}, TestOptions.ReleaseDll)
compCompliant.AssertTheseDiagnostics(
<errors>
BC40041: Type 'Bad' is not CLS-compliant.
Public Function Method2() As (Bad, Bad)
~~~~~~~
BC40041: Type 'Bad' is not CLS-compliant.
Public Function Method2() As (Bad, Bad)
~~~~~~~
</errors>)
Dim libNotCompliant = CreateCompilationWithMscorlib40({libNotCompliant_vb}, options:=TestOptions.ReleaseDll).EmitToImageReference()
Dim compNotCompliant = CreateCompilationWithMscorlib40({source}, {libNotCompliant}, TestOptions.ReleaseDll)
compNotCompliant.AssertTheseDiagnostics(
<errors>
BC40027: Return type of function 'Method' is not CLS-compliant.
Public Function Method() As (Integer, Integer)
~~~~~~
BC40027: Return type of function 'Method2' is not CLS-compliant.
Public Function Method2() As (Bad, Bad)
~~~~~~~
BC40041: Type 'Bad' is not CLS-compliant.
Public Function Method2() As (Bad, Bad)
~~~~~~~
BC40041: Type 'Bad' is not CLS-compliant.
Public Function Method2() As (Bad, Bad)
~~~~~~~
</errors>)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/NamingRule.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.NamingStyles;
namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles
{
internal readonly struct NamingRule
{
public readonly SymbolSpecification SymbolSpecification;
public readonly NamingStyle NamingStyle;
public readonly ReportDiagnostic EnforcementLevel;
public NamingRule(SymbolSpecification symbolSpecification, NamingStyle namingStyle, ReportDiagnostic enforcementLevel)
{
SymbolSpecification = symbolSpecification;
NamingStyle = namingStyle;
EnforcementLevel = enforcementLevel;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.NamingStyles;
namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles
{
internal readonly struct NamingRule
{
public readonly SymbolSpecification SymbolSpecification;
public readonly NamingStyle NamingStyle;
public readonly ReportDiagnostic EnforcementLevel;
public NamingRule(SymbolSpecification symbolSpecification, NamingStyle namingStyle, ReportDiagnostic enforcementLevel)
{
SymbolSpecification = symbolSpecification;
NamingStyle = namingStyle;
EnforcementLevel = enforcementLevel;
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./eng/config/test/Core/InstallTraceListener.cs | // <auto-generated/>
using System.Runtime.CompilerServices;
using Roslyn.Test.Utilities;
internal sealed class InitializeTestModule
{
[ModuleInitializer]
internal static void Initializer()
{
RuntimeHelpers.RunModuleConstructor(typeof(TestBase).Module.ModuleHandle);
}
}
| // <auto-generated/>
using System.Runtime.CompilerServices;
using Roslyn.Test.Utilities;
internal sealed class InitializeTestModule
{
[ModuleInitializer]
internal static void Initializer()
{
RuntimeHelpers.RunModuleConstructor(typeof(TestBase).Module.ModuleHandle);
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IBranchOperation.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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 Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IOperationTests_IBranchOperation : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_01()
{
var source = @"
class C
{
void F()
/*<bind>*/{
label1: ;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,1): warning CS0164: This label has not been referenced
// label1: ;
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label1").WithLocation(6, 1)
);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Exit
Predecessors: [B0]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_02()
{
var source = @"
class C
{
void F(bool a, bool b, bool c)
/*<bind>*/{
label1: if (a) goto label2;
c = true;
label2: if (b) goto label1;
if (c) goto label1;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0] [B3] [B4]
Statements (0)
Jump if False (Regular) to Block[B2]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B3]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'c = true')
Left:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'c')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B1] [B2]
Statements (0)
Jump if False (Regular) to Block[B4]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B1]
Block[B4] - Block
Predecessors: [B3]
Statements (0)
Jump if False (Regular) to Block[B5]
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'c')
Next (Regular) Block[B1]
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_03()
{
var source = @"
class C
{
void F(bool a, bool b, bool c)
/*<bind>*/{
label1: if (a) goto label2;
if (b) goto label2;
c = true;
label2: if (c) goto label1;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0] [B4]
Statements (0)
Jump if False (Regular) to Block[B2]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B4]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'c = true')
Left:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'c')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B1] [B2] [B3]
Statements (0)
Jump if False (Regular) to Block[B5]
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'c')
Next (Regular) Block[B1]
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_04()
{
var source = @"
class C
{
void F(bool a, bool b, bool c)
/*<bind>*/{
label1: if (a) goto label2;
goto label3;
label2: c = true;
label3: if (b) goto label4;
goto label1;
label4: if (c) goto label5;
goto label1;
label5: ;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0] [B3] [B4]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'c = true')
Left:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'c')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B1] [B2]
Statements (0)
Jump if False (Regular) to Block[B1]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (0)
Jump if False (Regular) to Block[B1]
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'c')
Next (Regular) Block[B5]
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_05()
{
var source = @"
class C
{
void F(bool a, bool b, bool c)
/*<bind>*/{
label1: if (a) goto label2;
goto label4;
label2: if (b) goto label3;
goto label4;
label3: c = true;
label4: if (c) goto label5;
goto label1;
label5: ;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0] [B4]
Statements (0)
Jump if False (Regular) to Block[B4]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B4]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'c = true')
Left:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'c')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B1] [B2] [B3]
Statements (0)
Jump if False (Regular) to Block[B1]
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'c')
Next (Regular) Block[B5]
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_06()
{
var source = @"
class C
{
void F()
/*<bind>*/{
goto label1;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,14): error CS0159: No such label 'label1' within the scope of the goto statement
// goto label1;
Diagnostic(ErrorCode.ERR_LabelNotFound, "label1").WithArguments("label1").WithLocation(6, 14)
);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'label1')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto label1;')
Children(0)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_07()
{
var source = @"
class C
{
void F()
/*<bind>*/{
goto label1;
goto label1;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,14): error CS0159: No such label 'label1' within the scope of the goto statement
// goto label1;
Diagnostic(ErrorCode.ERR_LabelNotFound, "label1").WithArguments("label1").WithLocation(6, 14),
// (7,14): error CS0159: No such label 'label1' within the scope of the goto statement
// goto label1;
Diagnostic(ErrorCode.ERR_LabelNotFound, "label1").WithArguments("label1").WithLocation(7, 14)
);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (4)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'label1')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto label1;')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'label1')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto label1;')
Children(0)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_08()
{
var source = @"
class C
{
void F(bool a)
/*<bind>*/{
if (a) goto label2;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,21): error CS0159: No such label 'label2' within the scope of the goto statement
// if (a) goto label2;
Diagnostic(ErrorCode.ERR_LabelNotFound, "label2").WithArguments("label2").WithLocation(6, 21)
);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (2)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'label2')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto label2;')
Children(0)
Next (Regular) Block[B3]
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_09()
{
var source = @"
class C
{
void F(bool a, bool b)
/*<bind>*/{
if (a) goto label2;
if (b) goto label2;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,21): error CS0159: No such label 'label2' within the scope of the goto statement
// if (a) goto label2;
Diagnostic(ErrorCode.ERR_LabelNotFound, "label2").WithArguments("label2").WithLocation(6, 21),
// (7,21): error CS0159: No such label 'label2' within the scope of the goto statement
// if (b) goto label2;
Diagnostic(ErrorCode.ERR_LabelNotFound, "label2").WithArguments("label2").WithLocation(7, 21)
);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (2)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'label2')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto label2;')
Children(0)
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B1] [B2]
Statements (0)
Jump if False (Regular) to Block[B5]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (2)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'label2')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto label2;')
Children(0)
Next (Regular) Block[B5]
Block[B5] - Exit
Predecessors: [B3] [B4]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_10()
{
var source = @"
class C
{
void F(bool a)
/*<bind>*/{
if (a) goto label2;
goto label1;
label2: ;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (7,14): error CS0159: No such label 'label1' within the scope of the goto statement
// goto label1;
Diagnostic(ErrorCode.ERR_LabelNotFound, "label1").WithArguments("label1").WithLocation(7, 14)
);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B2]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B3]
Block[B2] - Block
Predecessors: [B1]
Statements (2)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'label1')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto label1;')
Children(0)
Next (Regular) Block[B3]
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_11()
{
var source = @"
class C
{
void F(bool a, bool b)
/*<bind>*/{
if (a) goto label2;
goto label1;
label2: if (b) goto label3;
goto label1;
label3: ;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (7,14): error CS0159: No such label 'label1' within the scope of the goto statement
// goto label1;
Diagnostic(ErrorCode.ERR_LabelNotFound, "label1").WithArguments("label1").WithLocation(7, 14),
// (9,14): error CS0159: No such label 'label1' within the scope of the goto statement
// goto label1;
Diagnostic(ErrorCode.ERR_LabelNotFound, "label1").WithArguments("label1").WithLocation(9, 14)
);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B2]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B3]
Block[B2] - Block
Predecessors: [B1]
Statements (2)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'label1')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto label1;')
Children(0)
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B1] [B2]
Statements (0)
Jump if False (Regular) to Block[B4]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B5]
Block[B4] - Block
Predecessors: [B3]
Statements (2)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'label1')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto label1;')
Children(0)
Next (Regular) Block[B5]
Block[B5] - Exit
Predecessors: [B3] [B4]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_12()
{
var source = @"
class C
{
void F(bool a, bool b)
/*<bind>*/{
while (a)
{
if (b) break;
a = false;
}
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'a = false')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B1]
Block[B4] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_15()
{
var source = @"
class C
{
void F()
/*<bind>*/{
break;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,9): error CS0139: No enclosing loop out of which to break or continue
// break;
Diagnostic(ErrorCode.ERR_NoBreakOrCont, "break;").WithLocation(6, 9)
);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'break;')
Children(0)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_16()
{
string source = @"
class P
{
void M(bool x, bool y)
/*<bind>*/{
while (filter(out var j))
{
if (x) continue;
y = false;
}
}/*</bind>*/
bool filter(out int i) => throw null;
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0] [B3] [B4]
Statements (0)
Next (Regular) Block[B2]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 j]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B5]
IInvocationOperation ( System.Boolean P.filter(out System.Int32 i)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'filter(out var j)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'filter')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'out var j')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var j')
ILocalReferenceOperation: j (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B4]
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'x')
Next (Regular) Block[B1]
Leaving: {R1}
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'y = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'y = false')
Left:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B1]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_17()
{
string source = @"
class P
{
void M(bool x, bool y)
/*<bind>*/{
do
{
if (x) continue;
y = false;
}
while (filter(out var j));
}/*</bind>*/
bool filter(out int i) => throw null;
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0] [B4]
Statements (0)
Next (Regular) Block[B2]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 j]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'x')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'y = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'y = false')
Left:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (0)
Jump if True (Regular) to Block[B1]
IInvocationOperation ( System.Boolean P.filter(out System.Int32 i)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'filter(out var j)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'filter')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'out var j')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var j')
ILocalReferenceOperation: j (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R1}
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_19()
{
string source = @"
class P
{
void M()
/*<bind>*/{
continue;
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'continue;')
Children(0)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = new[] {
// file.cs(6,9): error CS0139: No enclosing loop out of which to break or continue
// continue;
Diagnostic(ErrorCode.ERR_NoBreakOrCont, "continue;").WithLocation(6, 9)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_25()
{
string source = @"
class P
{
void M(bool x)
/*<bind>*/{
goto finallyLabel;
goto catchlabel;
goto trylabel;
try
{
trylabel:
goto finallyLabel;
goto catchlabel;
goto outsideLabel;
}
catch
{
catchlabel:
goto finallyLabel;
goto trylabel;
goto outsideLabel;
}
finally
{
finallyLabel:
goto catchlabel;
goto trylabel;
goto outsideLabel;
}
x = true;
outsideLabel:;
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (6)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'finallyLabel')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto finallyLabel;')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'catchlabel')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto catchlabel;')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'trylabel')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto trylabel;')
Children(0)
Next (Regular) Block[B2]
Entering: {R1} {R2} {R3} {R4}
.try {R1, R2}
{
.try {R3, R4}
{
Block[B2] - Block
Predecessors: [B1]
Statements (4)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'finallyLabel')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto finallyLabel;')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'catchlabel')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto catchlabel;')
Children(0)
Next (Regular) Block[B6]
Finalizing: {R6}
Leaving: {R4} {R3} {R2} {R1}
}
.catch {R5} (System.Object)
{
Block[B3] - Block
Predecessors (0)
Statements (4)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'finallyLabel')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto finallyLabel;')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'trylabel')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto trylabel;')
Children(0)
Next (Regular) Block[B6]
Finalizing: {R6}
Leaving: {R5} {R3} {R2} {R1}
}
}
.finally {R6}
{
Block[B4] - Block
Predecessors (0)
Statements (4)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'catchlabel')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto catchlabel;')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'trylabel')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto trylabel;')
Children(0)
Next (Regular) Block[B6]
Leaving: {R6} {R1}
}
Block[B5] - Block [UnReachable]
Predecessors (0)
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'x = true')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B6]
Block[B6] - Exit
Predecessors: [B2] [B3] [B4] [B5]
Statements (0)
";
var expectedDiagnostics = new[] {
// file.cs(6,14): error CS0159: No such label 'finallyLabel' within the scope of the goto statement
// goto finallyLabel;
Diagnostic(ErrorCode.ERR_LabelNotFound, "finallyLabel").WithArguments("finallyLabel").WithLocation(6, 14),
// file.cs(7,14): error CS0159: No such label 'catchlabel' within the scope of the goto statement
// goto catchlabel;
Diagnostic(ErrorCode.ERR_LabelNotFound, "catchlabel").WithArguments("catchlabel").WithLocation(7, 14),
// file.cs(8,14): error CS0159: No such label 'trylabel' within the scope of the goto statement
// goto trylabel;
Diagnostic(ErrorCode.ERR_LabelNotFound, "trylabel").WithArguments("trylabel").WithLocation(8, 14),
// file.cs(13,18): error CS0159: No such label 'finallyLabel' within the scope of the goto statement
// goto finallyLabel;
Diagnostic(ErrorCode.ERR_LabelNotFound, "finallyLabel").WithArguments("finallyLabel").WithLocation(13, 18),
// file.cs(14,18): error CS0159: No such label 'catchlabel' within the scope of the goto statement
// goto catchlabel;
Diagnostic(ErrorCode.ERR_LabelNotFound, "catchlabel").WithArguments("catchlabel").WithLocation(14, 18),
// file.cs(20,18): error CS0159: No such label 'finallyLabel' within the scope of the goto statement
// goto finallyLabel;
Diagnostic(ErrorCode.ERR_LabelNotFound, "finallyLabel").WithArguments("finallyLabel").WithLocation(20, 18),
// file.cs(21,18): error CS0159: No such label 'trylabel' within the scope of the goto statement
// goto trylabel;
Diagnostic(ErrorCode.ERR_LabelNotFound, "trylabel").WithArguments("trylabel").WithLocation(21, 18),
// file.cs(27,18): error CS0159: No such label 'catchlabel' within the scope of the goto statement
// goto catchlabel;
Diagnostic(ErrorCode.ERR_LabelNotFound, "catchlabel").WithArguments("catchlabel").WithLocation(27, 18),
// file.cs(28,18): error CS0159: No such label 'trylabel' within the scope of the goto statement
// goto trylabel;
Diagnostic(ErrorCode.ERR_LabelNotFound, "trylabel").WithArguments("trylabel").WithLocation(28, 18),
// file.cs(29,13): error CS0157: Control cannot leave the body of a finally clause
// goto outsideLabel;
Diagnostic(ErrorCode.ERR_BadFinallyLeave, "goto").WithLocation(29, 13),
// file.cs(32,9): warning CS0162: Unreachable code detected
// x = true;
Diagnostic(ErrorCode.WRN_UnreachableCode, "x").WithLocation(32, 9),
// file.cs(12,1): warning CS0164: This label has not been referenced
// trylabel:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "trylabel").WithLocation(12, 1),
// file.cs(19,1): warning CS0164: This label has not been referenced
// catchlabel:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "catchlabel").WithLocation(19, 1),
// file.cs(26,1): warning CS0164: This label has not been referenced
// finallyLabel:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "finallyLabel").WithLocation(26, 1)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_49()
{
var source = @"
class C
{
void F(bool a)
/*<bind>*/{
if (a) goto label1;
goto label1;
label1: return;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B2]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1*2]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_50()
{
var source = @"
class C
{
void F(bool a, bool b)
/*<bind>*/{
goto label2;
label1:
if (a) goto label3;
goto label3;
label2:
if (b) goto label1;
goto label1;
label3: ;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B2]
Block[B1] - Block
Predecessors: [B2*2]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B3]
Block[B2] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B1]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B1]
Block[B3] - Exit
Predecessors: [B1*2]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_51()
{
var source = @"
class C
{
void F(bool a, bool b)
/*<bind>*/{
goto label1;
label1:
a = true;
goto label3;
label1:
b = false;
label3: ;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (10,1): error CS0140: The label 'label1' is a duplicate
// label1:
Diagnostic(ErrorCode.ERR_DuplicateLabel, "label1").WithArguments("label1").WithLocation(10, 1)
);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'a = true')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B3]
Block[B2] - Block [UnReachable]
Predecessors (0)
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = false')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_52()
{
var source = @"
class C
{
void F(bool a, bool b)
/*<bind>*/{
label1:
a = true;
goto label3;
label1:
b = false;
goto label1;
label3: ;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (9,1): error CS0140: The label 'label1' is a duplicate
// label1:
Diagnostic(ErrorCode.ERR_DuplicateLabel, "label1").WithArguments("label1").WithLocation(9, 1)
);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0] [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'a = true')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B3]
Block[B2] - Block [UnReachable]
Predecessors (0)
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = false')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B1]
Block[B3] - Exit
Predecessors: [B1]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_54()
{
string source = @"
#pragma warning disable CS8321
struct C
{
void M()
/*<bind>*/{
void local()
{
goto label;
}
label: ;
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Methods: [void local()]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Next (Regular) Block[B2]
Leaving: {R1}
{ void local()
Block[B0#0R1] - Entry
Statements (0)
Next (Regular) Block[B1#0R1]
Block[B1#0R1] - Block
Predecessors: [B0#0R1]
Statements (0)
Next (Error) Block[null]
Block[B2#0R1] - Exit [UnReachable]
Predecessors (0)
Statements (0)
}
}
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = new[] {
// file.cs(9,13): error CS0159: No such label 'label' within the scope of the goto statement
// goto label;
Diagnostic(ErrorCode.ERR_LabelNotFound, "goto").WithArguments("label").WithLocation(9, 13),
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_55()
{
string source = @"
#pragma warning disable CS8321
struct C
{
void M()
/*<bind>*/{
void local(bool input)
{
if (input) return;
goto label;
}
label: ;
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Methods: [void local(System.Boolean input)]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Next (Regular) Block[B2]
Leaving: {R1}
{ void local(System.Boolean input)
Block[B0#0R1] - Entry
Statements (0)
Next (Regular) Block[B1#0R1]
Block[B1#0R1] - Block
Predecessors: [B0#0R1]
Statements (0)
Jump if False (Error) to Block[null]
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input')
Next (Regular) Block[B2#0R1]
Block[B2#0R1] - Exit
Predecessors: [B1#0R1]
Statements (0)
}
}
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = new[] {
// file.cs(11,13): error CS0159: No such label 'label' within the scope of the goto statement
// goto label;
Diagnostic(ErrorCode.ERR_LabelNotFound, "goto").WithArguments("label").WithLocation(11, 13),
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_56()
{
string source = @"
struct C
{
void M(System.Action<bool> d)
/*<bind>*/{
d = (bool input) =>
{
if (input) return;
goto label;
};
label: ;
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'd = (bool i ... };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action<System.Boolean>, IsInvalid) (Syntax: 'd = (bool i ... }')
Left:
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.Action<System.Boolean>) (Syntax: 'd')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Boolean>, IsInvalid, IsImplicit) (Syntax: '(bool input ... }')
Target:
IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null, IsInvalid) (Syntax: '(bool input ... }')
{
Block[B0#A0] - Entry
Statements (0)
Next (Regular) Block[B1#A0]
Block[B1#A0] - Block
Predecessors: [B0#A0]
Statements (0)
Jump if False (Error) to Block[null]
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input')
Next (Regular) Block[B2#A0]
Block[B2#A0] - Exit
Predecessors: [B1#A0]
Statements (0)
}
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = new[] {
// file.cs(10,13): error CS0159: No such label 'label' within the scope of the goto statement
// goto label;
Diagnostic(ErrorCode.ERR_LabelNotFound, "goto").WithArguments("label").WithLocation(10, 13),
// file.cs(13,1): warning CS0164: This label has not been referenced
// label: ;
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label").WithLocation(13, 1)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IOperationTests_IBranchOperation : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_01()
{
var source = @"
class C
{
void F()
/*<bind>*/{
label1: ;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,1): warning CS0164: This label has not been referenced
// label1: ;
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label1").WithLocation(6, 1)
);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Exit
Predecessors: [B0]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_02()
{
var source = @"
class C
{
void F(bool a, bool b, bool c)
/*<bind>*/{
label1: if (a) goto label2;
c = true;
label2: if (b) goto label1;
if (c) goto label1;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0] [B3] [B4]
Statements (0)
Jump if False (Regular) to Block[B2]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B3]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'c = true')
Left:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'c')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B1] [B2]
Statements (0)
Jump if False (Regular) to Block[B4]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B1]
Block[B4] - Block
Predecessors: [B3]
Statements (0)
Jump if False (Regular) to Block[B5]
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'c')
Next (Regular) Block[B1]
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_03()
{
var source = @"
class C
{
void F(bool a, bool b, bool c)
/*<bind>*/{
label1: if (a) goto label2;
if (b) goto label2;
c = true;
label2: if (c) goto label1;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0] [B4]
Statements (0)
Jump if False (Regular) to Block[B2]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B4]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'c = true')
Left:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'c')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B1] [B2] [B3]
Statements (0)
Jump if False (Regular) to Block[B5]
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'c')
Next (Regular) Block[B1]
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_04()
{
var source = @"
class C
{
void F(bool a, bool b, bool c)
/*<bind>*/{
label1: if (a) goto label2;
goto label3;
label2: c = true;
label3: if (b) goto label4;
goto label1;
label4: if (c) goto label5;
goto label1;
label5: ;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0] [B3] [B4]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'c = true')
Left:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'c')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B1] [B2]
Statements (0)
Jump if False (Regular) to Block[B1]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (0)
Jump if False (Regular) to Block[B1]
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'c')
Next (Regular) Block[B5]
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_05()
{
var source = @"
class C
{
void F(bool a, bool b, bool c)
/*<bind>*/{
label1: if (a) goto label2;
goto label4;
label2: if (b) goto label3;
goto label4;
label3: c = true;
label4: if (c) goto label5;
goto label1;
label5: ;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0] [B4]
Statements (0)
Jump if False (Regular) to Block[B4]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B4]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'c = true')
Left:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'c')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B1] [B2] [B3]
Statements (0)
Jump if False (Regular) to Block[B1]
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'c')
Next (Regular) Block[B5]
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_06()
{
var source = @"
class C
{
void F()
/*<bind>*/{
goto label1;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,14): error CS0159: No such label 'label1' within the scope of the goto statement
// goto label1;
Diagnostic(ErrorCode.ERR_LabelNotFound, "label1").WithArguments("label1").WithLocation(6, 14)
);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'label1')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto label1;')
Children(0)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_07()
{
var source = @"
class C
{
void F()
/*<bind>*/{
goto label1;
goto label1;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,14): error CS0159: No such label 'label1' within the scope of the goto statement
// goto label1;
Diagnostic(ErrorCode.ERR_LabelNotFound, "label1").WithArguments("label1").WithLocation(6, 14),
// (7,14): error CS0159: No such label 'label1' within the scope of the goto statement
// goto label1;
Diagnostic(ErrorCode.ERR_LabelNotFound, "label1").WithArguments("label1").WithLocation(7, 14)
);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (4)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'label1')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto label1;')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'label1')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto label1;')
Children(0)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_08()
{
var source = @"
class C
{
void F(bool a)
/*<bind>*/{
if (a) goto label2;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,21): error CS0159: No such label 'label2' within the scope of the goto statement
// if (a) goto label2;
Diagnostic(ErrorCode.ERR_LabelNotFound, "label2").WithArguments("label2").WithLocation(6, 21)
);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (2)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'label2')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto label2;')
Children(0)
Next (Regular) Block[B3]
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_09()
{
var source = @"
class C
{
void F(bool a, bool b)
/*<bind>*/{
if (a) goto label2;
if (b) goto label2;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,21): error CS0159: No such label 'label2' within the scope of the goto statement
// if (a) goto label2;
Diagnostic(ErrorCode.ERR_LabelNotFound, "label2").WithArguments("label2").WithLocation(6, 21),
// (7,21): error CS0159: No such label 'label2' within the scope of the goto statement
// if (b) goto label2;
Diagnostic(ErrorCode.ERR_LabelNotFound, "label2").WithArguments("label2").WithLocation(7, 21)
);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (2)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'label2')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto label2;')
Children(0)
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B1] [B2]
Statements (0)
Jump if False (Regular) to Block[B5]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (2)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'label2')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto label2;')
Children(0)
Next (Regular) Block[B5]
Block[B5] - Exit
Predecessors: [B3] [B4]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_10()
{
var source = @"
class C
{
void F(bool a)
/*<bind>*/{
if (a) goto label2;
goto label1;
label2: ;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (7,14): error CS0159: No such label 'label1' within the scope of the goto statement
// goto label1;
Diagnostic(ErrorCode.ERR_LabelNotFound, "label1").WithArguments("label1").WithLocation(7, 14)
);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B2]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B3]
Block[B2] - Block
Predecessors: [B1]
Statements (2)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'label1')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto label1;')
Children(0)
Next (Regular) Block[B3]
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_11()
{
var source = @"
class C
{
void F(bool a, bool b)
/*<bind>*/{
if (a) goto label2;
goto label1;
label2: if (b) goto label3;
goto label1;
label3: ;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (7,14): error CS0159: No such label 'label1' within the scope of the goto statement
// goto label1;
Diagnostic(ErrorCode.ERR_LabelNotFound, "label1").WithArguments("label1").WithLocation(7, 14),
// (9,14): error CS0159: No such label 'label1' within the scope of the goto statement
// goto label1;
Diagnostic(ErrorCode.ERR_LabelNotFound, "label1").WithArguments("label1").WithLocation(9, 14)
);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B2]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B3]
Block[B2] - Block
Predecessors: [B1]
Statements (2)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'label1')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto label1;')
Children(0)
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B1] [B2]
Statements (0)
Jump if False (Regular) to Block[B4]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B5]
Block[B4] - Block
Predecessors: [B3]
Statements (2)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'label1')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto label1;')
Children(0)
Next (Regular) Block[B5]
Block[B5] - Exit
Predecessors: [B3] [B4]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_12()
{
var source = @"
class C
{
void F(bool a, bool b)
/*<bind>*/{
while (a)
{
if (b) break;
a = false;
}
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'a = false')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B1]
Block[B4] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_15()
{
var source = @"
class C
{
void F()
/*<bind>*/{
break;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,9): error CS0139: No enclosing loop out of which to break or continue
// break;
Diagnostic(ErrorCode.ERR_NoBreakOrCont, "break;").WithLocation(6, 9)
);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'break;')
Children(0)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_16()
{
string source = @"
class P
{
void M(bool x, bool y)
/*<bind>*/{
while (filter(out var j))
{
if (x) continue;
y = false;
}
}/*</bind>*/
bool filter(out int i) => throw null;
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0] [B3] [B4]
Statements (0)
Next (Regular) Block[B2]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 j]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B5]
IInvocationOperation ( System.Boolean P.filter(out System.Int32 i)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'filter(out var j)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'filter')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'out var j')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var j')
ILocalReferenceOperation: j (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B4]
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'x')
Next (Regular) Block[B1]
Leaving: {R1}
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'y = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'y = false')
Left:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B1]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B2]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_17()
{
string source = @"
class P
{
void M(bool x, bool y)
/*<bind>*/{
do
{
if (x) continue;
y = false;
}
while (filter(out var j));
}/*</bind>*/
bool filter(out int i) => throw null;
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0] [B4]
Statements (0)
Next (Regular) Block[B2]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 j]
Block[B2] - Block
Predecessors: [B1]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'x')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'y = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'y = false')
Left:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (0)
Jump if True (Regular) to Block[B1]
IInvocationOperation ( System.Boolean P.filter(out System.Int32 i)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'filter(out var j)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'filter')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'out var j')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var j')
ILocalReferenceOperation: j (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R1}
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_19()
{
string source = @"
class P
{
void M()
/*<bind>*/{
continue;
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'continue;')
Children(0)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = new[] {
// file.cs(6,9): error CS0139: No enclosing loop out of which to break or continue
// continue;
Diagnostic(ErrorCode.ERR_NoBreakOrCont, "continue;").WithLocation(6, 9)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_25()
{
string source = @"
class P
{
void M(bool x)
/*<bind>*/{
goto finallyLabel;
goto catchlabel;
goto trylabel;
try
{
trylabel:
goto finallyLabel;
goto catchlabel;
goto outsideLabel;
}
catch
{
catchlabel:
goto finallyLabel;
goto trylabel;
goto outsideLabel;
}
finally
{
finallyLabel:
goto catchlabel;
goto trylabel;
goto outsideLabel;
}
x = true;
outsideLabel:;
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (6)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'finallyLabel')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto finallyLabel;')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'catchlabel')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto catchlabel;')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'trylabel')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto trylabel;')
Children(0)
Next (Regular) Block[B2]
Entering: {R1} {R2} {R3} {R4}
.try {R1, R2}
{
.try {R3, R4}
{
Block[B2] - Block
Predecessors: [B1]
Statements (4)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'finallyLabel')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto finallyLabel;')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'catchlabel')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto catchlabel;')
Children(0)
Next (Regular) Block[B6]
Finalizing: {R6}
Leaving: {R4} {R3} {R2} {R1}
}
.catch {R5} (System.Object)
{
Block[B3] - Block
Predecessors (0)
Statements (4)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'finallyLabel')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto finallyLabel;')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'trylabel')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto trylabel;')
Children(0)
Next (Regular) Block[B6]
Finalizing: {R6}
Leaving: {R5} {R3} {R2} {R1}
}
}
.finally {R6}
{
Block[B4] - Block
Predecessors (0)
Statements (4)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'catchlabel')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto catchlabel;')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'trylabel')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto trylabel;')
Children(0)
Next (Regular) Block[B6]
Leaving: {R6} {R1}
}
Block[B5] - Block [UnReachable]
Predecessors (0)
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'x = true')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B6]
Block[B6] - Exit
Predecessors: [B2] [B3] [B4] [B5]
Statements (0)
";
var expectedDiagnostics = new[] {
// file.cs(6,14): error CS0159: No such label 'finallyLabel' within the scope of the goto statement
// goto finallyLabel;
Diagnostic(ErrorCode.ERR_LabelNotFound, "finallyLabel").WithArguments("finallyLabel").WithLocation(6, 14),
// file.cs(7,14): error CS0159: No such label 'catchlabel' within the scope of the goto statement
// goto catchlabel;
Diagnostic(ErrorCode.ERR_LabelNotFound, "catchlabel").WithArguments("catchlabel").WithLocation(7, 14),
// file.cs(8,14): error CS0159: No such label 'trylabel' within the scope of the goto statement
// goto trylabel;
Diagnostic(ErrorCode.ERR_LabelNotFound, "trylabel").WithArguments("trylabel").WithLocation(8, 14),
// file.cs(13,18): error CS0159: No such label 'finallyLabel' within the scope of the goto statement
// goto finallyLabel;
Diagnostic(ErrorCode.ERR_LabelNotFound, "finallyLabel").WithArguments("finallyLabel").WithLocation(13, 18),
// file.cs(14,18): error CS0159: No such label 'catchlabel' within the scope of the goto statement
// goto catchlabel;
Diagnostic(ErrorCode.ERR_LabelNotFound, "catchlabel").WithArguments("catchlabel").WithLocation(14, 18),
// file.cs(20,18): error CS0159: No such label 'finallyLabel' within the scope of the goto statement
// goto finallyLabel;
Diagnostic(ErrorCode.ERR_LabelNotFound, "finallyLabel").WithArguments("finallyLabel").WithLocation(20, 18),
// file.cs(21,18): error CS0159: No such label 'trylabel' within the scope of the goto statement
// goto trylabel;
Diagnostic(ErrorCode.ERR_LabelNotFound, "trylabel").WithArguments("trylabel").WithLocation(21, 18),
// file.cs(27,18): error CS0159: No such label 'catchlabel' within the scope of the goto statement
// goto catchlabel;
Diagnostic(ErrorCode.ERR_LabelNotFound, "catchlabel").WithArguments("catchlabel").WithLocation(27, 18),
// file.cs(28,18): error CS0159: No such label 'trylabel' within the scope of the goto statement
// goto trylabel;
Diagnostic(ErrorCode.ERR_LabelNotFound, "trylabel").WithArguments("trylabel").WithLocation(28, 18),
// file.cs(29,13): error CS0157: Control cannot leave the body of a finally clause
// goto outsideLabel;
Diagnostic(ErrorCode.ERR_BadFinallyLeave, "goto").WithLocation(29, 13),
// file.cs(32,9): warning CS0162: Unreachable code detected
// x = true;
Diagnostic(ErrorCode.WRN_UnreachableCode, "x").WithLocation(32, 9),
// file.cs(12,1): warning CS0164: This label has not been referenced
// trylabel:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "trylabel").WithLocation(12, 1),
// file.cs(19,1): warning CS0164: This label has not been referenced
// catchlabel:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "catchlabel").WithLocation(19, 1),
// file.cs(26,1): warning CS0164: This label has not been referenced
// finallyLabel:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "finallyLabel").WithLocation(26, 1)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_49()
{
var source = @"
class C
{
void F(bool a)
/*<bind>*/{
if (a) goto label1;
goto label1;
label1: return;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B2]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1*2]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_50()
{
var source = @"
class C
{
void F(bool a, bool b)
/*<bind>*/{
goto label2;
label1:
if (a) goto label3;
goto label3;
label2:
if (b) goto label1;
goto label1;
label3: ;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B2]
Block[B1] - Block
Predecessors: [B2*2]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B3]
Block[B2] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B1]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B1]
Block[B3] - Exit
Predecessors: [B1*2]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_51()
{
var source = @"
class C
{
void F(bool a, bool b)
/*<bind>*/{
goto label1;
label1:
a = true;
goto label3;
label1:
b = false;
label3: ;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (10,1): error CS0140: The label 'label1' is a duplicate
// label1:
Diagnostic(ErrorCode.ERR_DuplicateLabel, "label1").WithArguments("label1").WithLocation(10, 1)
);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'a = true')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B3]
Block[B2] - Block [UnReachable]
Predecessors (0)
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = false')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B3]
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_52()
{
var source = @"
class C
{
void F(bool a, bool b)
/*<bind>*/{
label1:
a = true;
goto label3;
label1:
b = false;
goto label1;
label3: ;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (9,1): error CS0140: The label 'label1' is a duplicate
// label1:
Diagnostic(ErrorCode.ERR_DuplicateLabel, "label1").WithArguments("label1").WithLocation(9, 1)
);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0] [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a = true;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'a = true')
Left:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B3]
Block[B2] - Block [UnReachable]
Predecessors (0)
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = false;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = false')
Left:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false')
Next (Regular) Block[B1]
Block[B3] - Exit
Predecessors: [B1]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_54()
{
string source = @"
#pragma warning disable CS8321
struct C
{
void M()
/*<bind>*/{
void local()
{
goto label;
}
label: ;
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Methods: [void local()]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Next (Regular) Block[B2]
Leaving: {R1}
{ void local()
Block[B0#0R1] - Entry
Statements (0)
Next (Regular) Block[B1#0R1]
Block[B1#0R1] - Block
Predecessors: [B0#0R1]
Statements (0)
Next (Error) Block[null]
Block[B2#0R1] - Exit [UnReachable]
Predecessors (0)
Statements (0)
}
}
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = new[] {
// file.cs(9,13): error CS0159: No such label 'label' within the scope of the goto statement
// goto label;
Diagnostic(ErrorCode.ERR_LabelNotFound, "goto").WithArguments("label").WithLocation(9, 13),
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_55()
{
string source = @"
#pragma warning disable CS8321
struct C
{
void M()
/*<bind>*/{
void local(bool input)
{
if (input) return;
goto label;
}
label: ;
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Methods: [void local(System.Boolean input)]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Next (Regular) Block[B2]
Leaving: {R1}
{ void local(System.Boolean input)
Block[B0#0R1] - Entry
Statements (0)
Next (Regular) Block[B1#0R1]
Block[B1#0R1] - Block
Predecessors: [B0#0R1]
Statements (0)
Jump if False (Error) to Block[null]
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input')
Next (Regular) Block[B2#0R1]
Block[B2#0R1] - Exit
Predecessors: [B1#0R1]
Statements (0)
}
}
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = new[] {
// file.cs(11,13): error CS0159: No such label 'label' within the scope of the goto statement
// goto label;
Diagnostic(ErrorCode.ERR_LabelNotFound, "goto").WithArguments("label").WithLocation(11, 13),
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void BranchFlow_56()
{
string source = @"
struct C
{
void M(System.Action<bool> d)
/*<bind>*/{
d = (bool input) =>
{
if (input) return;
goto label;
};
label: ;
}/*</bind>*/
}
";
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'd = (bool i ... };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action<System.Boolean>, IsInvalid) (Syntax: 'd = (bool i ... }')
Left:
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.Action<System.Boolean>) (Syntax: 'd')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.Boolean>, IsInvalid, IsImplicit) (Syntax: '(bool input ... }')
Target:
IFlowAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.FlowAnonymousFunction, Type: null, IsInvalid) (Syntax: '(bool input ... }')
{
Block[B0#A0] - Entry
Statements (0)
Next (Regular) Block[B1#A0]
Block[B1#A0] - Block
Predecessors: [B0#A0]
Statements (0)
Jump if False (Error) to Block[null]
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input')
Next (Regular) Block[B2#A0]
Block[B2#A0] - Exit
Predecessors: [B1#A0]
Statements (0)
}
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
var expectedDiagnostics = new[] {
// file.cs(10,13): error CS0159: No such label 'label' within the scope of the goto statement
// goto label;
Diagnostic(ErrorCode.ERR_LabelNotFound, "goto").WithArguments("label").WithLocation(10, 13),
// file.cs(13,1): warning CS0164: This label has not been referenced
// label: ;
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label").WithLocation(13, 1)
};
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Test/CodeModel/VisualBasic/OptionsStatementTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.VisualBasic
Public Class OptionsStatementTests
Inherits AbstractCodeElementTests
#Region "GetStartPoint() tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetStartPoint1()
Dim code =
<Code>
Option $$Strict On
Class C
End Class
</Code>
TestGetStartPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartName,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=16)))
End Sub
#End Region
#Region "GetEndPoint() tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetEndPoint1()
Dim code =
<Code>
Option $$Strict On
Class C
End Class
</Code>
TestGetEndPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=1, lineOffset:=17, absoluteOffset:=17, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=1, lineOffset:=17, absoluteOffset:=17, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=1, lineOffset:=17, absoluteOffset:=17, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=1, lineOffset:=17, absoluteOffset:=17, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartName,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=1, lineOffset:=17, absoluteOffset:=17, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=1, lineOffset:=17, absoluteOffset:=17, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=1, lineOffset:=17, absoluteOffset:=17, lineLength:=16)))
End Sub
#End Region
#Region "Kind tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestKind1()
Dim code =
<Code>
$$Option Strict On
</Code>
TestKind(code, EnvDTE.vsCMElement.vsCMElementOptionStmt)
End Sub
#End Region
#Region "Name tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestName1()
Dim code =
<Code>
$$Option Strict On
</Code>
TestName(code, "Option Strict On")
End Sub
#End Region
Protected Overrides ReadOnly Property LanguageName As String
Get
Return LanguageNames.VisualBasic
End Get
End Property
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.VisualBasic
Public Class OptionsStatementTests
Inherits AbstractCodeElementTests
#Region "GetStartPoint() tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetStartPoint1()
Dim code =
<Code>
Option $$Strict On
Class C
End Class
</Code>
TestGetStartPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartName,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=1, lineOffset:=1, absoluteOffset:=1, lineLength:=16)))
End Sub
#End Region
#Region "GetEndPoint() tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetEndPoint1()
Dim code =
<Code>
Option $$Strict On
Class C
End Class
</Code>
TestGetEndPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=1, lineOffset:=17, absoluteOffset:=17, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=1, lineOffset:=17, absoluteOffset:=17, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=1, lineOffset:=17, absoluteOffset:=17, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=1, lineOffset:=17, absoluteOffset:=17, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartName,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=1, lineOffset:=17, absoluteOffset:=17, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=1, lineOffset:=17, absoluteOffset:=17, lineLength:=16)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=1, lineOffset:=17, absoluteOffset:=17, lineLength:=16)))
End Sub
#End Region
#Region "Kind tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestKind1()
Dim code =
<Code>
$$Option Strict On
</Code>
TestKind(code, EnvDTE.vsCMElement.vsCMElementOptionStmt)
End Sub
#End Region
#Region "Name tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestName1()
Dim code =
<Code>
$$Option Strict On
</Code>
TestName(code, "Option Strict On")
End Sub
#End Region
Protected Overrides ReadOnly Property LanguageName As String
Get
Return LanguageNames.VisualBasic
End Get
End Property
End Class
End Namespace
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/VisualBasic/Portable/Symbols/FieldOrPropertyInitializer.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Represents a field or property initializer. Holds the symbol and the syntax for the initialization.
''' </summary>
Friend Structure FieldOrPropertyInitializer
''' <summary>
''' The fields or properties being initialized, or Nothing if this represents an executable statement in script code.
''' We can get into a multiple properties case when multiple WithEvents fields are initialized with As New ...
''' </summary>
Public ReadOnly FieldsOrProperties As ImmutableArray(Of Symbol)
''' <summary>
''' A reference to
''' <see cref="EqualsValueSyntax"/>,
''' <see cref="AsNewClauseSyntax"/>,
''' <see cref="ModifiedIdentifierSyntax"/>,
''' <see cref="StatementSyntax"/> (top-level statement).
''' </summary>
Public ReadOnly Syntax As SyntaxReference
''' <summary>
''' A sum of widths of spans of all preceding initializers
''' (instance and static initializers are summed separately, and trivias are not counted).
''' </summary>
Friend ReadOnly PrecedingInitializersLength As Integer
Friend ReadOnly IsMetadataConstant As Boolean
''' <summary>
''' Initializer for an executable statement in script code.
''' </summary>
''' <param name="syntax">The initializer syntax for the statement.</param>
Public Sub New(syntax As SyntaxReference, precedingInitializersLength As Integer)
Debug.Assert(TypeOf syntax.GetSyntax() Is StatementSyntax)
Me.Syntax = syntax
Me.IsMetadataConstant = False
Me.PrecedingInitializersLength = precedingInitializersLength
End Sub
''' <summary>
''' Initializes a new instance of the <see cref="FieldOrPropertyInitializer" /> structure.
''' </summary>
''' <param name="field">The field.</param>
''' <param name="syntax">The initializer syntax for the field.</param>
Public Sub New(field As FieldSymbol, syntax As SyntaxReference, precedingInitializersLength As Integer)
Debug.Assert(field IsNot Nothing)
Debug.Assert(syntax.GetSyntax().IsKind(SyntaxKind.AsNewClause) OrElse
syntax.GetSyntax().IsKind(SyntaxKind.EqualsValue) OrElse
syntax.GetSyntax().IsKind(SyntaxKind.ModifiedIdentifier))
Me.FieldsOrProperties = ImmutableArray.Create(Of Symbol)(field)
Me.Syntax = syntax
Me.IsMetadataConstant = field.IsMetadataConstant
Me.PrecedingInitializersLength = precedingInitializersLength
End Sub
''' <summary>
''' Initializes a new instance of the <see cref="FieldOrPropertyInitializer" /> structure.
''' </summary>
Public Sub New(fieldsOrProperties As ImmutableArray(Of Symbol), syntax As SyntaxReference, precedingInitializersLength As Integer)
Debug.Assert(Not fieldsOrProperties.IsEmpty)
Debug.Assert(syntax.GetSyntax().IsKind(SyntaxKind.AsNewClause) OrElse syntax.GetSyntax().IsKind(SyntaxKind.EqualsValue))
Me.FieldsOrProperties = fieldsOrProperties
Me.Syntax = syntax
Me.IsMetadataConstant = False
Me.PrecedingInitializersLength = precedingInitializersLength
End Sub
''' <summary>
''' Initializes a new instance of the <see cref="FieldOrPropertyInitializer" /> structure.
''' </summary>
''' <param name="property">The property.</param>
''' <param name="syntax">The initializer syntax for the property.</param>
Public Sub New([property] As PropertySymbol, syntax As SyntaxReference, precedingInitializersLength As Integer)
Debug.Assert([property] IsNot Nothing)
Debug.Assert(syntax IsNot Nothing)
Debug.Assert(syntax.GetSyntax().IsKind(SyntaxKind.AsNewClause) OrElse syntax.GetSyntax().IsKind(SyntaxKind.EqualsValue))
Me.FieldsOrProperties = ImmutableArray.Create(Of Symbol)([property])
Me.Syntax = syntax
Me.IsMetadataConstant = False
Me.PrecedingInitializersLength = precedingInitializersLength
End Sub
End Structure
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Represents a field or property initializer. Holds the symbol and the syntax for the initialization.
''' </summary>
Friend Structure FieldOrPropertyInitializer
''' <summary>
''' The fields or properties being initialized, or Nothing if this represents an executable statement in script code.
''' We can get into a multiple properties case when multiple WithEvents fields are initialized with As New ...
''' </summary>
Public ReadOnly FieldsOrProperties As ImmutableArray(Of Symbol)
''' <summary>
''' A reference to
''' <see cref="EqualsValueSyntax"/>,
''' <see cref="AsNewClauseSyntax"/>,
''' <see cref="ModifiedIdentifierSyntax"/>,
''' <see cref="StatementSyntax"/> (top-level statement).
''' </summary>
Public ReadOnly Syntax As SyntaxReference
''' <summary>
''' A sum of widths of spans of all preceding initializers
''' (instance and static initializers are summed separately, and trivias are not counted).
''' </summary>
Friend ReadOnly PrecedingInitializersLength As Integer
Friend ReadOnly IsMetadataConstant As Boolean
''' <summary>
''' Initializer for an executable statement in script code.
''' </summary>
''' <param name="syntax">The initializer syntax for the statement.</param>
Public Sub New(syntax As SyntaxReference, precedingInitializersLength As Integer)
Debug.Assert(TypeOf syntax.GetSyntax() Is StatementSyntax)
Me.Syntax = syntax
Me.IsMetadataConstant = False
Me.PrecedingInitializersLength = precedingInitializersLength
End Sub
''' <summary>
''' Initializes a new instance of the <see cref="FieldOrPropertyInitializer" /> structure.
''' </summary>
''' <param name="field">The field.</param>
''' <param name="syntax">The initializer syntax for the field.</param>
Public Sub New(field As FieldSymbol, syntax As SyntaxReference, precedingInitializersLength As Integer)
Debug.Assert(field IsNot Nothing)
Debug.Assert(syntax.GetSyntax().IsKind(SyntaxKind.AsNewClause) OrElse
syntax.GetSyntax().IsKind(SyntaxKind.EqualsValue) OrElse
syntax.GetSyntax().IsKind(SyntaxKind.ModifiedIdentifier))
Me.FieldsOrProperties = ImmutableArray.Create(Of Symbol)(field)
Me.Syntax = syntax
Me.IsMetadataConstant = field.IsMetadataConstant
Me.PrecedingInitializersLength = precedingInitializersLength
End Sub
''' <summary>
''' Initializes a new instance of the <see cref="FieldOrPropertyInitializer" /> structure.
''' </summary>
Public Sub New(fieldsOrProperties As ImmutableArray(Of Symbol), syntax As SyntaxReference, precedingInitializersLength As Integer)
Debug.Assert(Not fieldsOrProperties.IsEmpty)
Debug.Assert(syntax.GetSyntax().IsKind(SyntaxKind.AsNewClause) OrElse syntax.GetSyntax().IsKind(SyntaxKind.EqualsValue))
Me.FieldsOrProperties = fieldsOrProperties
Me.Syntax = syntax
Me.IsMetadataConstant = False
Me.PrecedingInitializersLength = precedingInitializersLength
End Sub
''' <summary>
''' Initializes a new instance of the <see cref="FieldOrPropertyInitializer" /> structure.
''' </summary>
''' <param name="property">The property.</param>
''' <param name="syntax">The initializer syntax for the property.</param>
Public Sub New([property] As PropertySymbol, syntax As SyntaxReference, precedingInitializersLength As Integer)
Debug.Assert([property] IsNot Nothing)
Debug.Assert(syntax IsNot Nothing)
Debug.Assert(syntax.GetSyntax().IsKind(SyntaxKind.AsNewClause) OrElse syntax.GetSyntax().IsKind(SyntaxKind.EqualsValue))
Me.FieldsOrProperties = ImmutableArray.Create(Of Symbol)([property])
Me.Syntax = syntax
Me.IsMetadataConstant = False
Me.PrecedingInitializersLength = precedingInitializersLength
End Sub
End Structure
End Namespace
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenOperators.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.CSharp.UnitTests.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using System.Collections.Immutable;
using System.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public class CodeGenOperators : CSharpTestBase
{
[Fact]
public void TestIsNullPattern()
{
var source = @"
using System;
class C
{
public static void Main()
{
var c = new C();
Console.Write(c is null);
}
}
";
// Release
var compilation = CompileAndVerify(source, expectedOutput: "False", options: TestOptions.ReleaseExe);
compilation.VerifyIL("C.Main", @"{
// Code size 14 (0xe)
.maxstack 2
IL_0000: newobj ""C..ctor()""
IL_0005: ldnull
IL_0006: ceq
IL_0008: call ""void System.Console.Write(bool)""
IL_000d: ret
}");
// Debug
compilation = CompileAndVerify(source, expectedOutput: "False", options: TestOptions.DebugExe);
compilation.VerifyIL("C.Main", @"{
// Code size 18 (0x12)
.maxstack 2
.locals init (C V_0) //c
IL_0000: nop
IL_0001: newobj ""C..ctor()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldnull
IL_0009: ceq
IL_000b: call ""void System.Console.Write(bool)""
IL_0010: nop
IL_0011: ret
}");
}
[Fact]
public void TestIsNullPatternGenericParam()
{
var source = @"
using System;
class C
{
public static void M<T>(T o)
{
Console.Write(o is null);
if (o is null)
{
Console.Write(""Branch taken"");
}
}
public static void Main()
{
M(new object());
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "False", options: TestOptions.ReleaseExe);
compilation.VerifyIL("C.M<T>(T)", @"{
// Code size 33 (0x21)
.maxstack 2
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: ldnull
IL_0007: ceq
IL_0009: call ""void System.Console.Write(bool)""
IL_000e: ldarg.0
IL_000f: box ""T""
IL_0014: brtrue.s IL_0020
IL_0016: ldstr ""Branch taken""
IL_001b: call ""void System.Console.Write(string)""
IL_0020: ret
}");
// Debug
compilation = CompileAndVerify(source, expectedOutput: "False", options: TestOptions.DebugExe);
compilation.VerifyIL("C.M<T>(T)", @"{
// Code size 43 (0x2b)
.maxstack 2
.locals init (bool V_0)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: box ""T""
IL_0007: ldnull
IL_0008: ceq
IL_000a: call ""void System.Console.Write(bool)""
IL_000f: nop
IL_0010: ldarg.0
IL_0011: box ""T""
IL_0016: ldnull
IL_0017: ceq
IL_0019: stloc.0
IL_001a: ldloc.0
IL_001b: brfalse.s IL_002a
IL_001d: nop
IL_001e: ldstr ""Branch taken""
IL_0023: call ""void System.Console.Write(string)""
IL_0028: nop
IL_0029: nop
IL_002a: ret
}");
}
[Fact]
public void TestIsNullPatternGenericParamClass()
{
var source = @"
using System;
class C
{
public static void M<T>(T o) where T: class
{
Console.Write(o is null);
if (o is null) {
Console.Write("" Branch taken"");
}
}
public static void Main()
{
M(new object());
}
}
";
// Release
var compilation = CompileAndVerify(source, expectedOutput: "False", options: TestOptions.ReleaseExe);
compilation.VerifyIL("C.M<T>(T)", @"{
// Code size 33 (0x21)
.maxstack 2
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: ldnull
IL_0007: ceq
IL_0009: call ""void System.Console.Write(bool)""
IL_000e: ldarg.0
IL_000f: box ""T""
IL_0014: brtrue.s IL_0020
IL_0016: ldstr "" Branch taken""
IL_001b: call ""void System.Console.Write(string)""
IL_0020: ret
}");
// Debug
compilation = CompileAndVerify(source, expectedOutput: "False", options: TestOptions.DebugExe);
compilation.VerifyIL("C.M<T>(T)", @"{
// Code size 43 (0x2b)
.maxstack 2
.locals init (bool V_0)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: box ""T""
IL_0007: ldnull
IL_0008: ceq
IL_000a: call ""void System.Console.Write(bool)""
IL_000f: nop
IL_0010: ldarg.0
IL_0011: box ""T""
IL_0016: ldnull
IL_0017: ceq
IL_0019: stloc.0
IL_001a: ldloc.0
IL_001b: brfalse.s IL_002a
IL_001d: nop
IL_001e: ldstr "" Branch taken""
IL_0023: call ""void System.Console.Write(string)""
IL_0028: nop
IL_0029: nop
IL_002a: ret
}");
}
[Fact]
public void TestIsNullPatternNullable()
{
var source = @"
using System;
class C
{
public static void M(Nullable<int> obj)
{
Console.Write(obj is null);
if (obj is null) {
Console.Write("" Branch taken"");
} else {
Console.Write("" Branch not taken"");
}
}
public static void Main()
{
M(5);
Console.Write(""-"");
M(null);
}
}
";
// Release
var compilation = CompileAndVerify(source, expectedOutput: "False Branch not taken-True Branch taken", options: TestOptions.ReleaseExe);
compilation.VerifyIL("C.M", @"{
// Code size 46 (0x2e)
.maxstack 2
IL_0000: ldarga.s V_0
IL_0002: call ""bool int?.HasValue.get""
IL_0007: ldc.i4.0
IL_0008: ceq
IL_000a: call ""void System.Console.Write(bool)""
IL_000f: ldarga.s V_0
IL_0011: call ""bool int?.HasValue.get""
IL_0016: brtrue.s IL_0023
IL_0018: ldstr "" Branch taken""
IL_001d: call ""void System.Console.Write(string)""
IL_0022: ret
IL_0023: ldstr "" Branch not taken""
IL_0028: call ""void System.Console.Write(string)""
IL_002d: ret
}");
// Debug
compilation = CompileAndVerify(source, expectedOutput: "False Branch not taken-True Branch taken", options: TestOptions.DebugExe);
compilation.VerifyIL("C.M", @"{
// Code size 60 (0x3c)
.maxstack 2
.locals init (bool V_0)
IL_0000: nop
IL_0001: ldarga.s V_0
IL_0003: call ""bool int?.HasValue.get""
IL_0008: ldc.i4.0
IL_0009: ceq
IL_000b: call ""void System.Console.Write(bool)""
IL_0010: nop
IL_0011: ldarga.s V_0
IL_0013: call ""bool int?.HasValue.get""
IL_0018: ldc.i4.0
IL_0019: ceq
IL_001b: stloc.0
IL_001c: ldloc.0
IL_001d: brfalse.s IL_002e
IL_001f: nop
IL_0020: ldstr "" Branch taken""
IL_0025: call ""void System.Console.Write(string)""
IL_002a: nop
IL_002b: nop
IL_002c: br.s IL_003b
IL_002e: nop
IL_002f: ldstr "" Branch not taken""
IL_0034: call ""void System.Console.Write(string)""
IL_0039: nop
IL_003a: nop
IL_003b: ret
}");
}
[Fact]
public void TestIsNullPatternObjectLiteral()
{
var source = @"
using System;
class C
{
public static void Main()
{
Console.Write(((object)null) is null);
if (((object) null) is null) {
Console.Write("" Branch taken"");
}
}
}
";
// Release
var compilation = CompileAndVerify(source, expectedOutput: "True Branch taken", options: TestOptions.ReleaseExe);
compilation.VerifyIL("C.Main", @"{
// Code size 17 (0x11)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: call ""void System.Console.Write(bool)""
IL_0006: ldstr "" Branch taken""
IL_000b: call ""void System.Console.Write(string)""
IL_0010: ret
}");
// Debug
compilation = CompileAndVerify(source, expectedOutput: "True Branch taken", options: TestOptions.DebugExe);
compilation.VerifyIL("C.Main", @"
{
// Code size 27 (0x1b)
.maxstack 1
.locals init (bool V_0)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: call ""void System.Console.Write(bool)""
IL_0007: nop
IL_0008: ldc.i4.1
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_001a
IL_000d: nop
IL_000e: ldstr "" Branch taken""
IL_0013: call ""void System.Console.Write(string)""
IL_0018: nop
IL_0019: nop
IL_001a: ret
}");
}
[Fact]
public void TestIsNullPatternStringConstant()
{
var source = @"
using System;
class C
{
const String nullString = null;
public static void Main()
{
Console.Write(((string)null) is nullString);
if (((string) null) is nullString) {
Console.Write("" Branch taken"");
}
}
}
";
// Release
var compilation = CompileAndVerify(source, expectedOutput: "True Branch taken", options: TestOptions.ReleaseExe);
compilation.VerifyIL("C.Main", @"{
// Code size 17 (0x11)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: call ""void System.Console.Write(bool)""
IL_0006: ldstr "" Branch taken""
IL_000b: call ""void System.Console.Write(string)""
IL_0010: ret
}");
// Debug
compilation = CompileAndVerify(source, expectedOutput: "True Branch taken", options: TestOptions.DebugExe);
compilation.VerifyIL("C.Main", @"{
// Code size 27 (0x1b)
.maxstack 1
.locals init (bool V_0)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: call ""void System.Console.Write(bool)""
IL_0007: nop
IL_0008: ldc.i4.1
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_001a
IL_000d: nop
IL_000e: ldstr "" Branch taken""
IL_0013: call ""void System.Console.Write(string)""
IL_0018: nop
IL_0019: nop
IL_001a: ret
}");
}
[Fact]
public void TestDelegateAndStringOperators()
{
var source = @"
using System;
class C
{
delegate void D();
public static void M123()
{
Console.WriteLine(123);
}
public static void M456()
{
Console.WriteLine(456);
}
public static void Main()
{
D d123 = M123;
D d456 = M456;
D d123456 = d123 + d456;
d123456();
Console.WriteLine(d123456 - d123 == d456);
Console.WriteLine(d123456 - d123 == d123);
string s123 = 123.ToString();
object s456 = 456.ToString();
Console.WriteLine(s123 + s456);
Console.WriteLine(s123 + s456 + s123);
}
}
";
string expectedOutput =
@"123
456
True
False
123456
123456123
";
var compilation = CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void TestCompoundAssignmentOperators()
{
var source = @"
using System;
class C
{
delegate void D();
public static void M123()
{
Console.Write(123);
}
public static void M456()
{
Console.Write(456);
}
static C c;
static C GetC() { Console.Write(""GetC""); return c; }
byte f;
public static void Main()
{
C.c = new C();
D d123 = M123;
D d456 = M456;
D d = null;
d += d123;
d();
d += d456;
d();
d -= d123;
d();
Console.WriteLine();
short b = 100;
b -= 70;
Console.Write(b);
b *= 2;
Console.Write(b);
Console.WriteLine();
string s = string.Empty;
s += 789.ToString();
Console.Write(s);
s += 987.ToString();
Console.Write(s);
Console.WriteLine();
GetC().f += 100;
Console.Write(C.c.f);
Console.WriteLine();
int[] arr = { 10 };
arr[0] += 1;
Console.Write(arr[0]);
Console.WriteLine();
}
}
";
string expectedOutput =
@"123123456456
3060
789789987
GetC100
11";
var compilation = CompileAndVerify(source, expectedOutput: expectedOutput);
}
// TODO: Add VerifyIL for is and as Codegen tests
[Fact]
public void TestIsOperator()
{
var source = @"
namespace TestIsOperator
{
public interface MyInter { }
public class TestType : MyInter { }
public class AnotherType { }
public class MyBase { }
public class MyDerived : MyBase { }
public class C
{
static void Main()
{
string myStr = ""goo"";
object o = myStr;
bool b = o is string;
int myInt = 3;
b = myInt is int;
TestType tt = null;
o = tt;
b = o is TestType;
tt = new TestType();
o = tt;
b = o is AnotherType;
b = o is MyInter;
MyInter mi = new TestType();
o = mi;
b = o is MyInter;
MyBase mb = new MyBase();
o = mb;
b = o is MyDerived;
MyDerived md = new MyDerived();
o = md;
b = o is MyBase;
b = null is MyBase;
}
}
}
";
var compilation = CompileAndVerify(source);
}
// TODO: Add VerifyIL for is and as Codegen tests
[Fact]
public void TestIsOperatorGeneric()
{
var source = @"
namespace TestIsOperatorGeneric
{
public class C
{
public static void Main() { }
public static void M<T, U, W>(T t, U u, W w)
where T : class
where U : class
where W : class
{
bool test = t is int;
test = u is object;
test = t is U;
test = t is T;
test = u is U;
test = u is T;
test = w is int;
test = w is object;
test = w is U;
test = u is W;
test = t is W;
test = w is W;
}
}
}
";
var compilation = CompileAndVerify(source);
}
[Fact]
public void CS0184WRN_IsAlwaysFalse()
{
var text = @"
class MyClass
{
public static int Main()
{
int i = 0;
bool b = i is string; // CS0184
System.Console.WriteLine(b);
return 0;
}
}
";
var comp = CompileAndVerify(text, expectedOutput: "False");
comp.VerifyDiagnostics(
// (7,18): warning CS0184: The given expression is never of the provided ('string') type
// bool b = i is string; // CS0184
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "i is string").WithArguments("string"));
comp.VerifyIL("MyClass.Main", @"
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: call ""void System.Console.WriteLine(bool)""
IL_0006: ldc.i4.0
IL_0007: ret
}");
}
[WorkItem(542466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542466")]
[Fact]
public void CS0184WRN_IsAlwaysFalse_Enum()
{
var text = @"
class IsTest
{
static void Main()
{
var b = 1 is color;
System.Console.WriteLine(b);
}
}
enum color
{ }
";
var comp = CompileAndVerify(text, expectedOutput: "False");
comp.VerifyDiagnostics(
// (6,17): warning CS0184: The given expression is never of the provided ('color') type
// var b = 1 is color;
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "1 is color").WithArguments("color"));
comp.VerifyIL("IsTest.Main", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: call ""void System.Console.WriteLine(bool)""
IL_0006: ret
}");
}
[WorkItem(542466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542466")]
[Fact]
public void CS0184WRN_IsAlwaysFalse_ExplicitEnumeration()
{
var text = @"
class IsTest
{
static void Main()
{
var b = default(color) is int;
System.Console.WriteLine(b);
}
}
enum color
{ }
";
var comp = CompileAndVerify(text, expectedOutput: "False");
comp.VerifyDiagnostics(
// (6,17): warning CS0184: The given expression is never of the provided ('int') type
// var b = default(color) is int;
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "default(color) is int").WithArguments("int"));
comp.VerifyIL("IsTest.Main", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: call ""void System.Console.WriteLine(bool)""
IL_0006: ret
}");
}
[WorkItem(542466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542466")]
[Fact]
public void CS0184WRN_IsAlwaysFalse_ImplicitNumeric()
{
var text = @"
class IsTest
{
static void Main()
{
var b = 1 is double;
System.Console.WriteLine(b);
}
}
";
var comp = CompileAndVerify(text, expectedOutput: "False");
comp.VerifyDiagnostics(
// (6,17): warning CS0184: The given expression is never of the provided ('double') type
// var b = 1 is double;
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "1 is double").WithArguments("double"));
comp.VerifyIL("IsTest.Main", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: call ""void System.Console.WriteLine(bool)""
IL_0006: ret
}");
}
[Fact, WorkItem(542466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542466")]
public void CS0184WRN_IsAlwaysFalse_ExplicitNumeric()
{
var text = @"
class IsTest
{
static void Main()
{
var b = 1.0 is int;
System.Console.WriteLine(b);
b = 1.0 is float;
System.Console.WriteLine(b);
b = 1 is byte;
System.Console.WriteLine(b);
}
}
";
var comp = CompileAndVerify(text, expectedOutput: @"False
False
False");
comp.VerifyDiagnostics(
// (6,17): warning CS0184: The given expression is never of the provided ('int') type
// var b = 1.0 is int;
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "1.0 is int").WithArguments("int"),
// (7,13): warning CS0184: The given expression is never of the provided ('float') type
// b = 1.0 is float;
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "1.0 is float").WithArguments("float"),
// (8,13): warning CS0184: The given expression is never of the provided ('byte') type
// b = 1 is byte;
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "1 is byte").WithArguments("byte"));
comp.VerifyIL("IsTest.Main", @"
{
// Code size 19 (0x13)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: call ""void System.Console.WriteLine(bool)""
IL_0006: ldc.i4.0
IL_0007: call ""void System.Console.WriteLine(bool)""
IL_000c: ldc.i4.0
IL_000d: call ""void System.Console.WriteLine(bool)""
IL_0012: ret
}");
}
[Fact, WorkItem(546371, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546371")]
public void CS0184WRN_IsAlwaysFalse_NumericIsNullable()
{
#region src
var text = @"using System;
public class Test
{
const char v0 = default(char);
public static sbyte v1 = default(sbyte);
internal static byte v2 = 0;// default(byte);
protected static short v3 = 0; // default(short);
private static ushort v4 = default(ushort);
static void Main()
{
const int v5 = 0; // default(int);
uint v6 = 0; // default(uint);
long v7 = 0; // default(long);
const ulong v8 = default(ulong);
float v9 = default(float);
// char
if (v0 is ushort?)
Console.Write(0);
else
Console.Write(1);
// sbyte & byte
if (v1 is short? || v2 is short?)
Console.Write(0);
else
Console.Write(2);
// short & ushort
if (v3 is int? || v4 is int?)
Console.Write(0);
else
Console.Write(3);
// int & uint
if (v5 is long? || v6 is long?)
Console.Write(0);
else
Console.Write(4);
// long & ulong
if (v7 is float? || v8 is float?)
Console.Write(0);
else
Console.Write(5);
// float
if (v9 is int?)
Console.Write(0);
else
Console.Write(6);
}
}
";
#endregion
var comp = CompileAndVerify(text, expectedOutput: @"123456");
comp.VerifyDiagnostics(
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "v0 is ushort?").WithArguments("ushort?"),
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "v1 is short?").WithArguments("short?"),
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "v2 is short?").WithArguments("short?"),
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "v3 is int?").WithArguments("int?"),
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "v4 is int?").WithArguments("int?"),
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "v5 is long?").WithArguments("long?"),
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "v6 is long?").WithArguments("long?"),
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "v7 is float?").WithArguments("float?"),
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "v8 is float?").WithArguments("float?"),
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "v9 is int?").WithArguments("int?")
);
comp.VerifyIL("Test.Main", @"
{
// Code size 61 (0x3d)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: call ""void System.Console.Write(int)""
IL_0006: ldsfld ""sbyte Test.v1""
IL_000b: pop
IL_000c: ldsfld ""byte Test.v2""
IL_0011: pop
IL_0012: ldc.i4.2
IL_0013: call ""void System.Console.Write(int)""
IL_0018: ldsfld ""short Test.v3""
IL_001d: pop
IL_001e: ldsfld ""ushort Test.v4""
IL_0023: pop
IL_0024: ldc.i4.3
IL_0025: call ""void System.Console.Write(int)""
IL_002a: ldc.i4.4
IL_002b: call ""void System.Console.Write(int)""
IL_0030: ldc.i4.5
IL_0031: call ""void System.Console.Write(int)""
IL_0036: ldc.i4.6
IL_0037: call ""void System.Console.Write(int)""
IL_003c: ret
}
");
}
// TODO: Add VerifyIL for is and as Codegen tests
[Fact]
public void TestAsOperator()
{
var source = @"
namespace TestAsOperator
{
public interface MyInter {}
public class TestType : MyInter {}
public class AnotherType {}
public class MyBase {}
public class MyDerived : MyBase { }
public class C
{
static void Main()
{
string myStr = ""goo"";
object o = myStr;
object b = o as string;
TestType tt = null;
o = tt;
b = o as TestType;
tt = new TestType();
o = tt;
b = o as AnotherType;
b = o as MyInter;
MyInter mi = new TestType();
o = mi;
b = o as MyInter;
MyBase mb = new MyBase();
o = mb;
b = o as MyDerived;
MyDerived md = new MyDerived();
o = md;
b = o as MyBase;
b = null as MyBase;
}
}
}
";
var compilation = CompileAndVerify(source);
}
[Fact]
public void TestAsOperatorGeneric()
{
var source = @"
public class TestAsOperatorGeneric
{
public static void Main() { }
public static void M<T, U, W>(T t, U u, W w)
where T : class
where U : class
where W : class
{
object test2 = u as object;
System.Console.WriteLine(test2);
U test3 = t as U;
System.Console.WriteLine(test3);
T test4 = t as T;
System.Console.WriteLine(test4);
U test5 = u as U;
System.Console.WriteLine(test5);
T test12 = u as T;
System.Console.WriteLine(test12);
object test7 = w as object;
System.Console.WriteLine(test7);
U test8 = w as U;
System.Console.WriteLine(test8);
W test9 = u as W;
System.Console.WriteLine(test9);
W test10 = t as W;
System.Console.WriteLine(test10);
W test11 = w as W;
System.Console.WriteLine(test11);
}
}
";
var compilation = CompileAndVerify(source);
compilation.VerifyIL("TestAsOperatorGeneric.M<T, U, W>(T, U, W)",
@"{
// Code size 186 (0xba)
.maxstack 1
IL_0000: ldarg.1
IL_0001: box ""U""
IL_0006: call ""void System.Console.WriteLine(object)""
IL_000b: ldarg.0
IL_000c: box ""T""
IL_0011: isinst ""U""
IL_0016: unbox.any ""U""
IL_001b: box ""U""
IL_0020: call ""void System.Console.WriteLine(object)""
IL_0025: ldarg.0
IL_0026: box ""T""
IL_002b: call ""void System.Console.WriteLine(object)""
IL_0030: ldarg.1
IL_0031: box ""U""
IL_0036: call ""void System.Console.WriteLine(object)""
IL_003b: ldarg.1
IL_003c: box ""U""
IL_0041: isinst ""T""
IL_0046: unbox.any ""T""
IL_004b: box ""T""
IL_0050: call ""void System.Console.WriteLine(object)""
IL_0055: ldarg.2
IL_0056: box ""W""
IL_005b: call ""void System.Console.WriteLine(object)""
IL_0060: ldarg.2
IL_0061: box ""W""
IL_0066: isinst ""U""
IL_006b: unbox.any ""U""
IL_0070: box ""U""
IL_0075: call ""void System.Console.WriteLine(object)""
IL_007a: ldarg.1
IL_007b: box ""U""
IL_0080: isinst ""W""
IL_0085: unbox.any ""W""
IL_008a: box ""W""
IL_008f: call ""void System.Console.WriteLine(object)""
IL_0094: ldarg.0
IL_0095: box ""T""
IL_009a: isinst ""W""
IL_009f: unbox.any ""W""
IL_00a4: box ""W""
IL_00a9: call ""void System.Console.WriteLine(object)""
IL_00ae: ldarg.2
IL_00af: box ""W""
IL_00b4: call ""void System.Console.WriteLine(object)""
IL_00b9: ret
}");
}
[Fact, WorkItem(754408, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754408")]
public void TestNullCoalesce_DynamicAndObject()
{
var source = @"using System;
public class A {}
public class C
{
public static dynamic Get()
{
object a = new A();
dynamic b = new A();
return a ?? b;
}
public static void Main()
{
var c = Get();
}
}";
var comp = CompileAndVerify(source,
references: new[] { CSharpRef },
expectedOutput: string.Empty);
comp.VerifyIL("C.Get",
@"{
// Code size 17 (0x11)
.maxstack 2
.locals init (object V_0) //b
IL_0000: newobj ""A..ctor()""
IL_0005: newobj ""A..ctor()""
IL_000a: stloc.0
IL_000b: dup
IL_000c: brtrue.s IL_0010
IL_000e: pop
IL_000f: ldloc.0
IL_0010: ret
}");
}
[Fact]
public void TestNullCoalesce_Implicit_b_To_a_nullable()
{
var source = @"
using System;
// a ?? b
public class E : D { }
public class D { }
public class C
{
public static int Main()
{
Nullable_a_Implicit_b_to_a0_null_a('a');
Nullable_a_Implicit_b_to_a0_constant_non_null_a('a');
Nullable_a_Implicit_b_to_a0_not_null_a('a', 10);
return 0;
}
public static int Nullable_a_Implicit_b_to_a0_null_a(char ch)
{
char b = ch;
int? a = null;
int z = a ?? b;
return z;
}
public static int Nullable_a_Implicit_b_to_a0_constant_non_null_a(char ch)
{
char b = ch;
int? a = 10;
int z = a ?? b;
return z;
}
public static int Nullable_a_Implicit_b_to_a0_not_null_a(char ch, int? i)
{
char b = ch;
int? a = i;
int z = a ?? b;
return z;
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: string.Empty);
compilation.VerifyIL("C.Nullable_a_Implicit_b_to_a0_null_a", @"
{
// Code size 31 (0x1f)
.maxstack 1
.locals init (char V_0, //b
int? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_1
IL_0004: initobj ""int?""
IL_000a: ldloc.1
IL_000b: stloc.1
IL_000c: ldloca.s V_1
IL_000e: call ""bool int?.HasValue.get""
IL_0013: brtrue.s IL_0017
IL_0015: ldloc.0
IL_0016: ret
IL_0017: ldloca.s V_1
IL_0019: call ""int int?.GetValueOrDefault()""
IL_001e: ret
}
");
compilation.VerifyIL("C.Nullable_a_Implicit_b_to_a0_constant_non_null_a", @"
{
// Code size 29 (0x1d)
.maxstack 1
.locals init (char V_0, //b
int? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldc.i4.s 10
IL_0004: newobj ""int?..ctor(int)""
IL_0009: stloc.1
IL_000a: ldloca.s V_1
IL_000c: call ""bool int?.HasValue.get""
IL_0011: brtrue.s IL_0015
IL_0013: ldloc.0
IL_0014: ret
IL_0015: ldloca.s V_1
IL_0017: call ""int int?.GetValueOrDefault()""
IL_001c: ret
}");
compilation.VerifyIL("C.Nullable_a_Implicit_b_to_a0_not_null_a", @"
{
// Code size 23 (0x17)
.maxstack 1
.locals init (char V_0, //b
int? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldarg.1
IL_0003: stloc.1
IL_0004: ldloca.s V_1
IL_0006: call ""bool int?.HasValue.get""
IL_000b: brtrue.s IL_000f
IL_000d: ldloc.0
IL_000e: ret
IL_000f: ldloca.s V_1
IL_0011: call ""int int?.GetValueOrDefault()""
IL_0016: ret
}
");
}
[Fact]
public void TestNullCoalesce_Nullable_a_Implicit_b_to_a0()
{
var source = @"
using System;
// a ?? b
public class E : D { }
public class D { }
public class C
{
public static int Main()
{
Nullable_a_Implicit_b_to_a0_null_a('a');
Nullable_a_Implicit_b_to_a0_constant_non_null_a('a');
Nullable_a_Implicit_b_to_a0_not_null_a('a', 10);
Nullable_a_Implicit_b_to_a_null_a('a');
Nullable_a_Implicit_b_to_a_constant_non_null_a('a');
Nullable_a_Implicit_b_to_a_not_null_a('a', 10);
return 0;
}
public static int Nullable_a_Implicit_b_to_a0_null_a(char ch)
{
char b = ch;
int? a = null;
int z = a ?? b;
return z;
}
public static int Nullable_a_Implicit_b_to_a0_constant_non_null_a(char ch)
{
char b = ch;
int? a = 10;
int z = a ?? b;
return z;
}
public static int Nullable_a_Implicit_b_to_a0_not_null_a(char ch, int? i)
{
char b = ch;
int? a = i;
int z = a ?? b;
return z;
}
public static int? Nullable_a_Implicit_b_to_a_null_a(char? ch)
{
char? b = ch;
int? a = null;
int? z = a ?? b;
return z;
}
public static int? Nullable_a_Implicit_b_to_a_constant_non_null_a(char? ch)
{
char? b = ch;
int? a = 10;
int? z = a ?? b;
return z;
}
public static int? Nullable_a_Implicit_b_to_a_not_null_a(char ch, int? i)
{
char? b = ch;
int? a = i;
int? z = a ?? b;
return z;
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: string.Empty);
compilation.VerifyIL("C.Nullable_a_Implicit_b_to_a0_null_a", @"
{
// Code size 31 (0x1f)
.maxstack 1
.locals init (char V_0, //b
int? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_1
IL_0004: initobj ""int?""
IL_000a: ldloc.1
IL_000b: stloc.1
IL_000c: ldloca.s V_1
IL_000e: call ""bool int?.HasValue.get""
IL_0013: brtrue.s IL_0017
IL_0015: ldloc.0
IL_0016: ret
IL_0017: ldloca.s V_1
IL_0019: call ""int int?.GetValueOrDefault()""
IL_001e: ret
}");
}
[Fact]
public void TestNullCoalesce_Nullable_a_ImplicitReference_a_to_b()
{
var source = @"
using System;
// a ?? b
public class E : D { }
public class D { }
public class C
{
public static int Main()
{
ImplicitReference_a_to_b_null_a_nullable(10);
ImplicitReference_a_to_b_constant_nonnull_a_nullable(10);
ImplicitReference_a_to_b_not_null_a_nullable(10, 'a');
Null_Literal_a('a');
return 0;
}
public static int? ImplicitReference_a_to_b_null_a_nullable(int? c)
{
int? b = c;
char? a = null;
int? z = a ?? b;
return z;
}
public static int? ImplicitReference_a_to_b_constant_nonnull_a_nullable(int? c)
{
int? b = c;
char? a = 'a';
int? z = a ?? b;
return z;
}
public static int? ImplicitReference_a_to_b_not_null_a_nullable(int? c, char? d)
{
int? b = c;
char? a = d;
int? z = a ?? b;
return z;
}
public static char? Null_Literal_a(char? ch)
{
char? b = ch;
char? z = null ?? b;
return z;
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: string.Empty);
compilation.VerifyIL("C.ImplicitReference_a_to_b_null_a_nullable", @"
{
// Code size 36 (0x24)
.maxstack 1
.locals init (int? V_0, //b
char? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_1
IL_0004: initobj ""char?""
IL_000a: ldloc.1
IL_000b: stloc.1
IL_000c: ldloca.s V_1
IL_000e: call ""bool char?.HasValue.get""
IL_0013: brtrue.s IL_0017
IL_0015: ldloc.0
IL_0016: ret
IL_0017: ldloca.s V_1
IL_0019: call ""char char?.GetValueOrDefault()""
IL_001e: newobj ""int?..ctor(int)""
IL_0023: ret
}");
compilation.VerifyIL("C.Null_Literal_a", @"
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}");
}
[Fact]
public void TestNullCoalesce_ImplicitReference_a_to_b()
{
var source = @"
using System;
// a ?? b
public class E : D { }
public class D { }
public class C
{
public static int Main()
{
ImplicitReference_a_to_b_null_a();
ImplicitReference_a_to_b_not_null_a();
return 0;
}
public static D ImplicitReference_a_to_b_null_a()
{
D b = new D();
E a = null;
D z = a ?? b;
return z;
}
public static D ImplicitReference_a_to_b_not_null_a()
{
D b = new D();
E a = new E();
D z = a ?? b;
return z;
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: string.Empty);
compilation.VerifyIL("C.ImplicitReference_a_to_b_null_a", @"
{
// Code size 13 (0xd)
.maxstack 2
.locals init (D V_0) //b
IL_0000: newobj ""D..ctor()""
IL_0005: stloc.0
IL_0006: ldnull
IL_0007: dup
IL_0008: brtrue.s IL_000c
IL_000a: pop
IL_000b: ldloc.0
IL_000c: ret
}
");
compilation.VerifyIL("C.ImplicitReference_a_to_b_not_null_a",
@"
{
// Code size 17 (0x11)
.maxstack 2
.locals init (D V_0) //b
IL_0000: newobj ""D..ctor()""
IL_0005: stloc.0
IL_0006: newobj ""E..ctor()""
IL_000b: dup
IL_000c: brtrue.s IL_0010
IL_000e: pop
IL_000f: ldloc.0
IL_0010: ret
}
");
}
[Fact]
public void TestNullCoalesce_TypeParameter()
{
var source = @"
using System;
static class Program
{
static void Main()
{
Goo(default, 1000);
Goo(1, 1000);
Goo(default, ""String parameter 1"");
Goo(""String parameter 2"", ""Should not print"");
Goo((int?)null, 4);
Goo((int?)5, 1000);
Goo2(6, 1000);
Goo2<int?, object>(null, 7);
Goo2<int?, object>(8, 1000);
Goo2<int?, int?>(9, 1000);
Goo2<int?, int?>(null, 10);
}
static void Goo<T>(T x1, T x2)
{
Console.WriteLine(x1 ?? x2);
}
static void Goo2<T1, T2>(T1 t1, T2 t2, dynamic d = null) where T1 : T2
{
// Verifying no type errors
Console.WriteLine(t1 ?? t2);
dynamic d2 = t1 ?? d;
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"
0
1
String parameter 1
String parameter 2
4
5
6
7
8
9
10
");
comp.VerifyIL("Program.Goo<T>(T, T)", expectedIL: @"
{
// Code size 25 (0x19)
.maxstack 1
.locals init (T V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: box ""T""
IL_0008: brtrue.s IL_000d
IL_000a: ldarg.1
IL_000b: br.s IL_000e
IL_000d: ldloc.0
IL_000e: box ""T""
IL_0013: call ""void System.Console.WriteLine(object)""
IL_0018: ret
}
");
comp.VerifyIL("Program.Goo2<T1, T2>(T1, T2, dynamic)", expectedIL: @"
{
// Code size 44 (0x2c)
.maxstack 1
.locals init (T1 V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: box ""T1""
IL_0008: brtrue.s IL_000d
IL_000a: ldarg.1
IL_000b: br.s IL_0018
IL_000d: ldloc.0
IL_000e: box ""T1""
IL_0013: unbox.any ""T2""
IL_0018: box ""T2""
IL_001d: call ""void System.Console.WriteLine(object)""
IL_0022: ldarg.0
IL_0023: stloc.0
IL_0024: ldloc.0
IL_0025: box ""T1""
IL_002a: pop
IL_002b: ret
}
");
}
[Fact]
public void TestNullCoalesce_TypeParameter_DefaultLHS()
{
var source = @"
using System;
static class Program
{
static void Main()
{
Goo(10);
Goo(""String parameter"");
Goo((int?)3);
}
static void Goo<T>(T x)
{
Console.WriteLine(default(T) ?? x);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"
0
String parameter
3
");
comp.VerifyIL("Program.Goo<T>(T)", expectedIL: @"
{
// Code size 31 (0x1f)
.maxstack 1
.locals init (T V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj ""T""
IL_0008: ldloc.0
IL_0009: box ""T""
IL_000e: brtrue.s IL_0013
IL_0010: ldarg.0
IL_0011: br.s IL_0014
IL_0013: ldloc.0
IL_0014: box ""T""
IL_0019: call ""void System.Console.WriteLine(object)""
IL_001e: ret
}
");
}
[Fact]
public void TestNullCoalesce_NoDuplicateCallsToGoo()
{
var source = @"
// a ?? b
public class Test
{
static void Main()
{
object o = Goo() ?? Bar();
}
static object Goo()
{
System.Console.Write(""Goo"");
return new object();
}
static object Bar()
{
System.Console.Write(""Bar"");
return new object();
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "Goo");
compilation.VerifyIL("Test.Main", @"
{
// Code size 14 (0xe)
.maxstack 1
IL_0000: call ""object Test.Goo()""
IL_0005: brtrue.s IL_000d
IL_0007: call ""object Test.Bar()""
IL_000c: pop
IL_000d: ret
}
");
}
[WorkItem(541232, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541232")]
[Fact]
public void TestNullCoalesce_MethodGroups()
{
var source =
@"class C
{
static void M()
{
System.Action a = null;
a = a ?? M;
a = M ?? a;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (7,13): error CS0019: Operator '??' cannot be applied to operands of type 'method group' and 'System.Action'
Diagnostic(ErrorCode.ERR_BadBinaryOps, "M ?? a").WithArguments("??", "method group", "System.Action").WithLocation(7, 13));
}
/// <summary>
/// From orcas bug #42645. PEVerify fails.
/// </summary>
[Fact]
public void TestNullCoalesce_InterfaceRegression1()
{
var source = @"
using System.Collections.Generic;
using System.Security;
[assembly: SecurityTransparent()]
public class Test
{
static void Main()
{
int[] a = new int[] { };
List<int> b = new List<int>();
IEnumerable<int> c = a ?? (IEnumerable<int>)b;
Goo(c);
}
static void Goo<T>(T x)
{
System.Console.WriteLine(typeof(T));
}
}";
// Note the explicit casts, even though the conversions are
// implicit reference conversions.
var comp = CompileAndVerify(source, expectedOutput: "System.Collections.Generic.IEnumerable`1[System.Int32]");
comp.VerifyDiagnostics();
comp.VerifyIL("Test.Main", @"
{
// Code size 25 (0x19)
.maxstack 2
.locals init (System.Collections.Generic.List<int> V_0, //b
System.Collections.Generic.IEnumerable<int> V_1)
IL_0000: ldc.i4.0
IL_0001: newarr ""int""
IL_0006: newobj ""System.Collections.Generic.List<int>..ctor()""
IL_000b: stloc.0
IL_000c: stloc.1
IL_000d: ldloc.1
IL_000e: dup
IL_000f: brtrue.s IL_0013
IL_0011: pop
IL_0012: ldloc.0
IL_0013: call ""void Test.Goo<System.Collections.Generic.IEnumerable<int>>(System.Collections.Generic.IEnumerable<int>)""
IL_0018: ret
}
");
}
[Fact]
public void TestNullCoalesce_InterfaceRegression1a()
{
var source = @"
using System.Collections.Generic;
public class Test
{
static void Main()
{
int[] a = new int[] { };
IEnumerable<int> b = new List<int>();
IEnumerable<int> c = b ?? a;
Goo(c);
}
static void Goo<T>(T x)
{
System.Console.WriteLine(typeof(T));
}
}";
var comp = CompileAndVerify(source, expectedOutput: "System.Collections.Generic.IEnumerable`1[System.Int32]");
comp.VerifyDiagnostics();
comp.VerifyIL("Test.Main", @"
{
// Code size 25 (0x19)
.maxstack 2
.locals init (int[] V_0, //a
System.Collections.Generic.IEnumerable<int> V_1)
IL_0000: ldc.i4.0
IL_0001: newarr ""int""
IL_0006: stloc.0
IL_0007: newobj ""System.Collections.Generic.List<int>..ctor()""
IL_000c: stloc.1
IL_000d: ldloc.1
IL_000e: dup
IL_000f: brtrue.s IL_0013
IL_0011: pop
IL_0012: ldloc.0
IL_0013: call ""void Test.Goo<System.Collections.Generic.IEnumerable<int>>(System.Collections.Generic.IEnumerable<int>)""
IL_0018: ret
}");
}
[Fact]
public void TestNullCoalesce_InterfaceRegression1b()
{
var source = @"
using System.Collections.Generic;
public class Test
{
static void Main()
{
int[] a = new int[] { };
IEnumerable<int> b;
IEnumerable<int> c = (b = (IEnumerable<int>)new List<int>()) ?? a;
Goo(c);
Goo(b);
}
static void Goo<T>(T x)
{
System.Console.Write(typeof(T));
}
}";
var comp = CompileAndVerify(source, expectedOutput: "System.Collections.Generic.IEnumerable`1[System.Int32]System.Collections.Generic.IEnumerable`1[System.Int32]");
comp.VerifyDiagnostics();
comp.VerifyIL("Test.Main", @"
{
// Code size 31 (0x1f)
.maxstack 3
.locals init (int[] V_0, //a
System.Collections.Generic.IEnumerable<int> V_1)
IL_0000: ldc.i4.0
IL_0001: newarr ""int""
IL_0006: stloc.0
IL_0007: newobj ""System.Collections.Generic.List<int>..ctor()""
IL_000c: dup
IL_000d: stloc.1
IL_000e: ldloc.1
IL_000f: dup
IL_0010: brtrue.s IL_0014
IL_0012: pop
IL_0013: ldloc.0
IL_0014: call ""void Test.Goo<System.Collections.Generic.IEnumerable<int>>(System.Collections.Generic.IEnumerable<int>)""
IL_0019: call ""void Test.Goo<System.Collections.Generic.IEnumerable<int>>(System.Collections.Generic.IEnumerable<int>)""
IL_001e: ret
}");
}
[Fact]
public void TestNullCoalesce_InterfaceRegression1c()
{
var source = @"
using System.Collections.Generic;
public class Test
{
static void Main()
{
int[] a = new int[] { };
IEnumerable<int> b = new List<int>();
Goo(b, b ?? a);
}
static void Goo<T, U>(T x, U y)
{
System.Console.Write(typeof(T));
}
}";
var comp = CompileAndVerify(source, expectedOutput: "System.Collections.Generic.IEnumerable`1[System.Int32]");
comp.VerifyDiagnostics();
comp.VerifyIL("Test.Main", @"
{
// Code size 26 (0x1a)
.maxstack 3
.locals init (int[] V_0, //a
System.Collections.Generic.IEnumerable<int> V_1)
IL_0000: ldc.i4.0
IL_0001: newarr ""int""
IL_0006: stloc.0
IL_0007: newobj ""System.Collections.Generic.List<int>..ctor()""
IL_000c: dup
IL_000d: stloc.1
IL_000e: ldloc.1
IL_000f: dup
IL_0010: brtrue.s IL_0014
IL_0012: pop
IL_0013: ldloc.0
IL_0014: call ""void Test.Goo<System.Collections.Generic.IEnumerable<int>, System.Collections.Generic.IEnumerable<int>>(System.Collections.Generic.IEnumerable<int>, System.Collections.Generic.IEnumerable<int>)""
IL_0019: ret
}
");
}
/// <summary>
/// From whidbey bug #49619. PEVerify fails.
/// </summary>
/// <remarks>
/// Dev10 does not produce verifiable code for this example.
/// </remarks>
[Fact]
public void TestNullCoalesce_InterfaceRegression2()
{
var source = @"
public interface IA { }
public interface IB { int f(); }
public class AB1 : IA, IB { public int f() { return 42; } }
public class AB2 : IA, IB { public int f() { return 1; } }
class MainClass
{
public static void g(AB1 ab1)
{
((IB)ab1 ?? (IB)new AB2()).f();
}
}";
// Note the explicit casts, even though the conversions are
// implicit reference conversions.
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("MainClass.g", @"
{
// Code size 19 (0x13)
.maxstack 2
.locals init (IB V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: dup
IL_0004: brtrue.s IL_000c
IL_0006: pop
IL_0007: newobj ""AB2..ctor()""
IL_000c: callvirt ""int IB.f()""
IL_0011: pop
IL_0012: ret
}");
}
[Fact, WorkItem(638289, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/638289")]
public void TestNullCoalesce_Nested()
{
var src =
@"interface I { void DoNothing(); }
class A : I { public void DoNothing() {} }
class B : I { public void DoNothing() {} }
class C : I
{
public void DoNothing() {}
static I Tester(A a, B b)
{
I i = a ?? (b ?? (I)new C());
i.DoNothing();
i = a ?? ((I)b ?? new C());
i.DoNothing();
i = ((I)a ?? b) ?? new C();
i.DoNothing();
return i;
}
static void Main()
{
System.Console.Write(Tester(null, null).GetType());
}
}";
var verify = CompileAndVerify(src,
options: TestOptions.DebugExe, expectedOutput: "C");
verify.VerifyIL("C.Tester", @"
{
// Code size 86 (0x56)
.maxstack 2
.locals init (I V_0, //i
I V_1,
I V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.1
IL_0003: ldloc.1
IL_0004: dup
IL_0005: brtrue.s IL_0014
IL_0007: pop
IL_0008: ldarg.1
IL_0009: stloc.1
IL_000a: ldloc.1
IL_000b: dup
IL_000c: brtrue.s IL_0014
IL_000e: pop
IL_000f: newobj ""C..ctor()""
IL_0014: stloc.0
IL_0015: ldloc.0
IL_0016: callvirt ""void I.DoNothing()""
IL_001b: nop
IL_001c: ldarg.0
IL_001d: stloc.1
IL_001e: ldloc.1
IL_001f: dup
IL_0020: brtrue.s IL_002f
IL_0022: pop
IL_0023: ldarg.1
IL_0024: stloc.1
IL_0025: ldloc.1
IL_0026: dup
IL_0027: brtrue.s IL_002f
IL_0029: pop
IL_002a: newobj ""C..ctor()""
IL_002f: stloc.0
IL_0030: ldloc.0
IL_0031: callvirt ""void I.DoNothing()""
IL_0036: nop
IL_0037: ldarg.0
IL_0038: stloc.1
IL_0039: ldloc.1
IL_003a: dup
IL_003b: brtrue.s IL_003f
IL_003d: pop
IL_003e: ldarg.1
IL_003f: dup
IL_0040: brtrue.s IL_0048
IL_0042: pop
IL_0043: newobj ""C..ctor()""
IL_0048: stloc.0
IL_0049: ldloc.0
IL_004a: callvirt ""void I.DoNothing()""
IL_004f: nop
IL_0050: ldloc.0
IL_0051: stloc.2
IL_0052: br.s IL_0054
IL_0054: ldloc.2
IL_0055: ret
}");
// Optimized
verify = CompileAndVerify(src, expectedOutput: "C");
verify.VerifyIL("C.Tester", @"
{
// Code size 72 (0x48)
.maxstack 2
.locals init (I V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: dup
IL_0004: brtrue.s IL_0013
IL_0006: pop
IL_0007: ldarg.1
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: dup
IL_000b: brtrue.s IL_0013
IL_000d: pop
IL_000e: newobj ""C..ctor()""
IL_0013: callvirt ""void I.DoNothing()""
IL_0018: ldarg.0
IL_0019: stloc.0
IL_001a: ldloc.0
IL_001b: dup
IL_001c: brtrue.s IL_002b
IL_001e: pop
IL_001f: ldarg.1
IL_0020: stloc.0
IL_0021: ldloc.0
IL_0022: dup
IL_0023: brtrue.s IL_002b
IL_0025: pop
IL_0026: newobj ""C..ctor()""
IL_002b: callvirt ""void I.DoNothing()""
IL_0030: ldarg.0
IL_0031: stloc.0
IL_0032: ldloc.0
IL_0033: dup
IL_0034: brtrue.s IL_0038
IL_0036: pop
IL_0037: ldarg.1
IL_0038: dup
IL_0039: brtrue.s IL_0041
IL_003b: pop
IL_003c: newobj ""C..ctor()""
IL_0041: dup
IL_0042: callvirt ""void I.DoNothing()""
IL_0047: ret
}");
}
[Fact]
public void TestNullCoalesce_FuncVariance()
{
var source = @"
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
Func<Exception[]> f1 = null;
Func<IEnumerable<object>> f2 = null;
var oo = f1 ?? f2;
Console.WriteLine(oo);
oo = f2 ?? f1;
Console.WriteLine(oo);
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"
{
// Code size 31 (0x1f)
.maxstack 2
.locals init (System.Func<System.Exception[]> V_0, //f1
System.Func<System.Collections.Generic.IEnumerable<object>> V_1, //f2
System.Func<System.Collections.Generic.IEnumerable<object>> V_2)
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldnull
IL_0003: stloc.1
IL_0004: ldloc.0
IL_0005: stloc.2
IL_0006: ldloc.2
IL_0007: dup
IL_0008: brtrue.s IL_000c
IL_000a: pop
IL_000b: ldloc.1
IL_000c: call ""void System.Console.WriteLine(object)""
IL_0011: ldloc.1
IL_0012: dup
IL_0013: brtrue.s IL_0019
IL_0015: pop
IL_0016: ldloc.0
IL_0017: stloc.2
IL_0018: ldloc.2
IL_0019: call ""void System.Console.WriteLine(object)""
IL_001e: ret
}
");
}
[Fact]
public void TestNullCoalesce_FuncVariance01()
{
var source = @"
using System;
using System.Collections;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
Func<Exception[]> f1 = null;
Func<IEnumerable<object>> f2 = null;
var oo = (Func<IEnumerable>)f1 ?? (Func<IEnumerable>)f2;
Console.WriteLine(oo);
oo = (Func<IEnumerable>)f2 ?? (Func<IEnumerable>)f1;
Console.WriteLine(oo);
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"
{
// Code size 35 (0x23)
.maxstack 2
.locals init (System.Func<System.Exception[]> V_0, //f1
System.Func<System.Collections.Generic.IEnumerable<object>> V_1, //f2
System.Func<System.Collections.IEnumerable> V_2)
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldnull
IL_0003: stloc.1
IL_0004: ldloc.0
IL_0005: stloc.2
IL_0006: ldloc.2
IL_0007: dup
IL_0008: brtrue.s IL_000e
IL_000a: pop
IL_000b: ldloc.1
IL_000c: stloc.2
IL_000d: ldloc.2
IL_000e: call ""void System.Console.WriteLine(object)""
IL_0013: ldloc.1
IL_0014: stloc.2
IL_0015: ldloc.2
IL_0016: dup
IL_0017: brtrue.s IL_001d
IL_0019: pop
IL_001a: ldloc.0
IL_001b: stloc.2
IL_001c: ldloc.2
IL_001d: call ""void System.Console.WriteLine(object)""
IL_0022: ret
}
");
}
[Fact]
public void TestNullCoalesce_InterfaceVariance()
{
var source = @"
using System;
using System.Collections.Generic;
class Program
{
interface CoInter<out T>
{
}
static void Main(string[] args)
{
CoInter<Exception[]> f1 = null;
CoInter<IEnumerable<object>> f2 = null;
var oo = f1 ?? f2;
Console.WriteLine(oo);
oo = f2 ?? f1;
Console.WriteLine(oo);
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"
{
// Code size 31 (0x1f)
.maxstack 2
.locals init (Program.CoInter<System.Exception[]> V_0, //f1
Program.CoInter<System.Collections.Generic.IEnumerable<object>> V_1, //f2
Program.CoInter<System.Collections.Generic.IEnumerable<object>> V_2)
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldnull
IL_0003: stloc.1
IL_0004: ldloc.0
IL_0005: stloc.2
IL_0006: ldloc.2
IL_0007: dup
IL_0008: brtrue.s IL_000c
IL_000a: pop
IL_000b: ldloc.1
IL_000c: call ""void System.Console.WriteLine(object)""
IL_0011: ldloc.1
IL_0012: dup
IL_0013: brtrue.s IL_0019
IL_0015: pop
IL_0016: ldloc.0
IL_0017: stloc.2
IL_0018: ldloc.2
IL_0019: call ""void System.Console.WriteLine(object)""
IL_001e: ret
}
");
}
[Fact]
public void TestNullCoalesce_InterfaceVariance01()
{
var source = @"
using System;
using System.Collections;
using System.Collections.Generic;
class Program
{
interface CoInter<out T>
{
}
static void Main(string[] args)
{
CoInter<Exception[]> f1 = null;
CoInter<IEnumerable<object>> f2 = null;
var oo = (CoInter<IEnumerable>)f1 ?? (CoInter<IEnumerable>)f2;
Console.WriteLine(oo);
oo = (CoInter<IEnumerable>)f2 ?? (CoInter<IEnumerable>)f1;
Console.WriteLine(oo);
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"
{
// Code size 35 (0x23)
.maxstack 2
.locals init (Program.CoInter<System.Exception[]> V_0, //f1
Program.CoInter<System.Collections.Generic.IEnumerable<object>> V_1, //f2
Program.CoInter<System.Collections.IEnumerable> V_2)
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldnull
IL_0003: stloc.1
IL_0004: ldloc.0
IL_0005: stloc.2
IL_0006: ldloc.2
IL_0007: dup
IL_0008: brtrue.s IL_000e
IL_000a: pop
IL_000b: ldloc.1
IL_000c: stloc.2
IL_000d: ldloc.2
IL_000e: call ""void System.Console.WriteLine(object)""
IL_0013: ldloc.1
IL_0014: stloc.2
IL_0015: ldloc.2
IL_0016: dup
IL_0017: brtrue.s IL_001d
IL_0019: pop
IL_001a: ldloc.0
IL_001b: stloc.2
IL_001c: ldloc.2
IL_001d: call ""void System.Console.WriteLine(object)""
IL_0022: ret
}
");
}
[WorkItem(543074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543074")]
[Fact]
public void TestEqualEqualOnNestedStructGuid()
{
var source = @"
using System;
public class Parent
{
public System.Guid Goo(int d = 0, System.Guid g = default(System.Guid)) { return g; }
}
public class Test
{
public static void Main()
{
var x = new Parent().Goo();
var ret = x == default(System.Guid);
Console.Write(ret);
}
}
";
CompileAndVerify(source, expectedOutput: "True");
}
[WorkItem(543092, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543092")]
[Fact]
public void ShortCircuitConditionalOperator()
{
var source = @"
using System;
using System.Linq;
using System.Collections.Generic;
class X
{
public int selectCount = 0;
public bool Select<T>(Func<int, T> selector)
{
selectCount++;
return true;
}
}
class P
{
static int Main()
{
int errCount = 0;
var src = new X();
// QE is not 'executed'
var b = false && from x in src select x;
if (src.selectCount == 1)
errCount++;
Console.Write(errCount);
return (errCount > 0) ? 1 : 0;
}
}";
CompileAndVerify(source, expectedOutput: "0", options: TestOptions.ReleaseExe.WithWarningLevel(5)).VerifyDiagnostics(
// (3,1): hidden CS8019: Unnecessary using directive.
// using System.Linq;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Linq;").WithLocation(3, 1),
// (4,1): hidden CS8019: Unnecessary using directive.
// using System.Collections.Generic;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections.Generic;").WithLocation(4, 1),
// (23,26): warning CS8848: Operator 'from' cannot be used here due to precedence. Use parentheses to disambiguate.
// var b = false && from x in src select x;
Diagnostic(ErrorCode.WRN_PrecedenceInversion, "from x in src").WithArguments("from").WithLocation(23, 26)
);
}
[WorkItem(543109, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543109")]
[Fact()]
public void ShortCircuitConditionalOperator02()
{
var source = @"
using System;
class P
{
static int Main()
{
int errCount = 0;
var f = false;
var b = f && (0 == errCount++);
Console.Write(errCount);
return (errCount > 0) ? 1 : 0;
}
}";
CompileAndVerify(source, expectedOutput: "0");
}
[WorkItem(543377, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543377")]
[Fact]
public void DecimalComparison()
{
var source = @"
class Program
{
static void Main()
{
decimal d1 = 1.0201m;
if (d1 == 10201M)
{
}
}
}";
CompileAndVerify(source).
VerifyIL("Program.Main", @"
{
// Code size 31 (0x1f)
.maxstack 5
IL_0000: ldc.i4 0x27d9
IL_0005: ldc.i4.0
IL_0006: ldc.i4.0
IL_0007: ldc.i4.0
IL_0008: ldc.i4.4
IL_0009: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_000e: ldc.i4 0x27d9
IL_0013: newobj ""decimal..ctor(int)""
IL_0018: call ""bool decimal.op_Equality(decimal, decimal)""
IL_001d: pop
IL_001e: ret
}");
}
[WorkItem(543453, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543453")]
[Fact]
public void TestIncrementDecrementOperator_Generic()
{
var source = @"
using System;
class BaseType<T> where T : BaseType<T>, new()
{
public static T operator ++(BaseType<T> x)
{
return null;
}
public static implicit operator T(BaseType<T> x)
{
return null;
}
}
class DrivedType : BaseType<DrivedType>
{
public static void Main()
{
BaseType<DrivedType> test = new BaseType<DrivedType>();
DrivedType test2 = test++;
}
}
";
CompileAndVerify(source);
}
[WorkItem(543474, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543474")]
[Fact]
public void LogicalComplementOperator()
{
var source = @"
class Program
{
static void Main(string[] args)
{
checked
{
var b = false;
if (!b) {System.Console.Write(""1""); }
}
}
}";
CompileAndVerify(source,
expectedOutput: "1");
}
[WorkItem(543500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543500")]
[Fact]
public void BuiltInLeftShiftOperators()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
int i = 1;
uint ui = 1;
long l = 1;
ulong ul = 1;
Console.WriteLine(i << 31);
Console.WriteLine(i << 32);
Console.WriteLine(i << 33);
Console.WriteLine(i << -1);
Console.WriteLine();
Console.WriteLine(ui << 31);
Console.WriteLine(ui << 32);
Console.WriteLine(ui << 33);
Console.WriteLine(ui << -1);
Console.WriteLine();
Console.WriteLine(l << 63);
Console.WriteLine(l << 64);
Console.WriteLine(l << 65);
Console.WriteLine(l << -1);
Console.WriteLine();
Console.WriteLine(ul << 63);
Console.WriteLine(ul << 64);
Console.WriteLine(ul << 65);
Console.WriteLine(ul << -1);
Console.WriteLine();
}
}";
CompileAndVerify(source,
expectedOutput: @"
-2147483648
1
2
-2147483648
2147483648
1
2
2147483648
-9223372036854775808
1
2
-9223372036854775808
9223372036854775808
1
2
9223372036854775808
");
}
[WorkItem(543500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543500")]
[Fact]
public void BuiltInRightShiftOperators()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
int i = int.MaxValue;
uint ui = uint.MaxValue;
long l = long.MaxValue;
ulong ul = ulong.MaxValue;
Console.WriteLine(i >> 31);
Console.WriteLine(i >> 32);
Console.WriteLine(i >> 33);
Console.WriteLine(i >> -1);
Console.WriteLine();
Console.WriteLine(ui >> 31);
Console.WriteLine(ui >> 32);
Console.WriteLine(ui >> 33);
Console.WriteLine(ui >> -1);
Console.WriteLine();
Console.WriteLine(l >> 63);
Console.WriteLine(l >> 64);
Console.WriteLine(l >> 65);
Console.WriteLine(l >> -1);
Console.WriteLine();
Console.WriteLine(ul >> 63);
Console.WriteLine(ul >> 64);
Console.WriteLine(ul >> 65);
Console.WriteLine(ul >> -1);
Console.WriteLine();
}
}";
CompileAndVerify(source,
expectedOutput: @"
0
2147483647
1073741823
0
1
4294967295
2147483647
1
0
9223372036854775807
4611686018427387903
0
1
18446744073709551615
9223372036854775807
1
");
}
[WorkItem(543500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543500")]
[Fact]
public void BuiltInShiftOperators()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
int i = 1;
long l = long.MaxValue;
int amount = 1;
Console.WriteLine(i << 31); // 31
Console.WriteLine(i << 32); // no shift
Console.WriteLine(i << 33); // 1
Console.WriteLine(i << -1); // 31
Console.WriteLine(i >> amount); // & 31
Console.WriteLine();
Console.WriteLine(l >> 63); // 63
Console.WriteLine(l >> 64); // no shift
Console.WriteLine(l >> 65); // 1
Console.WriteLine(l >> -1); // 63
Console.WriteLine(l >> amount); // & 63
Console.WriteLine();
}
}";
var verifier = CompileAndVerify(source,
expectedOutput: @"
-2147483648
1
2
-2147483648
0
0
9223372036854775807
4611686018427387903
0
4611686018427387903
");
verifier.VerifyIL("Program.Main", @"
{
// Code size 109 (0x6d)
.maxstack 3
.locals init (long V_0, //l
int V_1) //amount
IL_0000: ldc.i4.1
IL_0001: ldc.i8 0x7fffffffffffffff
IL_000a: stloc.0
IL_000b: ldc.i4.1
IL_000c: stloc.1
IL_000d: dup
IL_000e: ldc.i4.s 31
IL_0010: shl
IL_0011: call ""void System.Console.WriteLine(int)""
IL_0016: dup
IL_0017: call ""void System.Console.WriteLine(int)""
IL_001c: dup
IL_001d: ldc.i4.1
IL_001e: shl
IL_001f: call ""void System.Console.WriteLine(int)""
IL_0024: dup
IL_0025: ldc.i4.s 31
IL_0027: shl
IL_0028: call ""void System.Console.WriteLine(int)""
IL_002d: ldloc.1
IL_002e: ldc.i4.s 31
IL_0030: and
IL_0031: shr
IL_0032: call ""void System.Console.WriteLine(int)""
IL_0037: call ""void System.Console.WriteLine()""
IL_003c: ldloc.0
IL_003d: ldc.i4.s 63
IL_003f: shr
IL_0040: call ""void System.Console.WriteLine(long)""
IL_0045: ldloc.0
IL_0046: call ""void System.Console.WriteLine(long)""
IL_004b: ldloc.0
IL_004c: ldc.i4.1
IL_004d: shr
IL_004e: call ""void System.Console.WriteLine(long)""
IL_0053: ldloc.0
IL_0054: ldc.i4.s 63
IL_0056: shr
IL_0057: call ""void System.Console.WriteLine(long)""
IL_005c: ldloc.0
IL_005d: ldloc.1
IL_005e: ldc.i4.s 63
IL_0060: and
IL_0061: shr
IL_0062: call ""void System.Console.WriteLine(long)""
IL_0067: call ""void System.Console.WriteLine()""
IL_006c: ret
}
");
}
[Fact, WorkItem(543993, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543993")]
public void BuiltInShiftOperators01()
{
var source = @"
using System;
public class Test
{
public static void Main()
{
int n = 2;
int v1 = (1 << n) << 3;
int v2 = 1 << n << 3;
Console.Write(""{0}=={1} "", v1, v2);
v1 = (1 >> n) >> 3;
v2 = 1 >> n >> 3;
Console.Write(""{0}=={1}"", v1, v2);
}
}
";
var verifier = CompileAndVerify(source,
expectedOutput: @"32==32 0==0");
verifier.VerifyIL("Test.Main", @"
{
// Code size 83 (0x53)
.maxstack 3
.locals init (int V_0, //n
int V_1, //v1
int V_2) //v2
IL_0000: ldc.i4.2
IL_0001: stloc.0
IL_0002: ldc.i4.1
IL_0003: ldloc.0
IL_0004: ldc.i4.s 31
IL_0006: and
IL_0007: shl
IL_0008: ldc.i4.3
IL_0009: shl
IL_000a: stloc.1
IL_000b: ldc.i4.1
IL_000c: ldloc.0
IL_000d: ldc.i4.s 31
IL_000f: and
IL_0010: shl
IL_0011: ldc.i4.3
IL_0012: shl
IL_0013: stloc.2
IL_0014: ldstr ""{0}=={1} ""
IL_0019: ldloc.1
IL_001a: box ""int""
IL_001f: ldloc.2
IL_0020: box ""int""
IL_0025: call ""void System.Console.Write(string, object, object)""
IL_002a: ldc.i4.1
IL_002b: ldloc.0
IL_002c: ldc.i4.s 31
IL_002e: and
IL_002f: shr
IL_0030: ldc.i4.3
IL_0031: shr
IL_0032: stloc.1
IL_0033: ldc.i4.1
IL_0034: ldloc.0
IL_0035: ldc.i4.s 31
IL_0037: and
IL_0038: shr
IL_0039: ldc.i4.3
IL_003a: shr
IL_003b: stloc.2
IL_003c: ldstr ""{0}=={1}""
IL_0041: ldloc.1
IL_0042: box ""int""
IL_0047: ldloc.2
IL_0048: box ""int""
IL_004d: call ""void System.Console.Write(string, object, object)""
IL_0052: ret
}
");
}
[Fact, WorkItem(543993, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543993")]
public void BuiltInShiftOperators02()
{
var source = @"
class Program
{
static void Main()
{
System.Console.WriteLine(1 << 2 << 3);
System.Console.WriteLine((1 << 2) << 3);
System.Console.WriteLine(1 << (2 << 3));
}
}
";
CompileAndVerify(source, expectedOutput: @"
32
32
65536");
}
[WorkItem(543568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543568")]
[Fact]
public void ImplicitConversionOperatorWithOptionalParam()
{
var source = @"
using System;
public class C
{
static public implicit operator int(C d = null) // warning CS1066
{
if (d != null) return 0;
return 1;
}
}
class TestFunction
{
public static void Main()
{
var tf = new C();
int result = tf;
Console.Write(result);
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"0");
}
[WorkItem(543569, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543569")]
[Fact()]
public void AssignmentInOperandOfIsAlwaysFalse()
{
var source = @"
using System;
public class Program
{
public static void Main()
{
int[] a = null;
bool result = (a = new[] { 4, 5, 6 }) is char[]; // warning CS0184
if (a == null)
{
Console.WriteLine(""FAIL"");
}
else
{
Console.WriteLine(""PASS"");
}
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"PASS");
}
[WorkItem(543577, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543577")]
[Fact()]
public void IsOperatorAlwaysFalseInLambda()
{
var source = @"
using System;
class C
{
static int counter = 0;
public static void Increment()
{
counter++;
}
public static void Main()
{
Func<bool> testExpr = () => Increment() is object; // warning CS0184
Console.WriteLine(counter);
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"0");
}
[WorkItem(543446, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543446"), WorkItem(543446, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543446")]
[Fact]
public void ThrowExceptionByConversion()
{
var source = @"using System;
namespace Test
{
class DException : Exception
{
public static implicit operator DException(Action d)
{
return new DException();
}
}
class Program
{
static void M() { }
static void Main()
{
try
{
throw (DException) M;
}
catch (DException)
{
Console.Write(0);
}
Console.Write(1);
}
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"01");
}
[WorkItem(543586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543586")]
[Fact]
public void ImplicitVsExplicitOverloadOperators()
{
var source = @"using System;
class Test
{
static void Main()
{
Str str = (Str)1;
Console.WriteLine(str.num);
}
}
struct Str
{
public int num;
public static explicit operator Str(int i)
{
Str temp;
temp.num = 10;
return temp;
}
public static implicit operator Str(double i)
{
Str temp;
temp.num = 100;
return temp;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"10");
}
[WorkItem(543602, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543602")]
[WorkItem(543660, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543660")]
[Fact]
public void SwitchExpressionWithImplicitConversion()
{
var source = @"using System;
public class Test
{
public static implicit operator int(Test val)
{
return 1;
}
public static implicit operator float(Test val)
{
return 2.1f;
}
public static int Main()
{
Test t = new Test();
switch (t)
{
case 1:
Console.WriteLine(0);
return 0;
default:
Console.WriteLine(1);
return 1;
}
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"0");
}
[WorkItem(543498, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543498")]
[Fact]
public void UserDefinedConversionAfterUserDefinedIncrement()
{
var source =
@"using System;
class A
{
public static C operator ++(A x)
{
Console.Write('3');
return new C();
}
}
class C : A
{
public static implicit operator B(C x)
{
Console.Write('4');
return new B();
}
}
class B : A
{
static void Main()
{
Console.Write('1');
B b = new B();
Console.Write('2');
b++;
Console.Write('5');
}
}";
CompileAndVerify(source, expectedOutput: "12345");
}
[Fact]
public void TestXor()
{
var source = @"
using System;
class Program
{
static bool t() { return true; }
static bool f() { return false; }
static void write(bool b) { Console.WriteLine(b); }
static void Main(string[] args)
{
write(t() ^ t());
write(t() ^ f());
write(f() ^ t());
write(f() ^ f());
Console.WriteLine(""---"");
write(!(t() ^ t()));
write(!(t() ^ f()));
write(!(f() ^ t()));
write(!(f() ^ f()));
Console.WriteLine(""---"");
write((t() ^ t()) || (t() ^ f()));
write((t() ^ f()) || (t() ^ t()));
write((f() ^ t()) || (f() ^ f()));
write((f() ^ f()) || (t() ^ t()));
Console.WriteLine(""---"");
write((t() ^ t()) && (t() ^ f()));
write((t() ^ f()) && (t() ^ t()));
write((f() ^ t()) && (f() ^ f()));
write((f() ^ f()) && (f() ^ t()));
Console.WriteLine(""---"");
write((t() ^ t()) || !(t() ^ f()));
write((t() ^ f()) || !(t() ^ t()));
write(!(f() ^ t()) || (f() ^ f()));
write(!(f() ^ f()) || (f() ^ t()));
Console.WriteLine(""---"");
write((t() ^ t()) && !(t() ^ f()));
write((t() ^ f()) && !(t() ^ t()));
write(!(f() ^ t()) && (f() ^ f()));
write(!(f() ^ f()) && (f() ^ t()));
}
}
";
string expectedOutput =
@"False
True
True
False
---
True
False
False
True
---
True
True
True
False
---
False
False
False
False
---
False
True
False
True
---
False
True
False
True
";
var compilation = CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void TestXorInIf()
{
var source = @"
using System;
class Program
{
static bool t() { return true; }
static bool f() { return false; }
static void Main(string[] args)
{
if (t() ^ t())
{
Console.WriteLine(""1"");
}
if (!(t() ^ f()))
{
Console.WriteLine(""2"");
}
if (f() ^ t())
{
Console.WriteLine(""3"");
}
if (f() ^ f())
{
Console.WriteLine(""4"");
}
if ((t() ^ f()) && (f() ^ t()))
{
Console.WriteLine(""5"");
}
if ((t() ^ t()) || (t() ^ f()))
{
Console.WriteLine(""6"");
}
if ((t() ^ t()) || (f() ^ f()))
{
Console.WriteLine(""7"");
}
}
}
";
string expectedOutput =
@"3
5
6";
var compilation = CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void XorIl()
{
var text = @"using System;
class MyClass
{
public static bool f = false, t = true;
public static bool r;
public static void Main()
{
r = f ^ t;
r = !(f ^ t);
}
}
";
var comp = CompileAndVerify(text, expectedOutput: "");
comp.VerifyIL("MyClass.Main", @"
{
// Code size 34 (0x22)
.maxstack 2
IL_0000: ldsfld ""bool MyClass.f""
IL_0005: ldsfld ""bool MyClass.t""
IL_000a: xor
IL_000b: stsfld ""bool MyClass.r""
IL_0010: ldsfld ""bool MyClass.f""
IL_0015: ldsfld ""bool MyClass.t""
IL_001a: ceq
IL_001c: stsfld ""bool MyClass.r""
IL_0021: ret
}");
}
[Fact, WorkItem(543446, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543446")]
public void UserDefinedConversionAfterUserDefinedConvert()
{
var source =
@"using System;
delegate void D(int p1);
class DException : Exception
{
public D d;
public static implicit operator DException(D d)
{
DException e = new DException();
e.d = d;
return e;
}
}
class Program
{
static void PM(int p1)
{
}
static void Main()
{
throw (DException)PM;
}
}
";
CompileAndVerify(source);
}
[Fact]
public void UserDefinedOperatorAfterUserDefinedConversion()
{
var source =
@"using System;
class Program
{
public static void Main(string[] args)
{
var c = new C();
var trash = c + c; // which +?
}
}
class C
{
public static string operator +(C c, string s)
{
Console.WriteLine(""+(C,string)"");
return ""+s"";
}
public static string operator +(C c, object o)
{
Console.WriteLine(""+(C,object)"");
return ""+o"";
}
public static implicit operator string(C c)
{
Console.WriteLine(""C->string"");
return ""C->string"";
}
public override string ToString()
{
Console.WriteLine(""C.ToString()"");
return ""C2"";
}
}";
CompileAndVerify(source, expectedOutput:
@"C->string
+(C,string)
");
}
[Fact, WorkItem(529248, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529248")]
public void TestNullCoalescingOperatorWithNullableConversions()
{
// Native compiler violates the language specification while binding the type for the null coalescing operator (??).
// The last bullet in section 7.13 of the specification for binding the type of ?? operator states that:
// SPEC: Otherwise, if b has a type B and an implicit conversion exists from a to B, the result type is B.
// SPEC: At run-time, a is first evaluated. If a is not null, a is unwrapped to type A0 (if A exists and is nullable)
// SPEC: and converted to type B, and this becomes the result. Otherwise, b is evaluated and becomes the result.
// Note that for this test there is no implicit conversion from 's' -> int (SnapshotPoint? -> int), but there is an implicit conversion
// from stripped type SnapshotPoint -> int.
// Native compiler instead implements this part based on whether A is a nullable type or not. We maintain compatibility with the native compiler:
// SPEC PROPOSAL: Otherwise, if A exists and is a nullable type and if b has a type B and an implicit conversion exists from A0 to B,
// SPEC PROPOSAL: the result type is B. At run-time, a is first evaluated. If a is not null, a is unwrapped to type A0 and converted to type B,
// SPEC PROPOSAL: and this becomes the result. 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 an implicit conversion exists from a to B,
// SPEC PROPOSAL: the result type is B. At run-time, a is first evaluated. If a is not null, a is converted to type B, and this becomes the result.
// SPEC PROPOSAL: Otherwise, b is evaluated and becomes the result.
string source = @"
struct SnapshotPoint
{
public static implicit operator int(SnapshotPoint snapshotPoint)
{
System.Console.WriteLine(""Pass"");
return 0;
}
}
class Program
{
static void Main(string[] args)
{
SnapshotPoint? s = new SnapshotPoint();
var r = s ?? -1;
SnapshotPoint? s2 = null;
r = s2 ?? -1;
}
}
";
var verifier = CompileAndVerify(source: source, expectedOutput: "Pass");
verifier.VerifyIL("Program.Main", @"
{
// Code size 70 (0x46)
.maxstack 1
.locals init (SnapshotPoint V_0,
SnapshotPoint? V_1)
IL_0000: ldloca.s V_0
IL_0002: initobj ""SnapshotPoint""
IL_0008: ldloc.0
IL_0009: newobj ""SnapshotPoint?..ctor(SnapshotPoint)""
IL_000e: stloc.1
IL_000f: ldloca.s V_1
IL_0011: call ""bool SnapshotPoint?.HasValue.get""
IL_0016: brfalse.s IL_0025
IL_0018: ldloca.s V_1
IL_001a: call ""SnapshotPoint SnapshotPoint?.GetValueOrDefault()""
IL_001f: call ""int SnapshotPoint.op_Implicit(SnapshotPoint)""
IL_0024: pop
IL_0025: ldloca.s V_1
IL_0027: initobj ""SnapshotPoint?""
IL_002d: ldloc.1
IL_002e: stloc.1
IL_002f: ldloca.s V_1
IL_0031: call ""bool SnapshotPoint?.HasValue.get""
IL_0036: brfalse.s IL_0045
IL_0038: ldloca.s V_1
IL_003a: call ""SnapshotPoint SnapshotPoint?.GetValueOrDefault()""
IL_003f: call ""int SnapshotPoint.op_Implicit(SnapshotPoint)""
IL_0044: pop
IL_0045: ret
}");
}
[Fact, WorkItem(543980, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543980")]
public void IsOperatorOnEnumAndTypeParameterConstraintToStruct()
{
string source = @"using System;
public enum E { One }
class Gen<T> where T : struct
{
public static void TestIsOperatorEnum(T t)
{
Console.WriteLine(t is Enum);
Console.WriteLine(t is E);
Console.WriteLine(t as Enum);
}
}
public class Test
{
public static void Main()
{
Gen<E>.TestIsOperatorEnum(new E());
}
}
";
string expectedOutput = @"True
True
One";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact, WorkItem(543982, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543982")]
public void OverloadAdditionOperatorOnGenericClass()
{
var source = @"
using System;
public class G<T>
{
public static G<T> operator ~(G<T> g)
{
Console.WriteLine(""G<{0}> unary negation"", typeof(T));
return new G<T>();
}
public static G<T> operator +(G<T> G1, G<T> G2)
{
Console.WriteLine(""G<{0}> binary addition"", typeof(T));
return new G<T>();
}
}
public class Gen<T, U> where T : G<U>
{
public static void TestLookupOnT(T obj, U val)
{
G<U> t = obj + ~obj;
}
}
public class Test
{
public static void Main()
{
Gen<G<int>, int>.TestLookupOnT(new G<int>(), 1);
}
}
";
string expected = @"G<System.Int32> unary negation
G<System.Int32> binary addition";
CompileAndVerify(
source: source,
expectedOutput: expected);
}
[Fact, WorkItem(544539, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544539"), WorkItem(544540, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544540")]
public void NonShortCircuitBoolean()
{
var source = @"using System;
struct Program
{
public static bool P()
{
Console.WriteLine(""P"");
return true;
}
public static void Main(string[] args)
{
bool x = true | P();
Console.WriteLine(P() & false);
}
}";
string expected = @"P
P
False";
CompileAndVerify(
source: source,
expectedOutput: expected);
}
[Fact]
public void EqualZero()
{
var text = @"
using System;
class MyClass
{
public enum E1
{
A,
B
}
public static void Main()
{
Test1((object)null, 0);
}
public static void Test1<T>(T x, E1 e) where T : class
{
if (x == null)
{
Console.WriteLine(!(x == null));
}
if (e == E1.A)
{
Console.WriteLine(!(e == E1.A));
}
}
}
";
var comp = CompileAndVerify(text, expectedOutput: @"False
False
");
comp.VerifyIL("MyClass.Test1<T>", @"
{
// Code size 35 (0x23)
.maxstack 2
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: brtrue.s IL_0016
IL_0008: ldarg.0
IL_0009: box ""T""
IL_000e: ldnull
IL_000f: cgt.un
IL_0011: call ""void System.Console.WriteLine(bool)""
IL_0016: ldarg.1
IL_0017: brtrue.s IL_0022
IL_0019: ldarg.1
IL_001a: ldc.i4.0
IL_001b: cgt.un
IL_001d: call ""void System.Console.WriteLine(bool)""
IL_0022: ret
}
");
}
[Fact]
public void EqualZeroUnoptimized()
{
var text = @"
using System;
class MyClass
{
public enum E1
{
A,
B
}
public static void Main()
{
Test1((object)null, 0);
}
public static void Test1<T>(T x, E1 e) where T : class
{
if (x == null)
{
Console.WriteLine(x == null);
}
if (e == E1.A)
{
Console.WriteLine(e == E1.A);
}
}
}
";
var comp = CompileAndVerify(text, options: TestOptions.DebugExe, expectedOutput: @"True
True
");
comp.VerifyIL("MyClass.Test1<T>", @"
{
// Code size 52 (0x34)
.maxstack 2
.locals init (bool V_0,
bool V_1)
-IL_0000: nop
-IL_0001: ldarg.0
IL_0002: box ""T""
IL_0007: ldnull
IL_0008: ceq
IL_000a: stloc.0
~IL_000b: ldloc.0
IL_000c: brfalse.s IL_001f
-IL_000e: nop
-IL_000f: ldarg.0
IL_0010: box ""T""
IL_0015: ldnull
IL_0016: ceq
IL_0018: call ""void System.Console.WriteLine(bool)""
IL_001d: nop
-IL_001e: nop
-IL_001f: ldarg.1
IL_0020: ldc.i4.0
IL_0021: ceq
IL_0023: stloc.1
~IL_0024: ldloc.1
IL_0025: brfalse.s IL_0033
-IL_0027: nop
-IL_0028: ldarg.1
IL_0029: ldc.i4.0
IL_002a: ceq
IL_002c: call ""void System.Console.WriteLine(bool)""
IL_0031: nop
-IL_0032: nop
-IL_0033: ret
}
", sequencePoints: "MyClass.Test1");
}
[WorkItem(543893, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543893")]
[Fact]
public void EnumBitwiseComplement()
{
var text = @"
public class A
{
enum E : ushort { one = 1, two = 2, four = 4 }
public static void Main()
{
checked {
E e = E.one;
e &= ~E.two;
System.Console.WriteLine(e);
}
}
}
";
var comp = CompileAndVerify(text, expectedOutput: @"one");
// Can't actually see an unchecked cast here since only constant values are emitted.
comp.VerifyIL("A.Main", @"
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldc.i4.1
IL_0001: ldc.i4 0xfffd
IL_0006: and
IL_0007: box ""A.E""
IL_000c: call ""void System.Console.WriteLine(object)""
IL_0011: ret
}
");
text = @"
public class A
{
enum E : ushort { one = 1, two = 2, four = 4 }
public static void Main()
{
checked {
E e = E.one;
int i = 5 + (int)~e;
System.Console.WriteLine(i);
}
}
}
";
comp = CompileAndVerify(text, expectedOutput: @"65539");
// Can't actually see an unchecked cast here since only constant values are emitted.
comp.VerifyIL("A.Main", @"
{
// Code size 13 (0xd)
.maxstack 2
.locals init (A.E V_0) //e
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.5
IL_0003: ldloc.0
IL_0004: not
IL_0005: conv.u2
IL_0006: add.ovf
IL_0007: call ""void System.Console.WriteLine(int)""
IL_000c: ret
}
");
}
[Fact]
public void EnumXor()
{
var text = @"
using System;
enum e : sbyte
{
x = sbyte.MinValue,
y = sbyte.MaxValue,
z = 1
}
enum e1 : byte
{
x = byte.MinValue,
y = byte.MaxValue,
z = 1
}
public static class Test
{
public static void Main()
{
TestE();
TestE1();
}
private static void TestE()
{
var x = e.x;
var y = e.y;
var z = x ^ y;
System.Console.WriteLine((int)z);
x ^= e.z;
y ^= unchecked((e)(-1));
x ^= e.z;
y ^= unchecked((e)(-1));
z = x ^ y;
System.Console.WriteLine((int)z);
}
private static void TestE1()
{
var x = e1.x;
var y = e1.y;
var z = x ^ y;
System.Console.WriteLine((int)z);
x ^= e1.z;
y ^= unchecked((e1)(-1));
x ^= e1.z;
y ^= unchecked((e1)(-1));
z = x ^ y;
System.Console.WriteLine((int)z);
}
}
";
var comp = CompileAndVerify(text, expectedOutput: @"
-1
-1
255
255
");
comp.VerifyIL("Test.TestE()", @"
{
// Code size 33 (0x21)
.maxstack 3
.locals init (e V_0) //y
IL_0000: ldc.i4.s -128
IL_0002: ldc.i4.s 127
IL_0004: stloc.0
IL_0005: dup
IL_0006: ldloc.0
IL_0007: xor
IL_0008: call ""void System.Console.WriteLine(int)""
IL_000d: ldc.i4.1
IL_000e: xor
IL_000f: ldloc.0
IL_0010: ldc.i4.m1
IL_0011: xor
IL_0012: stloc.0
IL_0013: ldc.i4.1
IL_0014: xor
IL_0015: ldloc.0
IL_0016: ldc.i4.m1
IL_0017: xor
IL_0018: stloc.0
IL_0019: ldloc.0
IL_001a: xor
IL_001b: call ""void System.Console.WriteLine(int)""
IL_0020: ret
}
");
comp.VerifyIL("Test.TestE1()", @"
{
// Code size 43 (0x2b)
.maxstack 3
.locals init (e1 V_0) //y
IL_0000: ldc.i4.0
IL_0001: ldc.i4 0xff
IL_0006: stloc.0
IL_0007: dup
IL_0008: ldloc.0
IL_0009: xor
IL_000a: call ""void System.Console.WriteLine(int)""
IL_000f: ldc.i4.1
IL_0010: xor
IL_0011: ldloc.0
IL_0012: ldc.i4 0xff
IL_0017: xor
IL_0018: stloc.0
IL_0019: ldc.i4.1
IL_001a: xor
IL_001b: ldloc.0
IL_001c: ldc.i4 0xff
IL_0021: xor
IL_0022: stloc.0
IL_0023: ldloc.0
IL_0024: xor
IL_0025: call ""void System.Console.WriteLine(int)""
IL_002a: ret
}
");
}
[WorkItem(544452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544452")]
[Fact]
public void LiftedByteEnumAddition()
{
var text =
@"using System;
public class Program
{
private static bool ThrowsException(Action action)
{
try
{
action();
return false;
}
catch(Exception)
{
return true;
}
}
private static void Test(bool b)
{
Console.Write(b ? 't' : 'f');
}
enum Color : byte { Red, Green, Blue }
static void Main()
{
Color? c = Color.Blue;
byte? b = byte.MaxValue - 1;
Color? r = 0;
Test(ThrowsException(()=>{ r = checked(c + b); }));
Test(ThrowsException(()=>{ r = checked(c.Value + b.Value); }));
Test(ThrowsException(()=>{ r = unchecked(c + b); }));
Test(ThrowsException(()=>{ r = unchecked(c.Value + b.Value); }));
}
static void M(Color c, byte b)
{
Console.WriteLine(checked(c + b));
Console.WriteLine(unchecked(c + b));
}
}";
string il = @"{
// Code size 29 (0x1d)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: add.ovf
IL_0003: conv.ovf.u1
IL_0004: box ""Program.Color""
IL_0009: call ""void System.Console.WriteLine(object)""
IL_000e: ldarg.0
IL_000f: ldarg.1
IL_0010: add
IL_0011: conv.u1
IL_0012: box ""Program.Color""
IL_0017: call ""void System.Console.WriteLine(object)""
IL_001c: ret
}";
var comp = CompileAndVerify(text, expectedOutput: @"ttff");
comp.VerifyIL("Program.M", il);
}
[WorkItem(7091, "https://github.com/dotnet/roslyn/issues/7091")]
[Fact]
public void LiftedBitwiseOr()
{
var text =
@"using System;
public class Program
{
static void Main()
{
var res = XX() | YY();
}
static bool XX()
{
Console.WriteLine (""XX"");
return true;
}
static bool? YY()
{
Console.WriteLine(""YY"");
return true;
}
}
";
var expectedOutput =
@"XX
YY";
var comp = CompileAndVerify(text, expectedOutput: expectedOutput);
string il = @"{
// Code size 13 (0xd)
.maxstack 2
.locals init (bool? V_0)
IL_0000: call ""bool Program.XX()""
IL_0005: call ""bool? Program.YY()""
IL_000a: stloc.0
IL_000b: pop
IL_000c: ret
}
";
comp.VerifyIL("Program.Main", il);
}
[WorkItem(544943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544943")]
[Fact]
public void OptimizedXor()
{
var text = @"
using System;
class C
{
void M(bool b)
{
Console.WriteLine(b ^ true);
Console.WriteLine(b ^ false);
Console.WriteLine(true ^ b);
Console.WriteLine(false ^ b);
}
}";
//NOTE: all xors optimized away
var comp = CompileAndVerify(text).VerifyIL("C.M", @"
{
// Code size 31 (0x1f)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.0
IL_0002: ceq
IL_0004: call ""void System.Console.WriteLine(bool)""
IL_0009: ldarg.1
IL_000a: call ""void System.Console.WriteLine(bool)""
IL_000f: ldarg.1
IL_0010: ldc.i4.0
IL_0011: ceq
IL_0013: call ""void System.Console.WriteLine(bool)""
IL_0018: ldarg.1
IL_0019: call ""void System.Console.WriteLine(bool)""
IL_001e: ret
}");
}
[WorkItem(544943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544943")]
[Fact]
public void XorMalformedTrue()
{
var text = @"
using System;
class C
{
static void Main()
{
byte[] x = { 0xFF };
bool[] y = { true };
Buffer.BlockCopy(x, 0, y, 0, 1);
Console.WriteLine(y[0]);
Console.WriteLine(y[0] ^ true);
}
}";
var comp = CompileAndVerify(text, expectedOutput: @"True
False");
}
[WorkItem(539398, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539398")]
[WorkItem(1043494, "DevDiv")]
[ConditionalFact(typeof(DesktopOnly))]
public void TestFloatNegativeZero()
{
var text = @"
using System;
class C
{
static void Main()
{
Console.WriteLine(+0f == -0f);
Console.WriteLine(1f / 0f);
Console.WriteLine(1f / -0f);
Console.WriteLine(-1f / 0f);
Console.WriteLine(-1f / -0f);
Console.WriteLine(1f / (1f * 0f));
Console.WriteLine(1f / (1f * -0f));
Console.WriteLine(1f / (-1f * 0f));
Console.WriteLine(1f / (-1f * -0f));
}
}";
var comp = CompileAndVerify(text, expectedOutput: @"
True
Infinity
-Infinity
-Infinity
Infinity
Infinity
-Infinity
-Infinity
Infinity");
}
[WorkItem(539398, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539398")]
[WorkItem(1043494, "DevDiv")]
[ConditionalFact(typeof(DesktopOnly))]
public void TestDoubleNegativeZero()
{
var text = @"
using System;
class C
{
static void Main()
{
Console.WriteLine(+0d == -0d);
Console.WriteLine(1d / 0d);
Console.WriteLine(1d / -0d);
Console.WriteLine(-1d / 0d);
Console.WriteLine(-1d / -0d);
Console.WriteLine(1d / (1d * 0d));
Console.WriteLine(1d / (1d * -0d));
Console.WriteLine(1d / (-1d * 0d));
Console.WriteLine(1d / (-1d * -0d));
}
}";
var comp = CompileAndVerify(text, expectedOutput: @"
True
Infinity
-Infinity
-Infinity
Infinity
Infinity
-Infinity
-Infinity
Infinity");
}
// NOTE: decimal doesn't have infinity, so we convert to double.
[WorkItem(539398, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539398")]
[WorkItem(1043494, "DevDiv")]
[ConditionalFact(typeof(DesktopOnly))]
public void TestDecimalNegativeZero()
{
var text = @"
using System;
class C
{
static void Main()
{
Console.WriteLine(+0m == -0m);
Console.WriteLine(1d / (double)(0m));
Console.WriteLine(1d / (double)(-0m));
Console.WriteLine(-1d / (double)(0m));
Console.WriteLine(-1d / (double)(-0m));
Console.WriteLine(1d / (double)(1m * 0m));
Console.WriteLine(1d / (double)(1m * -0m));
Console.WriteLine(1d / (double)(-1m * 0m));
Console.WriteLine(1d / (double)(-1m * -0m));
}
}";
var comp = CompileAndVerify(text, expectedOutput: @"
True
Infinity
-Infinity
-Infinity
Infinity
Infinity
-Infinity
-Infinity
Infinity");
}
[WorkItem(545239, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545239")]
[Fact()]
public void IncrementPropertyOfTypeParameterReturnValue()
{
var text = @"
public interface I
{
int IntPropI { get; set; }
}
struct S1 : I
{
public int x;
public int IntPropI
{
get
{
x ++;
return x;
}
set
{
x ++;
System.Console.WriteLine(x);
}
}
}
public class Test
{
public static void Main()
{
S1 s = new S1();
TestINop(s);
}
public static T Nop<T>(T t) { return t; }
public static void TestINop<T>(T t) where T : I
{
Nop(t).IntPropI++;
Nop(t).IntPropI++;
}
}
";
CompileAndVerify(text, expectedOutput: @"
2
2").VerifyIL("Test.TestINop<T>", @"
{
// Code size 73 (0x49)
.maxstack 3
.locals init (int V_0,
T V_1)
IL_0000: ldarg.0
IL_0001: call ""T Test.Nop<T>(T)""
IL_0006: stloc.1
IL_0007: ldloca.s V_1
IL_0009: dup
IL_000a: constrained. ""T""
IL_0010: callvirt ""int I.IntPropI.get""
IL_0015: stloc.0
IL_0016: ldloc.0
IL_0017: ldc.i4.1
IL_0018: add
IL_0019: constrained. ""T""
IL_001f: callvirt ""void I.IntPropI.set""
IL_0024: ldarg.0
IL_0025: call ""T Test.Nop<T>(T)""
IL_002a: stloc.1
IL_002b: ldloca.s V_1
IL_002d: dup
IL_002e: constrained. ""T""
IL_0034: callvirt ""int I.IntPropI.get""
IL_0039: stloc.0
IL_003a: ldloc.0
IL_003b: ldc.i4.1
IL_003c: add
IL_003d: constrained. ""T""
IL_0043: callvirt ""void I.IntPropI.set""
IL_0048: ret
}
");
}
[WorkItem(546750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546750")]
[Fact()]
public void IncrementStructFieldWithReceiverThis()
{
var text = @"
struct S
{
int x;
void Test()
{
x++;
}
}
";
// NOTE: don't need a ref local in this case.
CompileAndVerify(text).VerifyIL("S.Test", @"
{
// Code size 15 (0xf)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldfld ""int S.x""
IL_0007: ldc.i4.1
IL_0008: add
IL_0009: stfld ""int S.x""
IL_000e: ret
}
");
}
[Fact]
public void TestTernary_InterfaceRegression1a()
{
var source = @"
using System.Collections.Generic;
public class Test
{
private static bool C() { return true;}
static void Main()
{
int[] a = new int[] { };
IEnumerable<int> b = new List<int>();
IEnumerable<int> c = C()? b : a;
Goo(c);
}
static void Goo<T>(T x)
{
System.Console.WriteLine(typeof(T));
}
}";
var comp = CompileAndVerify(source, expectedOutput: "System.Collections.Generic.IEnumerable`1[System.Int32]");
comp.VerifyDiagnostics();
comp.VerifyIL("Test.Main", @"
{
// Code size 32 (0x20)
.maxstack 1
.locals init (int[] V_0, //a
System.Collections.Generic.IEnumerable<int> V_1, //b
System.Collections.Generic.IEnumerable<int> V_2)
IL_0000: ldc.i4.0
IL_0001: newarr ""int""
IL_0006: stloc.0
IL_0007: newobj ""System.Collections.Generic.List<int>..ctor()""
IL_000c: stloc.1
IL_000d: call ""bool Test.C()""
IL_0012: brtrue.s IL_0019
IL_0014: ldloc.0
IL_0015: stloc.2
IL_0016: ldloc.2
IL_0017: br.s IL_001a
IL_0019: ldloc.1
IL_001a: call ""void Test.Goo<System.Collections.Generic.IEnumerable<int>>(System.Collections.Generic.IEnumerable<int>)""
IL_001f: ret
}");
}
[Fact]
public void TestTernary_InterfaceRegression1b()
{
var source = @"
using System.Collections.Generic;
public class Test
{
private static bool C() { return true;}
static void Main()
{
int[] a = new int[] { };
IEnumerable<int> b = null;
IEnumerable<int> c = C()? (b = (IEnumerable<int>)new List<int>()) : a;
Goo(c);
Goo(b);
}
static void Goo<T>(T x)
{
System.Console.Write(typeof(T));
}
}";
var comp = CompileAndVerify(source, expectedOutput: "System.Collections.Generic.IEnumerable`1[System.Int32]System.Collections.Generic.IEnumerable`1[System.Int32]");
comp.VerifyDiagnostics();
comp.VerifyIL("Test.Main", @"
{
// Code size 42 (0x2a)
.maxstack 2
.locals init (int[] V_0, //a
System.Collections.Generic.IEnumerable<int> V_1, //b
System.Collections.Generic.IEnumerable<int> V_2)
IL_0000: ldc.i4.0
IL_0001: newarr ""int""
IL_0006: stloc.0
IL_0007: ldnull
IL_0008: stloc.1
IL_0009: call ""bool Test.C()""
IL_000e: brtrue.s IL_0015
IL_0010: ldloc.0
IL_0011: stloc.2
IL_0012: ldloc.2
IL_0013: br.s IL_001e
IL_0015: newobj ""System.Collections.Generic.List<int>..ctor()""
IL_001a: dup
IL_001b: stloc.1
IL_001c: stloc.2
IL_001d: ldloc.2
IL_001e: call ""void Test.Goo<System.Collections.Generic.IEnumerable<int>>(System.Collections.Generic.IEnumerable<int>)""
IL_0023: ldloc.1
IL_0024: call ""void Test.Goo<System.Collections.Generic.IEnumerable<int>>(System.Collections.Generic.IEnumerable<int>)""
IL_0029: ret
}");
}
[Fact]
public void TestTernary_InterfaceRegression1c()
{
var source = @"
using System.Collections.Generic;
public class Test
{
static void Main()
{
int[] a = new int[] { };
IEnumerable<int> b = new List<int>();
Goo(b, b != null ? b : a);
}
static void Goo<T, U>(T x, U y)
{
System.Console.Write(typeof(T));
}
}";
var comp = CompileAndVerify(source, expectedOutput: "System.Collections.Generic.IEnumerable`1[System.Int32]");
comp.VerifyDiagnostics();
comp.VerifyIL("Test.Main", @"
{
// Code size 29 (0x1d)
.maxstack 2
.locals init (int[] V_0, //a
System.Collections.Generic.IEnumerable<int> V_1, //b
System.Collections.Generic.IEnumerable<int> V_2)
IL_0000: ldc.i4.0
IL_0001: newarr ""int""
IL_0006: stloc.0
IL_0007: newobj ""System.Collections.Generic.List<int>..ctor()""
IL_000c: stloc.1
IL_000d: ldloc.1
IL_000e: ldloc.1
IL_000f: brtrue.s IL_0016
IL_0011: ldloc.0
IL_0012: stloc.2
IL_0013: ldloc.2
IL_0014: br.s IL_0017
IL_0016: ldloc.1
IL_0017: call ""void Test.Goo<System.Collections.Generic.IEnumerable<int>, System.Collections.Generic.IEnumerable<int>>(System.Collections.Generic.IEnumerable<int>, System.Collections.Generic.IEnumerable<int>)""
IL_001c: ret
}
");
}
[Fact]
public void TestTernary_InterfaceRegression2()
{
var source = @"
public interface IA { }
public interface IB { int f(); }
public class AB1 : IA, IB { public int f() { return 42; } }
public class AB2 : IA, IB { public int f() { return 1; } }
class MainClass
{
private static bool C() { return true;}
public static void g(AB1 ab1)
{
(C()? (IB)ab1 : (IB)new AB2()).f();
}
}";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("MainClass.g", @"
{
// Code size 26 (0x1a)
.maxstack 1
.locals init (IB V_0)
IL_0000: call ""bool MainClass.C()""
IL_0005: brtrue.s IL_0010
IL_0007: newobj ""AB2..ctor()""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: br.s IL_0013
IL_0010: ldarg.0
IL_0011: stloc.0
IL_0012: ldloc.0
IL_0013: callvirt ""int IB.f()""
IL_0018: pop
IL_0019: ret
}");
}
[Fact]
public void TestTernary_FuncVariance()
{
var source = @"
using System;
using System.Collections.Generic;
class Program
{
private static bool C() { return true;}
static void Main(string[] args)
{
Func<Exception[]> f1 = null;
Func<IEnumerable<object>> f2 = null;
var oo = C()? f1 : f2;
Console.WriteLine(oo);
oo = C()? f2 : f1;
Console.WriteLine(oo);
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"
{
// Code size 41 (0x29)
.maxstack 1
.locals init (System.Func<System.Exception[]> V_0, //f1
System.Func<System.Collections.Generic.IEnumerable<object>> V_1, //f2
System.Func<System.Collections.Generic.IEnumerable<object>> V_2)
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldnull
IL_0003: stloc.1
IL_0004: call ""bool Program.C()""
IL_0009: brtrue.s IL_000e
IL_000b: ldloc.1
IL_000c: br.s IL_0011
IL_000e: ldloc.0
IL_000f: stloc.2
IL_0010: ldloc.2
IL_0011: call ""void System.Console.WriteLine(object)""
IL_0016: call ""bool Program.C()""
IL_001b: brtrue.s IL_0022
IL_001d: ldloc.0
IL_001e: stloc.2
IL_001f: ldloc.2
IL_0020: br.s IL_0023
IL_0022: ldloc.1
IL_0023: call ""void System.Console.WriteLine(object)""
IL_0028: ret
}
");
}
[Fact]
public void TestTernary_FuncVariance01()
{
var source = @"
using System;
using System.Collections;
using System.Collections.Generic;
class Program
{
private static bool C() { return true;}
static void Main(string[] args)
{
Func<Exception[]> f1 = null;
Func<IEnumerable<object>> f2 = null;
var oo = C()? (Func<IEnumerable>)f1 : (Func<IEnumerable>)f2;
Console.WriteLine(oo);
oo = C()? (Func<IEnumerable>)f2 : (Func<IEnumerable>)f1;
Console.WriteLine(oo);
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"
{
// Code size 45 (0x2d)
.maxstack 1
.locals init (System.Func<System.Exception[]> V_0, //f1
System.Func<System.Collections.Generic.IEnumerable<object>> V_1, //f2
System.Func<System.Collections.IEnumerable> V_2)
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldnull
IL_0003: stloc.1
IL_0004: call ""bool Program.C()""
IL_0009: brtrue.s IL_0010
IL_000b: ldloc.1
IL_000c: stloc.2
IL_000d: ldloc.2
IL_000e: br.s IL_0013
IL_0010: ldloc.0
IL_0011: stloc.2
IL_0012: ldloc.2
IL_0013: call ""void System.Console.WriteLine(object)""
IL_0018: call ""bool Program.C()""
IL_001d: brtrue.s IL_0024
IL_001f: ldloc.0
IL_0020: stloc.2
IL_0021: ldloc.2
IL_0022: br.s IL_0027
IL_0024: ldloc.1
IL_0025: stloc.2
IL_0026: ldloc.2
IL_0027: call ""void System.Console.WriteLine(object)""
IL_002c: ret
}
");
}
[Fact]
public void TestTernary_InterfaceVariance()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Security;
[assembly: SecurityTransparent()]
class Program
{
private static bool C() { return true;}
interface CoInter<out T>
{
}
static void Main(string[] args)
{
CoInter<Exception[]> f1 = null;
CoInter<IEnumerable<object>> f2 = null;
var oo = C()? f1 : f2;
Console.WriteLine(oo);
oo = C()? f2 : f1;
Console.WriteLine(oo);
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"
{
// Code size 41 (0x29)
.maxstack 1
.locals init (Program.CoInter<System.Exception[]> V_0, //f1
Program.CoInter<System.Collections.Generic.IEnumerable<object>> V_1, //f2
Program.CoInter<System.Collections.Generic.IEnumerable<object>> V_2)
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldnull
IL_0003: stloc.1
IL_0004: call ""bool Program.C()""
IL_0009: brtrue.s IL_000e
IL_000b: ldloc.1
IL_000c: br.s IL_0011
IL_000e: ldloc.0
IL_000f: stloc.2
IL_0010: ldloc.2
IL_0011: call ""void System.Console.WriteLine(object)""
IL_0016: call ""bool Program.C()""
IL_001b: brtrue.s IL_0022
IL_001d: ldloc.0
IL_001e: stloc.2
IL_001f: ldloc.2
IL_0020: br.s IL_0023
IL_0022: ldloc.1
IL_0023: call ""void System.Console.WriteLine(object)""
IL_0028: ret
}
");
}
[Fact]
public void TestTernary_InterfaceVarianceA()
{
var source = @"
using System;
using System.Security;
[assembly: SecurityTransparent()]
class Program
{
private static bool C() { return true;}
interface CoInter<out T>
{
}
static void Main(string[] args)
{
CoInter<Exception> f1 = null;
CoInter<object> f2 = null;
var oo = C()? f1 : f2;
Console.WriteLine(oo);
oo = C()? f2 : f1;
Console.WriteLine(oo);
}
}
";
var comp = CompileAndVerify(new string[] { source }, expectedOutput: @"");
// var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"
{
// Code size 41 (0x29)
.maxstack 1
.locals init (Program.CoInter<System.Exception> V_0, //f1
Program.CoInter<object> V_1, //f2
Program.CoInter<object> V_2)
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldnull
IL_0003: stloc.1
IL_0004: call ""bool Program.C()""
IL_0009: brtrue.s IL_000e
IL_000b: ldloc.1
IL_000c: br.s IL_0011
IL_000e: ldloc.0
IL_000f: stloc.2
IL_0010: ldloc.2
IL_0011: call ""void System.Console.WriteLine(object)""
IL_0016: call ""bool Program.C()""
IL_001b: brtrue.s IL_0022
IL_001d: ldloc.0
IL_001e: stloc.2
IL_001f: ldloc.2
IL_0020: br.s IL_0023
IL_0022: ldloc.1
IL_0023: call ""void System.Console.WriteLine(object)""
IL_0028: ret
}
");
}
[Fact]
public void TestTernary_InterfaceVariance01()
{
var source = @"
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security;
[assembly: SecurityTransparent()]
class Program
{
private static bool C() { return true;}
interface CoInter<out T>
{
}
static void Main(string[] args)
{
CoInter<Exception[]> f1 = null;
CoInter<IEnumerable<object>> f2 = null;
var oo = C()? (CoInter<IEnumerable>)f1 : (CoInter<IEnumerable>)f2;
Console.WriteLine(oo);
oo = C()? (CoInter<IEnumerable>)f2 : (CoInter<IEnumerable>)f1;
Console.WriteLine(oo);
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"
{
// Code size 45 (0x2d)
.maxstack 1
.locals init (Program.CoInter<System.Exception[]> V_0, //f1
Program.CoInter<System.Collections.Generic.IEnumerable<object>> V_1, //f2
Program.CoInter<System.Collections.IEnumerable> V_2)
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldnull
IL_0003: stloc.1
IL_0004: call ""bool Program.C()""
IL_0009: brtrue.s IL_0010
IL_000b: ldloc.1
IL_000c: stloc.2
IL_000d: ldloc.2
IL_000e: br.s IL_0013
IL_0010: ldloc.0
IL_0011: stloc.2
IL_0012: ldloc.2
IL_0013: call ""void System.Console.WriteLine(object)""
IL_0018: call ""bool Program.C()""
IL_001d: brtrue.s IL_0024
IL_001f: ldloc.0
IL_0020: stloc.2
IL_0021: ldloc.2
IL_0022: br.s IL_0027
IL_0024: ldloc.1
IL_0025: stloc.2
IL_0026: ldloc.2
IL_0027: call ""void System.Console.WriteLine(object)""
IL_002c: ret
}
");
}
[Fact]
public void TestTernary_ToBase()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Security;
[assembly: SecurityTransparent()]
class Program
{
private static bool C() { return true;}
static void Main(string[] args)
{
Exception[] f1 = null;
IEnumerable<object> f2 = null;
var oo = C()? (object)f1 : (object)f2;
Console.WriteLine(oo);
oo = C()? (object)f2 : (object)f1;
Console.WriteLine(oo);
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"
{
// Code size 37 (0x25)
.maxstack 1
.locals init (System.Exception[] V_0, //f1
System.Collections.Generic.IEnumerable<object> V_1) //f2
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldnull
IL_0003: stloc.1
IL_0004: call ""bool Program.C()""
IL_0009: brtrue.s IL_000e
IL_000b: ldloc.1
IL_000c: br.s IL_000f
IL_000e: ldloc.0
IL_000f: call ""void System.Console.WriteLine(object)""
IL_0014: call ""bool Program.C()""
IL_0019: brtrue.s IL_001e
IL_001b: ldloc.0
IL_001c: br.s IL_001f
IL_001e: ldloc.1
IL_001f: call ""void System.Console.WriteLine(object)""
IL_0024: ret
}
");
}
[WorkItem(634407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/634407")]
[Fact]
public void TestTernary_Null()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Security;
[assembly: SecurityTransparent()]
class Program
{
private static bool C() { return true;}
static void Main(string[] args)
{
Exception[] f1 = null;
var oo = C()? f1 : null as IEnumerable<object>;
Console.WriteLine(oo);
var oo1 = C()? null as IEnumerable<object> : f1 as IEnumerable<Exception>;
Console.WriteLine(oo1);
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"
{
// Code size 39 (0x27)
.maxstack 1
.locals init (System.Exception[] V_0, //f1
System.Collections.Generic.IEnumerable<object> V_1)
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: call ""bool Program.C()""
IL_0007: brtrue.s IL_000c
IL_0009: ldnull
IL_000a: br.s IL_000f
IL_000c: ldloc.0
IL_000d: stloc.1
IL_000e: ldloc.1
IL_000f: call ""void System.Console.WriteLine(object)""
IL_0014: call ""bool Program.C()""
IL_0019: brtrue.s IL_0020
IL_001b: ldloc.0
IL_001c: stloc.1
IL_001d: ldloc.1
IL_001e: br.s IL_0021
IL_0020: ldnull
IL_0021: call ""void System.Console.WriteLine(object)""
IL_0026: ret
}");
}
[WorkItem(634406, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/634406")]
[Fact]
public void TestBinary_Implicit()
{
var source = @"
using System;
using System.Security;
[assembly: SecurityTransparent()]
class Program
{
private static bool C() { return true; }
class cls1
{
public static implicit operator int(cls1 from)
{
return 42;
}
}
static void Main(string[] args)
{
cls1 f1 = null;
var oo = f1 ?? 33;
Console.WriteLine(oo);
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"
{
// Code size 21 (0x15)
.maxstack 1
.locals init (Program.cls1 V_0)
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: brtrue.s IL_0009
IL_0005: ldc.i4.s 33
IL_0007: br.s IL_000f
IL_0009: ldloc.0
IL_000a: call ""int Program.cls1.op_Implicit(Program.cls1)""
IL_000f: call ""void System.Console.WriteLine(int)""
IL_0014: ret
}
");
}
[WorkItem(656807, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/656807")]
[Fact]
public void DelegateEqualsNull()
{
var source = @"
public delegate int D(int x);
public class Program
{
public static D d1 = null;
public static int r1;
public static bool r2;
public static void Main(string[] args)
{
if (d1 == null) { r1 = 1; }
if (d1 != null) { r1 = 2; }
r2 = (d1 == null);
r2 = (d1 != null);
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"
{
// Code size 53 (0x35)
.maxstack 2
IL_0000: ldsfld ""D Program.d1""
IL_0005: brtrue.s IL_000d
IL_0007: ldc.i4.1
IL_0008: stsfld ""int Program.r1""
IL_000d: ldsfld ""D Program.d1""
IL_0012: brfalse.s IL_001a
IL_0014: ldc.i4.2
IL_0015: stsfld ""int Program.r1""
IL_001a: ldsfld ""D Program.d1""
IL_001f: ldnull
IL_0020: ceq
IL_0022: stsfld ""bool Program.r2""
IL_0027: ldsfld ""D Program.d1""
IL_002c: ldnull
IL_002d: cgt.un
IL_002f: stsfld ""bool Program.r2""
IL_0034: ret
}");
}
[WorkItem(717072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/717072")]
[Fact]
public void DecimalOperators()
{
var source = @"
class Program
{
static void Main()
{
decimal d1 = 1.0201m;
if (d1 == 10201M)
{
}
if (d1 != 10201M)
{
}
decimal d2 = d1 + d1;
decimal d3 = d1 - d1;
decimal d4 = d1 * d1;
decimal d5 = d1 / d1;
decimal d6 = d1 % d1;
decimal d7 = d1 ++;
decimal d8 = d1--;
decimal d9 = -d1;
decimal d10 = +d1;
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"
{
// Code size 116 (0x74)
.maxstack 6
.locals init (decimal V_0) //d1
IL_0000: ldloca.s V_0
IL_0002: ldc.i4 0x27d9
IL_0007: ldc.i4.0
IL_0008: ldc.i4.0
IL_0009: ldc.i4.0
IL_000a: ldc.i4.4
IL_000b: call ""decimal..ctor(int, int, int, bool, byte)""
IL_0010: ldloc.0
IL_0011: ldc.i4 0x27d9
IL_0016: newobj ""decimal..ctor(int)""
IL_001b: call ""bool decimal.op_Equality(decimal, decimal)""
IL_0020: pop
IL_0021: ldloc.0
IL_0022: ldc.i4 0x27d9
IL_0027: newobj ""decimal..ctor(int)""
IL_002c: call ""bool decimal.op_Inequality(decimal, decimal)""
IL_0031: pop
IL_0032: ldloc.0
IL_0033: ldloc.0
IL_0034: call ""decimal decimal.op_Addition(decimal, decimal)""
IL_0039: pop
IL_003a: ldloc.0
IL_003b: ldloc.0
IL_003c: call ""decimal decimal.op_Subtraction(decimal, decimal)""
IL_0041: pop
IL_0042: ldloc.0
IL_0043: ldloc.0
IL_0044: call ""decimal decimal.op_Multiply(decimal, decimal)""
IL_0049: pop
IL_004a: ldloc.0
IL_004b: ldloc.0
IL_004c: call ""decimal decimal.op_Division(decimal, decimal)""
IL_0051: pop
IL_0052: ldloc.0
IL_0053: ldloc.0
IL_0054: call ""decimal decimal.op_Modulus(decimal, decimal)""
IL_0059: pop
IL_005a: ldloc.0
IL_005b: dup
IL_005c: call ""decimal decimal.op_Increment(decimal)""
IL_0061: stloc.0
IL_0062: pop
IL_0063: ldloc.0
IL_0064: dup
IL_0065: call ""decimal decimal.op_Decrement(decimal)""
IL_006a: stloc.0
IL_006b: pop
IL_006c: ldloc.0
IL_006d: call ""decimal decimal.op_UnaryNegation(decimal)""
IL_0072: pop
IL_0073: ret
}
");
}
[WorkItem(732269, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/732269")]
[Fact]
public void NullCoalesce()
{
var source = @"
class Program
{
static int Main(int? x, int y) { return x ?? y; }
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"
{
// Code size 21 (0x15)
.maxstack 1
.locals init (int? V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool int?.HasValue.get""
IL_0009: brtrue.s IL_000d
IL_000b: ldarg.1
IL_000c: ret
IL_000d: ldloca.s V_0
IL_000f: call ""int int?.GetValueOrDefault()""
IL_0014: ret
}
");
}
[Fact]
public void TestCompoundOnAFieldOfGeneric()
{
var source = @"
class Program
{
static void Main(string[] args)
{
var x = new c0();
test<c0>.Repro1(x);
System.Console.WriteLine(x.x);
test<c0>.Repro2(x);
System.Console.WriteLine(x.x);
}
}
class c0
{
public int x;
public int P1
{
get { return x; }
set { x = value; }
}
public int this[int i]
{
get { return x; }
set { x = value; }
}
public static int Goo(c0 arg)
{
return 1;
}
public int Goo()
{
return 1;
}
}
class test<T> where T : c0
{
public static void Repro1(T arg)
{
arg.x += 1;
arg.P1 += 1;
arg[1] += 1;
}
public static void Repro2(T arg)
{
arg.x = c0.Goo(arg);
arg.x = arg.Goo();
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"3
1");
compilation.VerifyIL("test<T>.Repro1(T)", @"
{
// Code size 80 (0x50)
.maxstack 4
.locals init (T& V_0)
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: dup
IL_0007: ldfld ""int c0.x""
IL_000c: ldc.i4.1
IL_000d: add
IL_000e: stfld ""int c0.x""
IL_0013: ldarga.s V_0
IL_0015: stloc.0
IL_0016: ldloc.0
IL_0017: ldloc.0
IL_0018: constrained. ""T""
IL_001e: callvirt ""int c0.P1.get""
IL_0023: ldc.i4.1
IL_0024: add
IL_0025: constrained. ""T""
IL_002b: callvirt ""void c0.P1.set""
IL_0030: ldarga.s V_0
IL_0032: stloc.0
IL_0033: ldloc.0
IL_0034: ldc.i4.1
IL_0035: ldloc.0
IL_0036: ldc.i4.1
IL_0037: constrained. ""T""
IL_003d: callvirt ""int c0.this[int].get""
IL_0042: ldc.i4.1
IL_0043: add
IL_0044: constrained. ""T""
IL_004a: callvirt ""void c0.this[int].set""
IL_004f: ret
}
").VerifyIL("test<T>.Repro2(T)", @"
{
// Code size 45 (0x2d)
.maxstack 2
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: ldarg.0
IL_0007: box ""T""
IL_000c: call ""int c0.Goo(c0)""
IL_0011: stfld ""int c0.x""
IL_0016: ldarg.0
IL_0017: box ""T""
IL_001c: ldarg.0
IL_001d: box ""T""
IL_0022: callvirt ""int c0.Goo()""
IL_0027: stfld ""int c0.x""
IL_002c: ret
}
");
}
[Fact()]
[WorkItem(4828, "https://github.com/dotnet/roslyn/issues/4828")]
public void OptimizeOutLocals_01()
{
const string source = @"
class Program
{
static void Main(string[] args)
{
int a = 0;
int b = a + a / 1;
}
}";
var result = CompileAndVerify(source, options: TestOptions.ReleaseExe);
result.VerifyIL("Program.Main",
@"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldc.i4.0
IL_0001: ldc.i4.1
IL_0002: div
IL_0003: pop
IL_0004: ret
}
");
}
[ConditionalFact(typeof(NoIOperationValidation))]
[WorkItem(5395, "https://github.com/dotnet/roslyn/issues/5395")]
public void EmitSequenceOfBinaryExpressions_01()
{
var source =
@"
class Test
{
static void Main()
{
var f = new long[4096];
for (int i = 0; i < 4096 ; i++)
{
f[i] = 4096 - i;
}
System.Console.WriteLine((Calculate1(f) == Calculate2(f)) ? ""True"" : ""False"");
}
public static long Calculate1(long[] f)
{
" + $" return { BuildSequenceOfBinaryExpressions_01() };" + @"
}
public static long Calculate2(long[] f)
{
long result = 0;
int i;
for (i = 0; i < f.Length; i++)
{
result+=(i + 1)*f[i];
}
return result + (i + 1);
}
}
";
var result = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: "True");
}
private static string BuildSequenceOfBinaryExpressions_01(int count = 4096)
{
var builder = new System.Text.StringBuilder();
int i;
for (i = 0; i < count; i++)
{
builder.Append(i + 1);
builder.Append(" * ");
builder.Append("f[");
builder.Append(i);
builder.Append("] + ");
}
builder.Append(i + 1);
return builder.ToString();
}
[ConditionalFact(typeof(NoIOperationValidation))]
[WorkItem(5395, "https://github.com/dotnet/roslyn/issues/5395")]
public void EmitSequenceOfBinaryExpressions_02()
{
var source =
@"
class Test
{
static void Main()
{
var f = new long[4096];
for (int i = 0; i < 4096 ; i++)
{
f[i] = 4096 - i;
}
System.Console.WriteLine(Calculate(f));
}
public static double Calculate(long[] f)
{
" + $" return checked({ BuildSequenceOfBinaryExpressions_01() });" + @"
}
}
";
var result = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: "11461640193");
}
[ConditionalFact(typeof(ClrOnly), typeof(NoIOperationValidation), Reason = "https://github.com/dotnet/roslyn/issues/29428")]
[WorkItem(6077, "https://github.com/dotnet/roslyn/issues/6077")]
[WorkItem(5395, "https://github.com/dotnet/roslyn/issues/5395")]
public void EmitSequenceOfBinaryExpressions_03()
{
var diagnostics = ImmutableArray<Diagnostic>.Empty;
const int start = 8192;
const int step = 4096;
const int limit = start * 4;
for (int count = start; count <= limit && diagnostics.IsEmpty; count += step)
{
var source =
@"
class Test
{
static void Main()
{
}
public static bool Calculate(bool[] a, bool[] f)
{
" + $" return { BuildSequenceOfBinaryExpressions_03(count) };" + @"
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
diagnostics = compilation.GetEmitDiagnostics();
}
diagnostics.Verify(
// (10,16): error CS8078: An expression is too long or complex to compile
// return a[0] && f[0] || a[1] && f[1] || a[2] && f[2] || ...
Diagnostic(ErrorCode.ERR_InsufficientStack, "a").WithLocation(10, 16)
);
}
private static string BuildSequenceOfBinaryExpressions_03(int count = 8192)
{
var builder = new System.Text.StringBuilder();
int i;
for (i = 0; i < count; i++)
{
builder.Append("a[");
builder.Append(i);
builder.Append("]");
builder.Append(" && ");
builder.Append("f[");
builder.Append(i);
builder.Append("] || ");
}
builder.Append("a[");
builder.Append(i);
builder.Append("]");
return builder.ToString();
}
[ConditionalFact(typeof(ClrOnly), typeof(NoIOperationValidation), Reason = "https://github.com/dotnet/roslyn/issues/29428")]
[WorkItem(5395, "https://github.com/dotnet/roslyn/issues/5395")]
public void EmitSequenceOfBinaryExpressions_04()
{
var source =
@"
class Test
{
static void Main()
{
var f = new float?[4096];
for (int i = 0; i < 4096 ; i++)
{
f[i] = 4096 - i;
}
System.Console.WriteLine(Calculate(f));
}
public static double? Calculate(float?[] f)
{
" + $" return { BuildSequenceOfBinaryExpressions_01() };" + @"
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyEmitDiagnostics(
// (17,16): error CS8078: An expression is too long or complex to compile
// return 1 * f[0] + 2 * f[1] + 3 * f[2] + 4 * f[3] + ...
Diagnostic(ErrorCode.ERR_InsufficientStack, "1").WithLocation(17, 16)
);
}
[ConditionalFact(typeof(NoIOperationValidation))]
[WorkItem(5395, "https://github.com/dotnet/roslyn/issues/5395")]
public void EmitSequenceOfBinaryExpressions_05()
{
int count = 50;
var source =
@"
class Test
{
static void Main()
{
Test1();
Test2();
}
static void Test1()
{
var f = new double?[" + $"{count}" + @"];
for (int i = 0; i < " + $"{count}" + @" ; i++)
{
f[i] = 4096 - i;
}
System.Console.WriteLine(Calculate(f));
}
public static double? Calculate(double?[] f)
{
" + $" return { BuildSequenceOfBinaryExpressions_01(count) };" + @"
}
static void Test2()
{
var f = new double[" + $"{count}" + @"];
for (int i = 0; i < " + $"{count}" + @" ; i++)
{
f[i] = 4096 - i;
}
System.Console.WriteLine(Calculate(f));
}
public static double Calculate(double[] f)
{
" + $" return { BuildSequenceOfBinaryExpressions_01(count) };" + @"
}
}
";
var result = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"5180801
5180801");
}
[ConditionalFact(typeof(ClrOnly), typeof(NoIOperationValidation), Reason = "https://github.com/dotnet/roslyn/issues/29428", AlwaysSkip = "https://github.com/dotnet/roslyn/issues/46361")]
[WorkItem(5395, "https://github.com/dotnet/roslyn/issues/5395")]
public void EmitSequenceOfBinaryExpressions_06()
{
var source =
@"
class Test
{
static void Main()
{
}
public static bool Calculate(S1[] a, S1[] f)
{
" + $" return { BuildSequenceOfBinaryExpressions_03() };" + @"
}
}
struct S1
{
public static S1 operator & (S1 x, S1 y)
{
return new S1();
}
public static S1 operator |(S1 x, S1 y)
{
return new S1();
}
public static bool operator true(S1 x)
{
return true;
}
public static bool operator false(S1 x)
{
return true;
}
public static implicit operator bool (S1 x)
{
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyEmitDiagnostics(
// (10,16): error CS8078: An expression is too long or complex to compile
// return a[0] && f[0] || a[1] && f[1] || a[2] && f[2] || ...
Diagnostic(ErrorCode.ERR_InsufficientStack, "a").WithLocation(10, 16)
);
}
[Fact, WorkItem(7262, "https://github.com/dotnet/roslyn/issues/7262")]
public void TruncatePrecisionOnCast()
{
var source =
@"
class Test
{
static void Main()
{
float temp1 = (float)(23334800f / 5.5f);
System.Console.WriteLine((int)temp1);
const float temp2 = (float)(23334800f / 5.5f);
System.Console.WriteLine((int)temp2);
System.Console.WriteLine((int)(23334800f / 5.5f));
}
}
";
var expectedOutput =
@"4242691
4242691
4242691";
var result = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput);
}
[Fact, WorkItem(17756, "https://github.com/dotnet/roslyn/issues/17756")]
public void TestCoalesceNotLvalue()
{
var source = @"
class Program
{
struct S1
{
public int field;
public int Increment() => field++;
}
static void Main()
{
S1 v = default(S1);
v.Increment();
((S1?)null ?? v).Increment();
System.Console.WriteLine(v.field);
}
}
";
string expectedOutput = @"1";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void TestNullCoalesce_NullableWithDefault_Optimization()
{
var source = @"
class Program
{
struct S
{
int _a;
System.Guid _b;
public S(int a, System.Guid b)
{
_a = a;
_b = b;
}
public override string ToString() => (_a, _b).ToString();
}
static int CoalesceInt32(int? x)
{
return x ?? 0;
}
static T CoalesceGeneric<T>(T? x) where T : struct
{
return x ?? default(T);
}
static (bool a, System.Guid b) CoalesceTuple((bool a, System.Guid b)? x)
{
return x ?? default((bool a, System.Guid b));
}
static S CoalesceUserStruct(S? x)
{
return x ?? default(S);
}
static S CoalesceStructWithImplicitConstructor(S? x)
{
return x ?? new S();
}
static void Main()
{
System.Console.WriteLine(CoalesceInt32(42));
System.Console.WriteLine(CoalesceInt32(null));
System.Console.WriteLine(CoalesceGeneric<System.Guid>(new System.Guid(""44ed2f0b-c2fa-4791-81f6-97222fffa466"")));
System.Console.WriteLine(CoalesceGeneric<System.Guid>(null));
System.Console.WriteLine(CoalesceTuple((true, new System.Guid(""1c95cef0-1aae-4adb-a43c-54b2e7c083a0""))));
System.Console.WriteLine(CoalesceTuple(null));
System.Console.WriteLine(CoalesceUserStruct(new S(42, new System.Guid(""8683f371-81b4-45f6-aaed-1c665b371594""))));
System.Console.WriteLine(CoalesceUserStruct(null));
System.Console.WriteLine(CoalesceStructWithImplicitConstructor(new S()));
System.Console.WriteLine(CoalesceStructWithImplicitConstructor(null));
}
}";
var expectedOutput =
@"42
0
44ed2f0b-c2fa-4791-81f6-97222fffa466
00000000-0000-0000-0000-000000000000
(True, 1c95cef0-1aae-4adb-a43c-54b2e7c083a0)
(False, 00000000-0000-0000-0000-000000000000)
(42, 8683f371-81b4-45f6-aaed-1c665b371594)
(0, 00000000-0000-0000-0000-000000000000)
(0, 00000000-0000-0000-0000-000000000000)
(0, 00000000-0000-0000-0000-000000000000)";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyIL("Program.CoalesceInt32", @"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""int int?.GetValueOrDefault()""
IL_0007: ret
}");
comp.VerifyIL("Program.CoalesceGeneric<T>", @"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""T T?.GetValueOrDefault()""
IL_0007: ret
}");
comp.VerifyIL("Program.CoalesceTuple", @"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""System.ValueTuple<bool, System.Guid> System.ValueTuple<bool, System.Guid>?.GetValueOrDefault()""
IL_0007: ret
}");
comp.VerifyIL("Program.CoalesceUserStruct", @"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""Program.S Program.S?.GetValueOrDefault()""
IL_0007: ret
}");
comp.VerifyIL("Program.CoalesceStructWithImplicitConstructor", @"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""Program.S Program.S?.GetValueOrDefault()""
IL_0007: ret
}");
}
[Fact]
public void TestNullCoalesce_NullableWithConvertedDefault_Optimization()
{
var source = @"
class Program
{
static (bool a, System.Guid b, string c) CoalesceDifferentTupleNames((bool a, System.Guid b, string c)? x)
{
return x ?? default((bool c, System.Guid d, string e));
}
static void Main()
{
System.Console.WriteLine(CoalesceDifferentTupleNames((true, new System.Guid(""533d4d3b-5013-461e-ae9e-b98eb593d761""), ""value"")));
System.Console.WriteLine(CoalesceDifferentTupleNames(null));
}
}";
var expectedOutput =
@"(True, 533d4d3b-5013-461e-ae9e-b98eb593d761, value)
(False, 00000000-0000-0000-0000-000000000000, )";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyIL("Program.CoalesceDifferentTupleNames", @"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""System.ValueTuple<bool, System.Guid, string> System.ValueTuple<bool, System.Guid, string>?.GetValueOrDefault()""
IL_0007: ret
}");
}
[Fact]
public void TestNullCoalesce_NullableWithNonDefault_NoOptimization()
{
var source = @"
class Program
{
static int CoalesceWithNonDefault1(int? x)
{
return x ?? 2;
}
static int CoalesceWithNonDefault2(int? x, int y)
{
return x ?? y;
}
static int? CoalesceWithNonDefault3(int? x, int? y)
{
return x ?? y;
}
static int? CoalesceWithNonDefault4(int? x)
{
return x ?? default(int?);
}
static void Main()
{
void WriteLine(object value) => System.Console.WriteLine(value?.ToString() ?? ""*null*"");
WriteLine(CoalesceWithNonDefault1(42));
WriteLine(CoalesceWithNonDefault1(null));
WriteLine(CoalesceWithNonDefault2(12, 34));
WriteLine(CoalesceWithNonDefault2(null, 34));
WriteLine(CoalesceWithNonDefault3(123, 456));
WriteLine(CoalesceWithNonDefault3(123, null));
WriteLine(CoalesceWithNonDefault3(null, 456));
WriteLine(CoalesceWithNonDefault3(null, null));
WriteLine(CoalesceWithNonDefault4(42));
WriteLine(CoalesceWithNonDefault4(null));
}
}";
var expectedOutput =
@"42
2
12
34
123
123
456
*null*
42
*null*";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyIL("Program.CoalesceWithNonDefault1", @"{
// Code size 21 (0x15)
.maxstack 1
.locals init (int? V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool int?.HasValue.get""
IL_0009: brtrue.s IL_000d
IL_000b: ldc.i4.2
IL_000c: ret
IL_000d: ldloca.s V_0
IL_000f: call ""int int?.GetValueOrDefault()""
IL_0014: ret
}");
comp.VerifyIL("Program.CoalesceWithNonDefault2", @"{
// Code size 21 (0x15)
.maxstack 1
.locals init (int? V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool int?.HasValue.get""
IL_0009: brtrue.s IL_000d
IL_000b: ldarg.1
IL_000c: ret
IL_000d: ldloca.s V_0
IL_000f: call ""int int?.GetValueOrDefault()""
IL_0014: ret
}");
comp.VerifyIL("Program.CoalesceWithNonDefault3", @"{
// Code size 15 (0xf)
.maxstack 1
.locals init (int? V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool int?.HasValue.get""
IL_0009: brtrue.s IL_000d
IL_000b: ldarg.1
IL_000c: ret
IL_000d: ldloc.0
IL_000e: ret
}");
comp.VerifyIL("Program.CoalesceWithNonDefault4", @"{
// Code size 23 (0x17)
.maxstack 1
.locals init (int? V_0,
int? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool int?.HasValue.get""
IL_0009: brtrue.s IL_0015
IL_000b: ldloca.s V_1
IL_000d: initobj ""int?""
IL_0013: ldloc.1
IL_0014: ret
IL_0015: ldloc.0
IL_0016: ret
}");
}
[Fact]
public void TestNullCoalesce_NonNullableWithDefault_NoOptimization()
{
var source = @"
class Program
{
static string CoalesceNonNullableWithDefault(string x)
{
return x ?? default(string);
}
static void Main()
{
void WriteLine(object value) => System.Console.WriteLine(value?.ToString() ?? ""*null*"");
WriteLine(CoalesceNonNullableWithDefault(""value""));
WriteLine(CoalesceNonNullableWithDefault(null));
}
}";
var expectedOutput =
@"value
*null*";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyIL("Program.CoalesceNonNullableWithDefault", @"{
// Code size 7 (0x7)
.maxstack 2
IL_0000: ldarg.0
IL_0001: dup
IL_0002: brtrue.s IL_0006
IL_0004: pop
IL_0005: ldnull
IL_0006: ret
}");
}
[Fact]
public void TestNullCoalesce_NullableDefault_MissingGetValueOrDefault()
{
var source = @"
class Program
{
static int Coalesce(int? x)
{
return x ?? 0;
}
}";
var comp = CreateCompilation(source);
comp.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault);
comp.VerifyEmitDiagnostics(
// (6,16): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault'
// return x ?? 0;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "x").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(6, 16),
// (6,16): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault'
// return x ?? 0;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "x").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(6, 16)
);
}
[Fact]
public void TestNullCoalesce_UnconstrainedTypeParameter_OldLanguageVersion()
{
var source = @"
class C
{
void M<T>(T t1, T t2)
{
t1 = t1 ?? t2;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (6,14): error CS8652: The feature 'unconstrained type parameters in null coalescing operator' is not available in C# 7.3. Please use language version 8.0 or greater.
// t1 = t1 ?? t2;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "t1 ?? t2").WithArguments("unconstrained type parameters in null coalescing operator", "8.0").WithLocation(6, 14));
}
[Fact, WorkItem(41760, "https://github.com/dotnet/roslyn/issues/41760")]
public void NullableBoolOperatorSemantics_01()
{
// The C# specification has a section outlining the behavior of the bool operators `|` and `&`
// on operands of type `bool?`. We check that these are the semantics obeyed by the compiler.
var sourceStart = @"
using System;
public class C
{
bool T => true;
bool F => false;
static bool? True => true;
static bool? False => false;
static bool? Null => null;
static void Main()
{
C n = null;
C c = new C();
bool t = true;
bool f = false;
bool? nt = true;
bool? nf = false;
bool? nn = null;
";
var sourceEnd =
@" Console.WriteLine(""Done."");
}
static bool? And(bool? x, bool? y)
{
if (x == false || y == false)
return false;
if (x == null || y == null)
return null;
return true;
}
static bool? Or(bool? x, bool? y)
{
if (x == true || y == true)
return true;
if (x == null || y == null)
return null;
return false;
}
static bool? Xor(bool? x, bool? y)
{
if (x == null || y == null)
return null;
return x.Value != y.Value;
}
}
static class Assert
{
public static void Equal<T>(T expected, T actual, string message)
{
if (!object.Equals(expected, actual))
Console.WriteLine($""Wrong for {message,-15} Expected: {expected?.ToString() ?? ""null"",-5} Actual: {actual?.ToString() ?? ""null""}"");
}
}
";
var builder = new StringBuilder();
var forms = new string[]
{
"null",
"nn",
"true",
"t",
"nt",
"false",
"f",
"nf",
"c?.T",
"c?.F",
"n?.T",
"Null",
"True",
"False",
};
foreach (var left in forms)
{
foreach (var right in forms)
{
if (left == "null" && right == "null")
continue;
builder.AppendLine(@$" Assert.Equal<bool?>(Or({left}, {right}), {left} | {right}, ""{left} | {right}"");");
builder.AppendLine(@$" Assert.Equal<bool?>(And({left}, {right}), {left} & {right}, ""{left} & {right}"");");
if (left != "null" && right != "null")
builder.AppendLine(@$" Assert.Equal<bool?>(Xor({left}, {right}), {left} ^ {right}, ""{left} ^ {right}"");");
}
}
var source = sourceStart + builder.ToString() + sourceEnd;
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics(
);
CompileAndVerify(comp, expectedOutput: @"Done.");
}
[Fact, WorkItem(41760, "https://github.com/dotnet/roslyn/issues/41760")]
public void NullableBoolOperatorSemantics_02()
{
var source = @"
using System;
public class C
{
public bool BoolValue;
static void Main()
{
C obj = null;
Console.Write(obj?.BoolValue | true);
Console.Write(obj?.BoolValue & false);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics(
);
var cv = CompileAndVerify(comp, expectedOutput: @"TrueFalse");
cv.VerifyIL("C.Main", @"
{
// Code size 99 (0x63)
.maxstack 3
.locals init (bool? V_0,
bool? V_1)
IL_0000: ldnull
IL_0001: dup
IL_0002: dup
IL_0003: brtrue.s IL_0011
IL_0005: pop
IL_0006: ldloca.s V_1
IL_0008: initobj ""bool?""
IL_000e: ldloc.1
IL_000f: br.s IL_001b
IL_0011: ldfld ""bool C.BoolValue""
IL_0016: newobj ""bool?..ctor(bool)""
IL_001b: stloc.0
IL_001c: ldc.i4.1
IL_001d: brtrue.s IL_0022
IL_001f: ldloc.0
IL_0020: br.s IL_0028
IL_0022: ldc.i4.1
IL_0023: newobj ""bool?..ctor(bool)""
IL_0028: box ""bool?""
IL_002d: call ""void System.Console.Write(object)""
IL_0032: dup
IL_0033: brtrue.s IL_0041
IL_0035: pop
IL_0036: ldloca.s V_1
IL_0038: initobj ""bool?""
IL_003e: ldloc.1
IL_003f: br.s IL_004b
IL_0041: ldfld ""bool C.BoolValue""
IL_0046: newobj ""bool?..ctor(bool)""
IL_004b: stloc.0
IL_004c: ldc.i4.0
IL_004d: brtrue.s IL_0057
IL_004f: ldc.i4.0
IL_0050: newobj ""bool?..ctor(bool)""
IL_0055: br.s IL_0058
IL_0057: ldloc.0
IL_0058: box ""bool?""
IL_005d: call ""void System.Console.Write(object)""
IL_0062: 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.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.UnitTests.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using System.Collections.Immutable;
using System.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public class CodeGenOperators : CSharpTestBase
{
[Fact]
public void TestIsNullPattern()
{
var source = @"
using System;
class C
{
public static void Main()
{
var c = new C();
Console.Write(c is null);
}
}
";
// Release
var compilation = CompileAndVerify(source, expectedOutput: "False", options: TestOptions.ReleaseExe);
compilation.VerifyIL("C.Main", @"{
// Code size 14 (0xe)
.maxstack 2
IL_0000: newobj ""C..ctor()""
IL_0005: ldnull
IL_0006: ceq
IL_0008: call ""void System.Console.Write(bool)""
IL_000d: ret
}");
// Debug
compilation = CompileAndVerify(source, expectedOutput: "False", options: TestOptions.DebugExe);
compilation.VerifyIL("C.Main", @"{
// Code size 18 (0x12)
.maxstack 2
.locals init (C V_0) //c
IL_0000: nop
IL_0001: newobj ""C..ctor()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldnull
IL_0009: ceq
IL_000b: call ""void System.Console.Write(bool)""
IL_0010: nop
IL_0011: ret
}");
}
[Fact]
public void TestIsNullPatternGenericParam()
{
var source = @"
using System;
class C
{
public static void M<T>(T o)
{
Console.Write(o is null);
if (o is null)
{
Console.Write(""Branch taken"");
}
}
public static void Main()
{
M(new object());
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "False", options: TestOptions.ReleaseExe);
compilation.VerifyIL("C.M<T>(T)", @"{
// Code size 33 (0x21)
.maxstack 2
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: ldnull
IL_0007: ceq
IL_0009: call ""void System.Console.Write(bool)""
IL_000e: ldarg.0
IL_000f: box ""T""
IL_0014: brtrue.s IL_0020
IL_0016: ldstr ""Branch taken""
IL_001b: call ""void System.Console.Write(string)""
IL_0020: ret
}");
// Debug
compilation = CompileAndVerify(source, expectedOutput: "False", options: TestOptions.DebugExe);
compilation.VerifyIL("C.M<T>(T)", @"{
// Code size 43 (0x2b)
.maxstack 2
.locals init (bool V_0)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: box ""T""
IL_0007: ldnull
IL_0008: ceq
IL_000a: call ""void System.Console.Write(bool)""
IL_000f: nop
IL_0010: ldarg.0
IL_0011: box ""T""
IL_0016: ldnull
IL_0017: ceq
IL_0019: stloc.0
IL_001a: ldloc.0
IL_001b: brfalse.s IL_002a
IL_001d: nop
IL_001e: ldstr ""Branch taken""
IL_0023: call ""void System.Console.Write(string)""
IL_0028: nop
IL_0029: nop
IL_002a: ret
}");
}
[Fact]
public void TestIsNullPatternGenericParamClass()
{
var source = @"
using System;
class C
{
public static void M<T>(T o) where T: class
{
Console.Write(o is null);
if (o is null) {
Console.Write("" Branch taken"");
}
}
public static void Main()
{
M(new object());
}
}
";
// Release
var compilation = CompileAndVerify(source, expectedOutput: "False", options: TestOptions.ReleaseExe);
compilation.VerifyIL("C.M<T>(T)", @"{
// Code size 33 (0x21)
.maxstack 2
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: ldnull
IL_0007: ceq
IL_0009: call ""void System.Console.Write(bool)""
IL_000e: ldarg.0
IL_000f: box ""T""
IL_0014: brtrue.s IL_0020
IL_0016: ldstr "" Branch taken""
IL_001b: call ""void System.Console.Write(string)""
IL_0020: ret
}");
// Debug
compilation = CompileAndVerify(source, expectedOutput: "False", options: TestOptions.DebugExe);
compilation.VerifyIL("C.M<T>(T)", @"{
// Code size 43 (0x2b)
.maxstack 2
.locals init (bool V_0)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: box ""T""
IL_0007: ldnull
IL_0008: ceq
IL_000a: call ""void System.Console.Write(bool)""
IL_000f: nop
IL_0010: ldarg.0
IL_0011: box ""T""
IL_0016: ldnull
IL_0017: ceq
IL_0019: stloc.0
IL_001a: ldloc.0
IL_001b: brfalse.s IL_002a
IL_001d: nop
IL_001e: ldstr "" Branch taken""
IL_0023: call ""void System.Console.Write(string)""
IL_0028: nop
IL_0029: nop
IL_002a: ret
}");
}
[Fact]
public void TestIsNullPatternNullable()
{
var source = @"
using System;
class C
{
public static void M(Nullable<int> obj)
{
Console.Write(obj is null);
if (obj is null) {
Console.Write("" Branch taken"");
} else {
Console.Write("" Branch not taken"");
}
}
public static void Main()
{
M(5);
Console.Write(""-"");
M(null);
}
}
";
// Release
var compilation = CompileAndVerify(source, expectedOutput: "False Branch not taken-True Branch taken", options: TestOptions.ReleaseExe);
compilation.VerifyIL("C.M", @"{
// Code size 46 (0x2e)
.maxstack 2
IL_0000: ldarga.s V_0
IL_0002: call ""bool int?.HasValue.get""
IL_0007: ldc.i4.0
IL_0008: ceq
IL_000a: call ""void System.Console.Write(bool)""
IL_000f: ldarga.s V_0
IL_0011: call ""bool int?.HasValue.get""
IL_0016: brtrue.s IL_0023
IL_0018: ldstr "" Branch taken""
IL_001d: call ""void System.Console.Write(string)""
IL_0022: ret
IL_0023: ldstr "" Branch not taken""
IL_0028: call ""void System.Console.Write(string)""
IL_002d: ret
}");
// Debug
compilation = CompileAndVerify(source, expectedOutput: "False Branch not taken-True Branch taken", options: TestOptions.DebugExe);
compilation.VerifyIL("C.M", @"{
// Code size 60 (0x3c)
.maxstack 2
.locals init (bool V_0)
IL_0000: nop
IL_0001: ldarga.s V_0
IL_0003: call ""bool int?.HasValue.get""
IL_0008: ldc.i4.0
IL_0009: ceq
IL_000b: call ""void System.Console.Write(bool)""
IL_0010: nop
IL_0011: ldarga.s V_0
IL_0013: call ""bool int?.HasValue.get""
IL_0018: ldc.i4.0
IL_0019: ceq
IL_001b: stloc.0
IL_001c: ldloc.0
IL_001d: brfalse.s IL_002e
IL_001f: nop
IL_0020: ldstr "" Branch taken""
IL_0025: call ""void System.Console.Write(string)""
IL_002a: nop
IL_002b: nop
IL_002c: br.s IL_003b
IL_002e: nop
IL_002f: ldstr "" Branch not taken""
IL_0034: call ""void System.Console.Write(string)""
IL_0039: nop
IL_003a: nop
IL_003b: ret
}");
}
[Fact]
public void TestIsNullPatternObjectLiteral()
{
var source = @"
using System;
class C
{
public static void Main()
{
Console.Write(((object)null) is null);
if (((object) null) is null) {
Console.Write("" Branch taken"");
}
}
}
";
// Release
var compilation = CompileAndVerify(source, expectedOutput: "True Branch taken", options: TestOptions.ReleaseExe);
compilation.VerifyIL("C.Main", @"{
// Code size 17 (0x11)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: call ""void System.Console.Write(bool)""
IL_0006: ldstr "" Branch taken""
IL_000b: call ""void System.Console.Write(string)""
IL_0010: ret
}");
// Debug
compilation = CompileAndVerify(source, expectedOutput: "True Branch taken", options: TestOptions.DebugExe);
compilation.VerifyIL("C.Main", @"
{
// Code size 27 (0x1b)
.maxstack 1
.locals init (bool V_0)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: call ""void System.Console.Write(bool)""
IL_0007: nop
IL_0008: ldc.i4.1
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_001a
IL_000d: nop
IL_000e: ldstr "" Branch taken""
IL_0013: call ""void System.Console.Write(string)""
IL_0018: nop
IL_0019: nop
IL_001a: ret
}");
}
[Fact]
public void TestIsNullPatternStringConstant()
{
var source = @"
using System;
class C
{
const String nullString = null;
public static void Main()
{
Console.Write(((string)null) is nullString);
if (((string) null) is nullString) {
Console.Write("" Branch taken"");
}
}
}
";
// Release
var compilation = CompileAndVerify(source, expectedOutput: "True Branch taken", options: TestOptions.ReleaseExe);
compilation.VerifyIL("C.Main", @"{
// Code size 17 (0x11)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: call ""void System.Console.Write(bool)""
IL_0006: ldstr "" Branch taken""
IL_000b: call ""void System.Console.Write(string)""
IL_0010: ret
}");
// Debug
compilation = CompileAndVerify(source, expectedOutput: "True Branch taken", options: TestOptions.DebugExe);
compilation.VerifyIL("C.Main", @"{
// Code size 27 (0x1b)
.maxstack 1
.locals init (bool V_0)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: call ""void System.Console.Write(bool)""
IL_0007: nop
IL_0008: ldc.i4.1
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_001a
IL_000d: nop
IL_000e: ldstr "" Branch taken""
IL_0013: call ""void System.Console.Write(string)""
IL_0018: nop
IL_0019: nop
IL_001a: ret
}");
}
[Fact]
public void TestDelegateAndStringOperators()
{
var source = @"
using System;
class C
{
delegate void D();
public static void M123()
{
Console.WriteLine(123);
}
public static void M456()
{
Console.WriteLine(456);
}
public static void Main()
{
D d123 = M123;
D d456 = M456;
D d123456 = d123 + d456;
d123456();
Console.WriteLine(d123456 - d123 == d456);
Console.WriteLine(d123456 - d123 == d123);
string s123 = 123.ToString();
object s456 = 456.ToString();
Console.WriteLine(s123 + s456);
Console.WriteLine(s123 + s456 + s123);
}
}
";
string expectedOutput =
@"123
456
True
False
123456
123456123
";
var compilation = CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void TestCompoundAssignmentOperators()
{
var source = @"
using System;
class C
{
delegate void D();
public static void M123()
{
Console.Write(123);
}
public static void M456()
{
Console.Write(456);
}
static C c;
static C GetC() { Console.Write(""GetC""); return c; }
byte f;
public static void Main()
{
C.c = new C();
D d123 = M123;
D d456 = M456;
D d = null;
d += d123;
d();
d += d456;
d();
d -= d123;
d();
Console.WriteLine();
short b = 100;
b -= 70;
Console.Write(b);
b *= 2;
Console.Write(b);
Console.WriteLine();
string s = string.Empty;
s += 789.ToString();
Console.Write(s);
s += 987.ToString();
Console.Write(s);
Console.WriteLine();
GetC().f += 100;
Console.Write(C.c.f);
Console.WriteLine();
int[] arr = { 10 };
arr[0] += 1;
Console.Write(arr[0]);
Console.WriteLine();
}
}
";
string expectedOutput =
@"123123456456
3060
789789987
GetC100
11";
var compilation = CompileAndVerify(source, expectedOutput: expectedOutput);
}
// TODO: Add VerifyIL for is and as Codegen tests
[Fact]
public void TestIsOperator()
{
var source = @"
namespace TestIsOperator
{
public interface MyInter { }
public class TestType : MyInter { }
public class AnotherType { }
public class MyBase { }
public class MyDerived : MyBase { }
public class C
{
static void Main()
{
string myStr = ""goo"";
object o = myStr;
bool b = o is string;
int myInt = 3;
b = myInt is int;
TestType tt = null;
o = tt;
b = o is TestType;
tt = new TestType();
o = tt;
b = o is AnotherType;
b = o is MyInter;
MyInter mi = new TestType();
o = mi;
b = o is MyInter;
MyBase mb = new MyBase();
o = mb;
b = o is MyDerived;
MyDerived md = new MyDerived();
o = md;
b = o is MyBase;
b = null is MyBase;
}
}
}
";
var compilation = CompileAndVerify(source);
}
// TODO: Add VerifyIL for is and as Codegen tests
[Fact]
public void TestIsOperatorGeneric()
{
var source = @"
namespace TestIsOperatorGeneric
{
public class C
{
public static void Main() { }
public static void M<T, U, W>(T t, U u, W w)
where T : class
where U : class
where W : class
{
bool test = t is int;
test = u is object;
test = t is U;
test = t is T;
test = u is U;
test = u is T;
test = w is int;
test = w is object;
test = w is U;
test = u is W;
test = t is W;
test = w is W;
}
}
}
";
var compilation = CompileAndVerify(source);
}
[Fact]
public void CS0184WRN_IsAlwaysFalse()
{
var text = @"
class MyClass
{
public static int Main()
{
int i = 0;
bool b = i is string; // CS0184
System.Console.WriteLine(b);
return 0;
}
}
";
var comp = CompileAndVerify(text, expectedOutput: "False");
comp.VerifyDiagnostics(
// (7,18): warning CS0184: The given expression is never of the provided ('string') type
// bool b = i is string; // CS0184
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "i is string").WithArguments("string"));
comp.VerifyIL("MyClass.Main", @"
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: call ""void System.Console.WriteLine(bool)""
IL_0006: ldc.i4.0
IL_0007: ret
}");
}
[WorkItem(542466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542466")]
[Fact]
public void CS0184WRN_IsAlwaysFalse_Enum()
{
var text = @"
class IsTest
{
static void Main()
{
var b = 1 is color;
System.Console.WriteLine(b);
}
}
enum color
{ }
";
var comp = CompileAndVerify(text, expectedOutput: "False");
comp.VerifyDiagnostics(
// (6,17): warning CS0184: The given expression is never of the provided ('color') type
// var b = 1 is color;
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "1 is color").WithArguments("color"));
comp.VerifyIL("IsTest.Main", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: call ""void System.Console.WriteLine(bool)""
IL_0006: ret
}");
}
[WorkItem(542466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542466")]
[Fact]
public void CS0184WRN_IsAlwaysFalse_ExplicitEnumeration()
{
var text = @"
class IsTest
{
static void Main()
{
var b = default(color) is int;
System.Console.WriteLine(b);
}
}
enum color
{ }
";
var comp = CompileAndVerify(text, expectedOutput: "False");
comp.VerifyDiagnostics(
// (6,17): warning CS0184: The given expression is never of the provided ('int') type
// var b = default(color) is int;
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "default(color) is int").WithArguments("int"));
comp.VerifyIL("IsTest.Main", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: call ""void System.Console.WriteLine(bool)""
IL_0006: ret
}");
}
[WorkItem(542466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542466")]
[Fact]
public void CS0184WRN_IsAlwaysFalse_ImplicitNumeric()
{
var text = @"
class IsTest
{
static void Main()
{
var b = 1 is double;
System.Console.WriteLine(b);
}
}
";
var comp = CompileAndVerify(text, expectedOutput: "False");
comp.VerifyDiagnostics(
// (6,17): warning CS0184: The given expression is never of the provided ('double') type
// var b = 1 is double;
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "1 is double").WithArguments("double"));
comp.VerifyIL("IsTest.Main", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: call ""void System.Console.WriteLine(bool)""
IL_0006: ret
}");
}
[Fact, WorkItem(542466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542466")]
public void CS0184WRN_IsAlwaysFalse_ExplicitNumeric()
{
var text = @"
class IsTest
{
static void Main()
{
var b = 1.0 is int;
System.Console.WriteLine(b);
b = 1.0 is float;
System.Console.WriteLine(b);
b = 1 is byte;
System.Console.WriteLine(b);
}
}
";
var comp = CompileAndVerify(text, expectedOutput: @"False
False
False");
comp.VerifyDiagnostics(
// (6,17): warning CS0184: The given expression is never of the provided ('int') type
// var b = 1.0 is int;
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "1.0 is int").WithArguments("int"),
// (7,13): warning CS0184: The given expression is never of the provided ('float') type
// b = 1.0 is float;
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "1.0 is float").WithArguments("float"),
// (8,13): warning CS0184: The given expression is never of the provided ('byte') type
// b = 1 is byte;
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "1 is byte").WithArguments("byte"));
comp.VerifyIL("IsTest.Main", @"
{
// Code size 19 (0x13)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: call ""void System.Console.WriteLine(bool)""
IL_0006: ldc.i4.0
IL_0007: call ""void System.Console.WriteLine(bool)""
IL_000c: ldc.i4.0
IL_000d: call ""void System.Console.WriteLine(bool)""
IL_0012: ret
}");
}
[Fact, WorkItem(546371, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546371")]
public void CS0184WRN_IsAlwaysFalse_NumericIsNullable()
{
#region src
var text = @"using System;
public class Test
{
const char v0 = default(char);
public static sbyte v1 = default(sbyte);
internal static byte v2 = 0;// default(byte);
protected static short v3 = 0; // default(short);
private static ushort v4 = default(ushort);
static void Main()
{
const int v5 = 0; // default(int);
uint v6 = 0; // default(uint);
long v7 = 0; // default(long);
const ulong v8 = default(ulong);
float v9 = default(float);
// char
if (v0 is ushort?)
Console.Write(0);
else
Console.Write(1);
// sbyte & byte
if (v1 is short? || v2 is short?)
Console.Write(0);
else
Console.Write(2);
// short & ushort
if (v3 is int? || v4 is int?)
Console.Write(0);
else
Console.Write(3);
// int & uint
if (v5 is long? || v6 is long?)
Console.Write(0);
else
Console.Write(4);
// long & ulong
if (v7 is float? || v8 is float?)
Console.Write(0);
else
Console.Write(5);
// float
if (v9 is int?)
Console.Write(0);
else
Console.Write(6);
}
}
";
#endregion
var comp = CompileAndVerify(text, expectedOutput: @"123456");
comp.VerifyDiagnostics(
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "v0 is ushort?").WithArguments("ushort?"),
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "v1 is short?").WithArguments("short?"),
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "v2 is short?").WithArguments("short?"),
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "v3 is int?").WithArguments("int?"),
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "v4 is int?").WithArguments("int?"),
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "v5 is long?").WithArguments("long?"),
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "v6 is long?").WithArguments("long?"),
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "v7 is float?").WithArguments("float?"),
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "v8 is float?").WithArguments("float?"),
Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "v9 is int?").WithArguments("int?")
);
comp.VerifyIL("Test.Main", @"
{
// Code size 61 (0x3d)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: call ""void System.Console.Write(int)""
IL_0006: ldsfld ""sbyte Test.v1""
IL_000b: pop
IL_000c: ldsfld ""byte Test.v2""
IL_0011: pop
IL_0012: ldc.i4.2
IL_0013: call ""void System.Console.Write(int)""
IL_0018: ldsfld ""short Test.v3""
IL_001d: pop
IL_001e: ldsfld ""ushort Test.v4""
IL_0023: pop
IL_0024: ldc.i4.3
IL_0025: call ""void System.Console.Write(int)""
IL_002a: ldc.i4.4
IL_002b: call ""void System.Console.Write(int)""
IL_0030: ldc.i4.5
IL_0031: call ""void System.Console.Write(int)""
IL_0036: ldc.i4.6
IL_0037: call ""void System.Console.Write(int)""
IL_003c: ret
}
");
}
// TODO: Add VerifyIL for is and as Codegen tests
[Fact]
public void TestAsOperator()
{
var source = @"
namespace TestAsOperator
{
public interface MyInter {}
public class TestType : MyInter {}
public class AnotherType {}
public class MyBase {}
public class MyDerived : MyBase { }
public class C
{
static void Main()
{
string myStr = ""goo"";
object o = myStr;
object b = o as string;
TestType tt = null;
o = tt;
b = o as TestType;
tt = new TestType();
o = tt;
b = o as AnotherType;
b = o as MyInter;
MyInter mi = new TestType();
o = mi;
b = o as MyInter;
MyBase mb = new MyBase();
o = mb;
b = o as MyDerived;
MyDerived md = new MyDerived();
o = md;
b = o as MyBase;
b = null as MyBase;
}
}
}
";
var compilation = CompileAndVerify(source);
}
[Fact]
public void TestAsOperatorGeneric()
{
var source = @"
public class TestAsOperatorGeneric
{
public static void Main() { }
public static void M<T, U, W>(T t, U u, W w)
where T : class
where U : class
where W : class
{
object test2 = u as object;
System.Console.WriteLine(test2);
U test3 = t as U;
System.Console.WriteLine(test3);
T test4 = t as T;
System.Console.WriteLine(test4);
U test5 = u as U;
System.Console.WriteLine(test5);
T test12 = u as T;
System.Console.WriteLine(test12);
object test7 = w as object;
System.Console.WriteLine(test7);
U test8 = w as U;
System.Console.WriteLine(test8);
W test9 = u as W;
System.Console.WriteLine(test9);
W test10 = t as W;
System.Console.WriteLine(test10);
W test11 = w as W;
System.Console.WriteLine(test11);
}
}
";
var compilation = CompileAndVerify(source);
compilation.VerifyIL("TestAsOperatorGeneric.M<T, U, W>(T, U, W)",
@"{
// Code size 186 (0xba)
.maxstack 1
IL_0000: ldarg.1
IL_0001: box ""U""
IL_0006: call ""void System.Console.WriteLine(object)""
IL_000b: ldarg.0
IL_000c: box ""T""
IL_0011: isinst ""U""
IL_0016: unbox.any ""U""
IL_001b: box ""U""
IL_0020: call ""void System.Console.WriteLine(object)""
IL_0025: ldarg.0
IL_0026: box ""T""
IL_002b: call ""void System.Console.WriteLine(object)""
IL_0030: ldarg.1
IL_0031: box ""U""
IL_0036: call ""void System.Console.WriteLine(object)""
IL_003b: ldarg.1
IL_003c: box ""U""
IL_0041: isinst ""T""
IL_0046: unbox.any ""T""
IL_004b: box ""T""
IL_0050: call ""void System.Console.WriteLine(object)""
IL_0055: ldarg.2
IL_0056: box ""W""
IL_005b: call ""void System.Console.WriteLine(object)""
IL_0060: ldarg.2
IL_0061: box ""W""
IL_0066: isinst ""U""
IL_006b: unbox.any ""U""
IL_0070: box ""U""
IL_0075: call ""void System.Console.WriteLine(object)""
IL_007a: ldarg.1
IL_007b: box ""U""
IL_0080: isinst ""W""
IL_0085: unbox.any ""W""
IL_008a: box ""W""
IL_008f: call ""void System.Console.WriteLine(object)""
IL_0094: ldarg.0
IL_0095: box ""T""
IL_009a: isinst ""W""
IL_009f: unbox.any ""W""
IL_00a4: box ""W""
IL_00a9: call ""void System.Console.WriteLine(object)""
IL_00ae: ldarg.2
IL_00af: box ""W""
IL_00b4: call ""void System.Console.WriteLine(object)""
IL_00b9: ret
}");
}
[Fact, WorkItem(754408, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754408")]
public void TestNullCoalesce_DynamicAndObject()
{
var source = @"using System;
public class A {}
public class C
{
public static dynamic Get()
{
object a = new A();
dynamic b = new A();
return a ?? b;
}
public static void Main()
{
var c = Get();
}
}";
var comp = CompileAndVerify(source,
references: new[] { CSharpRef },
expectedOutput: string.Empty);
comp.VerifyIL("C.Get",
@"{
// Code size 17 (0x11)
.maxstack 2
.locals init (object V_0) //b
IL_0000: newobj ""A..ctor()""
IL_0005: newobj ""A..ctor()""
IL_000a: stloc.0
IL_000b: dup
IL_000c: brtrue.s IL_0010
IL_000e: pop
IL_000f: ldloc.0
IL_0010: ret
}");
}
[Fact]
public void TestNullCoalesce_Implicit_b_To_a_nullable()
{
var source = @"
using System;
// a ?? b
public class E : D { }
public class D { }
public class C
{
public static int Main()
{
Nullable_a_Implicit_b_to_a0_null_a('a');
Nullable_a_Implicit_b_to_a0_constant_non_null_a('a');
Nullable_a_Implicit_b_to_a0_not_null_a('a', 10);
return 0;
}
public static int Nullable_a_Implicit_b_to_a0_null_a(char ch)
{
char b = ch;
int? a = null;
int z = a ?? b;
return z;
}
public static int Nullable_a_Implicit_b_to_a0_constant_non_null_a(char ch)
{
char b = ch;
int? a = 10;
int z = a ?? b;
return z;
}
public static int Nullable_a_Implicit_b_to_a0_not_null_a(char ch, int? i)
{
char b = ch;
int? a = i;
int z = a ?? b;
return z;
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: string.Empty);
compilation.VerifyIL("C.Nullable_a_Implicit_b_to_a0_null_a", @"
{
// Code size 31 (0x1f)
.maxstack 1
.locals init (char V_0, //b
int? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_1
IL_0004: initobj ""int?""
IL_000a: ldloc.1
IL_000b: stloc.1
IL_000c: ldloca.s V_1
IL_000e: call ""bool int?.HasValue.get""
IL_0013: brtrue.s IL_0017
IL_0015: ldloc.0
IL_0016: ret
IL_0017: ldloca.s V_1
IL_0019: call ""int int?.GetValueOrDefault()""
IL_001e: ret
}
");
compilation.VerifyIL("C.Nullable_a_Implicit_b_to_a0_constant_non_null_a", @"
{
// Code size 29 (0x1d)
.maxstack 1
.locals init (char V_0, //b
int? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldc.i4.s 10
IL_0004: newobj ""int?..ctor(int)""
IL_0009: stloc.1
IL_000a: ldloca.s V_1
IL_000c: call ""bool int?.HasValue.get""
IL_0011: brtrue.s IL_0015
IL_0013: ldloc.0
IL_0014: ret
IL_0015: ldloca.s V_1
IL_0017: call ""int int?.GetValueOrDefault()""
IL_001c: ret
}");
compilation.VerifyIL("C.Nullable_a_Implicit_b_to_a0_not_null_a", @"
{
// Code size 23 (0x17)
.maxstack 1
.locals init (char V_0, //b
int? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldarg.1
IL_0003: stloc.1
IL_0004: ldloca.s V_1
IL_0006: call ""bool int?.HasValue.get""
IL_000b: brtrue.s IL_000f
IL_000d: ldloc.0
IL_000e: ret
IL_000f: ldloca.s V_1
IL_0011: call ""int int?.GetValueOrDefault()""
IL_0016: ret
}
");
}
[Fact]
public void TestNullCoalesce_Nullable_a_Implicit_b_to_a0()
{
var source = @"
using System;
// a ?? b
public class E : D { }
public class D { }
public class C
{
public static int Main()
{
Nullable_a_Implicit_b_to_a0_null_a('a');
Nullable_a_Implicit_b_to_a0_constant_non_null_a('a');
Nullable_a_Implicit_b_to_a0_not_null_a('a', 10);
Nullable_a_Implicit_b_to_a_null_a('a');
Nullable_a_Implicit_b_to_a_constant_non_null_a('a');
Nullable_a_Implicit_b_to_a_not_null_a('a', 10);
return 0;
}
public static int Nullable_a_Implicit_b_to_a0_null_a(char ch)
{
char b = ch;
int? a = null;
int z = a ?? b;
return z;
}
public static int Nullable_a_Implicit_b_to_a0_constant_non_null_a(char ch)
{
char b = ch;
int? a = 10;
int z = a ?? b;
return z;
}
public static int Nullable_a_Implicit_b_to_a0_not_null_a(char ch, int? i)
{
char b = ch;
int? a = i;
int z = a ?? b;
return z;
}
public static int? Nullable_a_Implicit_b_to_a_null_a(char? ch)
{
char? b = ch;
int? a = null;
int? z = a ?? b;
return z;
}
public static int? Nullable_a_Implicit_b_to_a_constant_non_null_a(char? ch)
{
char? b = ch;
int? a = 10;
int? z = a ?? b;
return z;
}
public static int? Nullable_a_Implicit_b_to_a_not_null_a(char ch, int? i)
{
char? b = ch;
int? a = i;
int? z = a ?? b;
return z;
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: string.Empty);
compilation.VerifyIL("C.Nullable_a_Implicit_b_to_a0_null_a", @"
{
// Code size 31 (0x1f)
.maxstack 1
.locals init (char V_0, //b
int? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_1
IL_0004: initobj ""int?""
IL_000a: ldloc.1
IL_000b: stloc.1
IL_000c: ldloca.s V_1
IL_000e: call ""bool int?.HasValue.get""
IL_0013: brtrue.s IL_0017
IL_0015: ldloc.0
IL_0016: ret
IL_0017: ldloca.s V_1
IL_0019: call ""int int?.GetValueOrDefault()""
IL_001e: ret
}");
}
[Fact]
public void TestNullCoalesce_Nullable_a_ImplicitReference_a_to_b()
{
var source = @"
using System;
// a ?? b
public class E : D { }
public class D { }
public class C
{
public static int Main()
{
ImplicitReference_a_to_b_null_a_nullable(10);
ImplicitReference_a_to_b_constant_nonnull_a_nullable(10);
ImplicitReference_a_to_b_not_null_a_nullable(10, 'a');
Null_Literal_a('a');
return 0;
}
public static int? ImplicitReference_a_to_b_null_a_nullable(int? c)
{
int? b = c;
char? a = null;
int? z = a ?? b;
return z;
}
public static int? ImplicitReference_a_to_b_constant_nonnull_a_nullable(int? c)
{
int? b = c;
char? a = 'a';
int? z = a ?? b;
return z;
}
public static int? ImplicitReference_a_to_b_not_null_a_nullable(int? c, char? d)
{
int? b = c;
char? a = d;
int? z = a ?? b;
return z;
}
public static char? Null_Literal_a(char? ch)
{
char? b = ch;
char? z = null ?? b;
return z;
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: string.Empty);
compilation.VerifyIL("C.ImplicitReference_a_to_b_null_a_nullable", @"
{
// Code size 36 (0x24)
.maxstack 1
.locals init (int? V_0, //b
char? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_1
IL_0004: initobj ""char?""
IL_000a: ldloc.1
IL_000b: stloc.1
IL_000c: ldloca.s V_1
IL_000e: call ""bool char?.HasValue.get""
IL_0013: brtrue.s IL_0017
IL_0015: ldloc.0
IL_0016: ret
IL_0017: ldloca.s V_1
IL_0019: call ""char char?.GetValueOrDefault()""
IL_001e: newobj ""int?..ctor(int)""
IL_0023: ret
}");
compilation.VerifyIL("C.Null_Literal_a", @"
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}");
}
[Fact]
public void TestNullCoalesce_ImplicitReference_a_to_b()
{
var source = @"
using System;
// a ?? b
public class E : D { }
public class D { }
public class C
{
public static int Main()
{
ImplicitReference_a_to_b_null_a();
ImplicitReference_a_to_b_not_null_a();
return 0;
}
public static D ImplicitReference_a_to_b_null_a()
{
D b = new D();
E a = null;
D z = a ?? b;
return z;
}
public static D ImplicitReference_a_to_b_not_null_a()
{
D b = new D();
E a = new E();
D z = a ?? b;
return z;
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: string.Empty);
compilation.VerifyIL("C.ImplicitReference_a_to_b_null_a", @"
{
// Code size 13 (0xd)
.maxstack 2
.locals init (D V_0) //b
IL_0000: newobj ""D..ctor()""
IL_0005: stloc.0
IL_0006: ldnull
IL_0007: dup
IL_0008: brtrue.s IL_000c
IL_000a: pop
IL_000b: ldloc.0
IL_000c: ret
}
");
compilation.VerifyIL("C.ImplicitReference_a_to_b_not_null_a",
@"
{
// Code size 17 (0x11)
.maxstack 2
.locals init (D V_0) //b
IL_0000: newobj ""D..ctor()""
IL_0005: stloc.0
IL_0006: newobj ""E..ctor()""
IL_000b: dup
IL_000c: brtrue.s IL_0010
IL_000e: pop
IL_000f: ldloc.0
IL_0010: ret
}
");
}
[Fact]
public void TestNullCoalesce_TypeParameter()
{
var source = @"
using System;
static class Program
{
static void Main()
{
Goo(default, 1000);
Goo(1, 1000);
Goo(default, ""String parameter 1"");
Goo(""String parameter 2"", ""Should not print"");
Goo((int?)null, 4);
Goo((int?)5, 1000);
Goo2(6, 1000);
Goo2<int?, object>(null, 7);
Goo2<int?, object>(8, 1000);
Goo2<int?, int?>(9, 1000);
Goo2<int?, int?>(null, 10);
}
static void Goo<T>(T x1, T x2)
{
Console.WriteLine(x1 ?? x2);
}
static void Goo2<T1, T2>(T1 t1, T2 t2, dynamic d = null) where T1 : T2
{
// Verifying no type errors
Console.WriteLine(t1 ?? t2);
dynamic d2 = t1 ?? d;
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"
0
1
String parameter 1
String parameter 2
4
5
6
7
8
9
10
");
comp.VerifyIL("Program.Goo<T>(T, T)", expectedIL: @"
{
// Code size 25 (0x19)
.maxstack 1
.locals init (T V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: box ""T""
IL_0008: brtrue.s IL_000d
IL_000a: ldarg.1
IL_000b: br.s IL_000e
IL_000d: ldloc.0
IL_000e: box ""T""
IL_0013: call ""void System.Console.WriteLine(object)""
IL_0018: ret
}
");
comp.VerifyIL("Program.Goo2<T1, T2>(T1, T2, dynamic)", expectedIL: @"
{
// Code size 44 (0x2c)
.maxstack 1
.locals init (T1 V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: box ""T1""
IL_0008: brtrue.s IL_000d
IL_000a: ldarg.1
IL_000b: br.s IL_0018
IL_000d: ldloc.0
IL_000e: box ""T1""
IL_0013: unbox.any ""T2""
IL_0018: box ""T2""
IL_001d: call ""void System.Console.WriteLine(object)""
IL_0022: ldarg.0
IL_0023: stloc.0
IL_0024: ldloc.0
IL_0025: box ""T1""
IL_002a: pop
IL_002b: ret
}
");
}
[Fact]
public void TestNullCoalesce_TypeParameter_DefaultLHS()
{
var source = @"
using System;
static class Program
{
static void Main()
{
Goo(10);
Goo(""String parameter"");
Goo((int?)3);
}
static void Goo<T>(T x)
{
Console.WriteLine(default(T) ?? x);
}
}
";
var comp = CompileAndVerify(source, expectedOutput: @"
0
String parameter
3
");
comp.VerifyIL("Program.Goo<T>(T)", expectedIL: @"
{
// Code size 31 (0x1f)
.maxstack 1
.locals init (T V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj ""T""
IL_0008: ldloc.0
IL_0009: box ""T""
IL_000e: brtrue.s IL_0013
IL_0010: ldarg.0
IL_0011: br.s IL_0014
IL_0013: ldloc.0
IL_0014: box ""T""
IL_0019: call ""void System.Console.WriteLine(object)""
IL_001e: ret
}
");
}
[Fact]
public void TestNullCoalesce_NoDuplicateCallsToGoo()
{
var source = @"
// a ?? b
public class Test
{
static void Main()
{
object o = Goo() ?? Bar();
}
static object Goo()
{
System.Console.Write(""Goo"");
return new object();
}
static object Bar()
{
System.Console.Write(""Bar"");
return new object();
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "Goo");
compilation.VerifyIL("Test.Main", @"
{
// Code size 14 (0xe)
.maxstack 1
IL_0000: call ""object Test.Goo()""
IL_0005: brtrue.s IL_000d
IL_0007: call ""object Test.Bar()""
IL_000c: pop
IL_000d: ret
}
");
}
[WorkItem(541232, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541232")]
[Fact]
public void TestNullCoalesce_MethodGroups()
{
var source =
@"class C
{
static void M()
{
System.Action a = null;
a = a ?? M;
a = M ?? a;
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (7,13): error CS0019: Operator '??' cannot be applied to operands of type 'method group' and 'System.Action'
Diagnostic(ErrorCode.ERR_BadBinaryOps, "M ?? a").WithArguments("??", "method group", "System.Action").WithLocation(7, 13));
}
/// <summary>
/// From orcas bug #42645. PEVerify fails.
/// </summary>
[Fact]
public void TestNullCoalesce_InterfaceRegression1()
{
var source = @"
using System.Collections.Generic;
using System.Security;
[assembly: SecurityTransparent()]
public class Test
{
static void Main()
{
int[] a = new int[] { };
List<int> b = new List<int>();
IEnumerable<int> c = a ?? (IEnumerable<int>)b;
Goo(c);
}
static void Goo<T>(T x)
{
System.Console.WriteLine(typeof(T));
}
}";
// Note the explicit casts, even though the conversions are
// implicit reference conversions.
var comp = CompileAndVerify(source, expectedOutput: "System.Collections.Generic.IEnumerable`1[System.Int32]");
comp.VerifyDiagnostics();
comp.VerifyIL("Test.Main", @"
{
// Code size 25 (0x19)
.maxstack 2
.locals init (System.Collections.Generic.List<int> V_0, //b
System.Collections.Generic.IEnumerable<int> V_1)
IL_0000: ldc.i4.0
IL_0001: newarr ""int""
IL_0006: newobj ""System.Collections.Generic.List<int>..ctor()""
IL_000b: stloc.0
IL_000c: stloc.1
IL_000d: ldloc.1
IL_000e: dup
IL_000f: brtrue.s IL_0013
IL_0011: pop
IL_0012: ldloc.0
IL_0013: call ""void Test.Goo<System.Collections.Generic.IEnumerable<int>>(System.Collections.Generic.IEnumerable<int>)""
IL_0018: ret
}
");
}
[Fact]
public void TestNullCoalesce_InterfaceRegression1a()
{
var source = @"
using System.Collections.Generic;
public class Test
{
static void Main()
{
int[] a = new int[] { };
IEnumerable<int> b = new List<int>();
IEnumerable<int> c = b ?? a;
Goo(c);
}
static void Goo<T>(T x)
{
System.Console.WriteLine(typeof(T));
}
}";
var comp = CompileAndVerify(source, expectedOutput: "System.Collections.Generic.IEnumerable`1[System.Int32]");
comp.VerifyDiagnostics();
comp.VerifyIL("Test.Main", @"
{
// Code size 25 (0x19)
.maxstack 2
.locals init (int[] V_0, //a
System.Collections.Generic.IEnumerable<int> V_1)
IL_0000: ldc.i4.0
IL_0001: newarr ""int""
IL_0006: stloc.0
IL_0007: newobj ""System.Collections.Generic.List<int>..ctor()""
IL_000c: stloc.1
IL_000d: ldloc.1
IL_000e: dup
IL_000f: brtrue.s IL_0013
IL_0011: pop
IL_0012: ldloc.0
IL_0013: call ""void Test.Goo<System.Collections.Generic.IEnumerable<int>>(System.Collections.Generic.IEnumerable<int>)""
IL_0018: ret
}");
}
[Fact]
public void TestNullCoalesce_InterfaceRegression1b()
{
var source = @"
using System.Collections.Generic;
public class Test
{
static void Main()
{
int[] a = new int[] { };
IEnumerable<int> b;
IEnumerable<int> c = (b = (IEnumerable<int>)new List<int>()) ?? a;
Goo(c);
Goo(b);
}
static void Goo<T>(T x)
{
System.Console.Write(typeof(T));
}
}";
var comp = CompileAndVerify(source, expectedOutput: "System.Collections.Generic.IEnumerable`1[System.Int32]System.Collections.Generic.IEnumerable`1[System.Int32]");
comp.VerifyDiagnostics();
comp.VerifyIL("Test.Main", @"
{
// Code size 31 (0x1f)
.maxstack 3
.locals init (int[] V_0, //a
System.Collections.Generic.IEnumerable<int> V_1)
IL_0000: ldc.i4.0
IL_0001: newarr ""int""
IL_0006: stloc.0
IL_0007: newobj ""System.Collections.Generic.List<int>..ctor()""
IL_000c: dup
IL_000d: stloc.1
IL_000e: ldloc.1
IL_000f: dup
IL_0010: brtrue.s IL_0014
IL_0012: pop
IL_0013: ldloc.0
IL_0014: call ""void Test.Goo<System.Collections.Generic.IEnumerable<int>>(System.Collections.Generic.IEnumerable<int>)""
IL_0019: call ""void Test.Goo<System.Collections.Generic.IEnumerable<int>>(System.Collections.Generic.IEnumerable<int>)""
IL_001e: ret
}");
}
[Fact]
public void TestNullCoalesce_InterfaceRegression1c()
{
var source = @"
using System.Collections.Generic;
public class Test
{
static void Main()
{
int[] a = new int[] { };
IEnumerable<int> b = new List<int>();
Goo(b, b ?? a);
}
static void Goo<T, U>(T x, U y)
{
System.Console.Write(typeof(T));
}
}";
var comp = CompileAndVerify(source, expectedOutput: "System.Collections.Generic.IEnumerable`1[System.Int32]");
comp.VerifyDiagnostics();
comp.VerifyIL("Test.Main", @"
{
// Code size 26 (0x1a)
.maxstack 3
.locals init (int[] V_0, //a
System.Collections.Generic.IEnumerable<int> V_1)
IL_0000: ldc.i4.0
IL_0001: newarr ""int""
IL_0006: stloc.0
IL_0007: newobj ""System.Collections.Generic.List<int>..ctor()""
IL_000c: dup
IL_000d: stloc.1
IL_000e: ldloc.1
IL_000f: dup
IL_0010: brtrue.s IL_0014
IL_0012: pop
IL_0013: ldloc.0
IL_0014: call ""void Test.Goo<System.Collections.Generic.IEnumerable<int>, System.Collections.Generic.IEnumerable<int>>(System.Collections.Generic.IEnumerable<int>, System.Collections.Generic.IEnumerable<int>)""
IL_0019: ret
}
");
}
/// <summary>
/// From whidbey bug #49619. PEVerify fails.
/// </summary>
/// <remarks>
/// Dev10 does not produce verifiable code for this example.
/// </remarks>
[Fact]
public void TestNullCoalesce_InterfaceRegression2()
{
var source = @"
public interface IA { }
public interface IB { int f(); }
public class AB1 : IA, IB { public int f() { return 42; } }
public class AB2 : IA, IB { public int f() { return 1; } }
class MainClass
{
public static void g(AB1 ab1)
{
((IB)ab1 ?? (IB)new AB2()).f();
}
}";
// Note the explicit casts, even though the conversions are
// implicit reference conversions.
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("MainClass.g", @"
{
// Code size 19 (0x13)
.maxstack 2
.locals init (IB V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: dup
IL_0004: brtrue.s IL_000c
IL_0006: pop
IL_0007: newobj ""AB2..ctor()""
IL_000c: callvirt ""int IB.f()""
IL_0011: pop
IL_0012: ret
}");
}
[Fact, WorkItem(638289, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/638289")]
public void TestNullCoalesce_Nested()
{
var src =
@"interface I { void DoNothing(); }
class A : I { public void DoNothing() {} }
class B : I { public void DoNothing() {} }
class C : I
{
public void DoNothing() {}
static I Tester(A a, B b)
{
I i = a ?? (b ?? (I)new C());
i.DoNothing();
i = a ?? ((I)b ?? new C());
i.DoNothing();
i = ((I)a ?? b) ?? new C();
i.DoNothing();
return i;
}
static void Main()
{
System.Console.Write(Tester(null, null).GetType());
}
}";
var verify = CompileAndVerify(src,
options: TestOptions.DebugExe, expectedOutput: "C");
verify.VerifyIL("C.Tester", @"
{
// Code size 86 (0x56)
.maxstack 2
.locals init (I V_0, //i
I V_1,
I V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.1
IL_0003: ldloc.1
IL_0004: dup
IL_0005: brtrue.s IL_0014
IL_0007: pop
IL_0008: ldarg.1
IL_0009: stloc.1
IL_000a: ldloc.1
IL_000b: dup
IL_000c: brtrue.s IL_0014
IL_000e: pop
IL_000f: newobj ""C..ctor()""
IL_0014: stloc.0
IL_0015: ldloc.0
IL_0016: callvirt ""void I.DoNothing()""
IL_001b: nop
IL_001c: ldarg.0
IL_001d: stloc.1
IL_001e: ldloc.1
IL_001f: dup
IL_0020: brtrue.s IL_002f
IL_0022: pop
IL_0023: ldarg.1
IL_0024: stloc.1
IL_0025: ldloc.1
IL_0026: dup
IL_0027: brtrue.s IL_002f
IL_0029: pop
IL_002a: newobj ""C..ctor()""
IL_002f: stloc.0
IL_0030: ldloc.0
IL_0031: callvirt ""void I.DoNothing()""
IL_0036: nop
IL_0037: ldarg.0
IL_0038: stloc.1
IL_0039: ldloc.1
IL_003a: dup
IL_003b: brtrue.s IL_003f
IL_003d: pop
IL_003e: ldarg.1
IL_003f: dup
IL_0040: brtrue.s IL_0048
IL_0042: pop
IL_0043: newobj ""C..ctor()""
IL_0048: stloc.0
IL_0049: ldloc.0
IL_004a: callvirt ""void I.DoNothing()""
IL_004f: nop
IL_0050: ldloc.0
IL_0051: stloc.2
IL_0052: br.s IL_0054
IL_0054: ldloc.2
IL_0055: ret
}");
// Optimized
verify = CompileAndVerify(src, expectedOutput: "C");
verify.VerifyIL("C.Tester", @"
{
// Code size 72 (0x48)
.maxstack 2
.locals init (I V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: dup
IL_0004: brtrue.s IL_0013
IL_0006: pop
IL_0007: ldarg.1
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: dup
IL_000b: brtrue.s IL_0013
IL_000d: pop
IL_000e: newobj ""C..ctor()""
IL_0013: callvirt ""void I.DoNothing()""
IL_0018: ldarg.0
IL_0019: stloc.0
IL_001a: ldloc.0
IL_001b: dup
IL_001c: brtrue.s IL_002b
IL_001e: pop
IL_001f: ldarg.1
IL_0020: stloc.0
IL_0021: ldloc.0
IL_0022: dup
IL_0023: brtrue.s IL_002b
IL_0025: pop
IL_0026: newobj ""C..ctor()""
IL_002b: callvirt ""void I.DoNothing()""
IL_0030: ldarg.0
IL_0031: stloc.0
IL_0032: ldloc.0
IL_0033: dup
IL_0034: brtrue.s IL_0038
IL_0036: pop
IL_0037: ldarg.1
IL_0038: dup
IL_0039: brtrue.s IL_0041
IL_003b: pop
IL_003c: newobj ""C..ctor()""
IL_0041: dup
IL_0042: callvirt ""void I.DoNothing()""
IL_0047: ret
}");
}
[Fact]
public void TestNullCoalesce_FuncVariance()
{
var source = @"
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
Func<Exception[]> f1 = null;
Func<IEnumerable<object>> f2 = null;
var oo = f1 ?? f2;
Console.WriteLine(oo);
oo = f2 ?? f1;
Console.WriteLine(oo);
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"
{
// Code size 31 (0x1f)
.maxstack 2
.locals init (System.Func<System.Exception[]> V_0, //f1
System.Func<System.Collections.Generic.IEnumerable<object>> V_1, //f2
System.Func<System.Collections.Generic.IEnumerable<object>> V_2)
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldnull
IL_0003: stloc.1
IL_0004: ldloc.0
IL_0005: stloc.2
IL_0006: ldloc.2
IL_0007: dup
IL_0008: brtrue.s IL_000c
IL_000a: pop
IL_000b: ldloc.1
IL_000c: call ""void System.Console.WriteLine(object)""
IL_0011: ldloc.1
IL_0012: dup
IL_0013: brtrue.s IL_0019
IL_0015: pop
IL_0016: ldloc.0
IL_0017: stloc.2
IL_0018: ldloc.2
IL_0019: call ""void System.Console.WriteLine(object)""
IL_001e: ret
}
");
}
[Fact]
public void TestNullCoalesce_FuncVariance01()
{
var source = @"
using System;
using System.Collections;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
Func<Exception[]> f1 = null;
Func<IEnumerable<object>> f2 = null;
var oo = (Func<IEnumerable>)f1 ?? (Func<IEnumerable>)f2;
Console.WriteLine(oo);
oo = (Func<IEnumerable>)f2 ?? (Func<IEnumerable>)f1;
Console.WriteLine(oo);
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"
{
// Code size 35 (0x23)
.maxstack 2
.locals init (System.Func<System.Exception[]> V_0, //f1
System.Func<System.Collections.Generic.IEnumerable<object>> V_1, //f2
System.Func<System.Collections.IEnumerable> V_2)
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldnull
IL_0003: stloc.1
IL_0004: ldloc.0
IL_0005: stloc.2
IL_0006: ldloc.2
IL_0007: dup
IL_0008: brtrue.s IL_000e
IL_000a: pop
IL_000b: ldloc.1
IL_000c: stloc.2
IL_000d: ldloc.2
IL_000e: call ""void System.Console.WriteLine(object)""
IL_0013: ldloc.1
IL_0014: stloc.2
IL_0015: ldloc.2
IL_0016: dup
IL_0017: brtrue.s IL_001d
IL_0019: pop
IL_001a: ldloc.0
IL_001b: stloc.2
IL_001c: ldloc.2
IL_001d: call ""void System.Console.WriteLine(object)""
IL_0022: ret
}
");
}
[Fact]
public void TestNullCoalesce_InterfaceVariance()
{
var source = @"
using System;
using System.Collections.Generic;
class Program
{
interface CoInter<out T>
{
}
static void Main(string[] args)
{
CoInter<Exception[]> f1 = null;
CoInter<IEnumerable<object>> f2 = null;
var oo = f1 ?? f2;
Console.WriteLine(oo);
oo = f2 ?? f1;
Console.WriteLine(oo);
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"
{
// Code size 31 (0x1f)
.maxstack 2
.locals init (Program.CoInter<System.Exception[]> V_0, //f1
Program.CoInter<System.Collections.Generic.IEnumerable<object>> V_1, //f2
Program.CoInter<System.Collections.Generic.IEnumerable<object>> V_2)
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldnull
IL_0003: stloc.1
IL_0004: ldloc.0
IL_0005: stloc.2
IL_0006: ldloc.2
IL_0007: dup
IL_0008: brtrue.s IL_000c
IL_000a: pop
IL_000b: ldloc.1
IL_000c: call ""void System.Console.WriteLine(object)""
IL_0011: ldloc.1
IL_0012: dup
IL_0013: brtrue.s IL_0019
IL_0015: pop
IL_0016: ldloc.0
IL_0017: stloc.2
IL_0018: ldloc.2
IL_0019: call ""void System.Console.WriteLine(object)""
IL_001e: ret
}
");
}
[Fact]
public void TestNullCoalesce_InterfaceVariance01()
{
var source = @"
using System;
using System.Collections;
using System.Collections.Generic;
class Program
{
interface CoInter<out T>
{
}
static void Main(string[] args)
{
CoInter<Exception[]> f1 = null;
CoInter<IEnumerable<object>> f2 = null;
var oo = (CoInter<IEnumerable>)f1 ?? (CoInter<IEnumerable>)f2;
Console.WriteLine(oo);
oo = (CoInter<IEnumerable>)f2 ?? (CoInter<IEnumerable>)f1;
Console.WriteLine(oo);
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"
{
// Code size 35 (0x23)
.maxstack 2
.locals init (Program.CoInter<System.Exception[]> V_0, //f1
Program.CoInter<System.Collections.Generic.IEnumerable<object>> V_1, //f2
Program.CoInter<System.Collections.IEnumerable> V_2)
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldnull
IL_0003: stloc.1
IL_0004: ldloc.0
IL_0005: stloc.2
IL_0006: ldloc.2
IL_0007: dup
IL_0008: brtrue.s IL_000e
IL_000a: pop
IL_000b: ldloc.1
IL_000c: stloc.2
IL_000d: ldloc.2
IL_000e: call ""void System.Console.WriteLine(object)""
IL_0013: ldloc.1
IL_0014: stloc.2
IL_0015: ldloc.2
IL_0016: dup
IL_0017: brtrue.s IL_001d
IL_0019: pop
IL_001a: ldloc.0
IL_001b: stloc.2
IL_001c: ldloc.2
IL_001d: call ""void System.Console.WriteLine(object)""
IL_0022: ret
}
");
}
[WorkItem(543074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543074")]
[Fact]
public void TestEqualEqualOnNestedStructGuid()
{
var source = @"
using System;
public class Parent
{
public System.Guid Goo(int d = 0, System.Guid g = default(System.Guid)) { return g; }
}
public class Test
{
public static void Main()
{
var x = new Parent().Goo();
var ret = x == default(System.Guid);
Console.Write(ret);
}
}
";
CompileAndVerify(source, expectedOutput: "True");
}
[WorkItem(543092, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543092")]
[Fact]
public void ShortCircuitConditionalOperator()
{
var source = @"
using System;
using System.Linq;
using System.Collections.Generic;
class X
{
public int selectCount = 0;
public bool Select<T>(Func<int, T> selector)
{
selectCount++;
return true;
}
}
class P
{
static int Main()
{
int errCount = 0;
var src = new X();
// QE is not 'executed'
var b = false && from x in src select x;
if (src.selectCount == 1)
errCount++;
Console.Write(errCount);
return (errCount > 0) ? 1 : 0;
}
}";
CompileAndVerify(source, expectedOutput: "0", options: TestOptions.ReleaseExe.WithWarningLevel(5)).VerifyDiagnostics(
// (3,1): hidden CS8019: Unnecessary using directive.
// using System.Linq;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Linq;").WithLocation(3, 1),
// (4,1): hidden CS8019: Unnecessary using directive.
// using System.Collections.Generic;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections.Generic;").WithLocation(4, 1),
// (23,26): warning CS8848: Operator 'from' cannot be used here due to precedence. Use parentheses to disambiguate.
// var b = false && from x in src select x;
Diagnostic(ErrorCode.WRN_PrecedenceInversion, "from x in src").WithArguments("from").WithLocation(23, 26)
);
}
[WorkItem(543109, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543109")]
[Fact()]
public void ShortCircuitConditionalOperator02()
{
var source = @"
using System;
class P
{
static int Main()
{
int errCount = 0;
var f = false;
var b = f && (0 == errCount++);
Console.Write(errCount);
return (errCount > 0) ? 1 : 0;
}
}";
CompileAndVerify(source, expectedOutput: "0");
}
[WorkItem(543377, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543377")]
[Fact]
public void DecimalComparison()
{
var source = @"
class Program
{
static void Main()
{
decimal d1 = 1.0201m;
if (d1 == 10201M)
{
}
}
}";
CompileAndVerify(source).
VerifyIL("Program.Main", @"
{
// Code size 31 (0x1f)
.maxstack 5
IL_0000: ldc.i4 0x27d9
IL_0005: ldc.i4.0
IL_0006: ldc.i4.0
IL_0007: ldc.i4.0
IL_0008: ldc.i4.4
IL_0009: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_000e: ldc.i4 0x27d9
IL_0013: newobj ""decimal..ctor(int)""
IL_0018: call ""bool decimal.op_Equality(decimal, decimal)""
IL_001d: pop
IL_001e: ret
}");
}
[WorkItem(543453, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543453")]
[Fact]
public void TestIncrementDecrementOperator_Generic()
{
var source = @"
using System;
class BaseType<T> where T : BaseType<T>, new()
{
public static T operator ++(BaseType<T> x)
{
return null;
}
public static implicit operator T(BaseType<T> x)
{
return null;
}
}
class DrivedType : BaseType<DrivedType>
{
public static void Main()
{
BaseType<DrivedType> test = new BaseType<DrivedType>();
DrivedType test2 = test++;
}
}
";
CompileAndVerify(source);
}
[WorkItem(543474, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543474")]
[Fact]
public void LogicalComplementOperator()
{
var source = @"
class Program
{
static void Main(string[] args)
{
checked
{
var b = false;
if (!b) {System.Console.Write(""1""); }
}
}
}";
CompileAndVerify(source,
expectedOutput: "1");
}
[WorkItem(543500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543500")]
[Fact]
public void BuiltInLeftShiftOperators()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
int i = 1;
uint ui = 1;
long l = 1;
ulong ul = 1;
Console.WriteLine(i << 31);
Console.WriteLine(i << 32);
Console.WriteLine(i << 33);
Console.WriteLine(i << -1);
Console.WriteLine();
Console.WriteLine(ui << 31);
Console.WriteLine(ui << 32);
Console.WriteLine(ui << 33);
Console.WriteLine(ui << -1);
Console.WriteLine();
Console.WriteLine(l << 63);
Console.WriteLine(l << 64);
Console.WriteLine(l << 65);
Console.WriteLine(l << -1);
Console.WriteLine();
Console.WriteLine(ul << 63);
Console.WriteLine(ul << 64);
Console.WriteLine(ul << 65);
Console.WriteLine(ul << -1);
Console.WriteLine();
}
}";
CompileAndVerify(source,
expectedOutput: @"
-2147483648
1
2
-2147483648
2147483648
1
2
2147483648
-9223372036854775808
1
2
-9223372036854775808
9223372036854775808
1
2
9223372036854775808
");
}
[WorkItem(543500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543500")]
[Fact]
public void BuiltInRightShiftOperators()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
int i = int.MaxValue;
uint ui = uint.MaxValue;
long l = long.MaxValue;
ulong ul = ulong.MaxValue;
Console.WriteLine(i >> 31);
Console.WriteLine(i >> 32);
Console.WriteLine(i >> 33);
Console.WriteLine(i >> -1);
Console.WriteLine();
Console.WriteLine(ui >> 31);
Console.WriteLine(ui >> 32);
Console.WriteLine(ui >> 33);
Console.WriteLine(ui >> -1);
Console.WriteLine();
Console.WriteLine(l >> 63);
Console.WriteLine(l >> 64);
Console.WriteLine(l >> 65);
Console.WriteLine(l >> -1);
Console.WriteLine();
Console.WriteLine(ul >> 63);
Console.WriteLine(ul >> 64);
Console.WriteLine(ul >> 65);
Console.WriteLine(ul >> -1);
Console.WriteLine();
}
}";
CompileAndVerify(source,
expectedOutput: @"
0
2147483647
1073741823
0
1
4294967295
2147483647
1
0
9223372036854775807
4611686018427387903
0
1
18446744073709551615
9223372036854775807
1
");
}
[WorkItem(543500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543500")]
[Fact]
public void BuiltInShiftOperators()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
int i = 1;
long l = long.MaxValue;
int amount = 1;
Console.WriteLine(i << 31); // 31
Console.WriteLine(i << 32); // no shift
Console.WriteLine(i << 33); // 1
Console.WriteLine(i << -1); // 31
Console.WriteLine(i >> amount); // & 31
Console.WriteLine();
Console.WriteLine(l >> 63); // 63
Console.WriteLine(l >> 64); // no shift
Console.WriteLine(l >> 65); // 1
Console.WriteLine(l >> -1); // 63
Console.WriteLine(l >> amount); // & 63
Console.WriteLine();
}
}";
var verifier = CompileAndVerify(source,
expectedOutput: @"
-2147483648
1
2
-2147483648
0
0
9223372036854775807
4611686018427387903
0
4611686018427387903
");
verifier.VerifyIL("Program.Main", @"
{
// Code size 109 (0x6d)
.maxstack 3
.locals init (long V_0, //l
int V_1) //amount
IL_0000: ldc.i4.1
IL_0001: ldc.i8 0x7fffffffffffffff
IL_000a: stloc.0
IL_000b: ldc.i4.1
IL_000c: stloc.1
IL_000d: dup
IL_000e: ldc.i4.s 31
IL_0010: shl
IL_0011: call ""void System.Console.WriteLine(int)""
IL_0016: dup
IL_0017: call ""void System.Console.WriteLine(int)""
IL_001c: dup
IL_001d: ldc.i4.1
IL_001e: shl
IL_001f: call ""void System.Console.WriteLine(int)""
IL_0024: dup
IL_0025: ldc.i4.s 31
IL_0027: shl
IL_0028: call ""void System.Console.WriteLine(int)""
IL_002d: ldloc.1
IL_002e: ldc.i4.s 31
IL_0030: and
IL_0031: shr
IL_0032: call ""void System.Console.WriteLine(int)""
IL_0037: call ""void System.Console.WriteLine()""
IL_003c: ldloc.0
IL_003d: ldc.i4.s 63
IL_003f: shr
IL_0040: call ""void System.Console.WriteLine(long)""
IL_0045: ldloc.0
IL_0046: call ""void System.Console.WriteLine(long)""
IL_004b: ldloc.0
IL_004c: ldc.i4.1
IL_004d: shr
IL_004e: call ""void System.Console.WriteLine(long)""
IL_0053: ldloc.0
IL_0054: ldc.i4.s 63
IL_0056: shr
IL_0057: call ""void System.Console.WriteLine(long)""
IL_005c: ldloc.0
IL_005d: ldloc.1
IL_005e: ldc.i4.s 63
IL_0060: and
IL_0061: shr
IL_0062: call ""void System.Console.WriteLine(long)""
IL_0067: call ""void System.Console.WriteLine()""
IL_006c: ret
}
");
}
[Fact, WorkItem(543993, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543993")]
public void BuiltInShiftOperators01()
{
var source = @"
using System;
public class Test
{
public static void Main()
{
int n = 2;
int v1 = (1 << n) << 3;
int v2 = 1 << n << 3;
Console.Write(""{0}=={1} "", v1, v2);
v1 = (1 >> n) >> 3;
v2 = 1 >> n >> 3;
Console.Write(""{0}=={1}"", v1, v2);
}
}
";
var verifier = CompileAndVerify(source,
expectedOutput: @"32==32 0==0");
verifier.VerifyIL("Test.Main", @"
{
// Code size 83 (0x53)
.maxstack 3
.locals init (int V_0, //n
int V_1, //v1
int V_2) //v2
IL_0000: ldc.i4.2
IL_0001: stloc.0
IL_0002: ldc.i4.1
IL_0003: ldloc.0
IL_0004: ldc.i4.s 31
IL_0006: and
IL_0007: shl
IL_0008: ldc.i4.3
IL_0009: shl
IL_000a: stloc.1
IL_000b: ldc.i4.1
IL_000c: ldloc.0
IL_000d: ldc.i4.s 31
IL_000f: and
IL_0010: shl
IL_0011: ldc.i4.3
IL_0012: shl
IL_0013: stloc.2
IL_0014: ldstr ""{0}=={1} ""
IL_0019: ldloc.1
IL_001a: box ""int""
IL_001f: ldloc.2
IL_0020: box ""int""
IL_0025: call ""void System.Console.Write(string, object, object)""
IL_002a: ldc.i4.1
IL_002b: ldloc.0
IL_002c: ldc.i4.s 31
IL_002e: and
IL_002f: shr
IL_0030: ldc.i4.3
IL_0031: shr
IL_0032: stloc.1
IL_0033: ldc.i4.1
IL_0034: ldloc.0
IL_0035: ldc.i4.s 31
IL_0037: and
IL_0038: shr
IL_0039: ldc.i4.3
IL_003a: shr
IL_003b: stloc.2
IL_003c: ldstr ""{0}=={1}""
IL_0041: ldloc.1
IL_0042: box ""int""
IL_0047: ldloc.2
IL_0048: box ""int""
IL_004d: call ""void System.Console.Write(string, object, object)""
IL_0052: ret
}
");
}
[Fact, WorkItem(543993, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543993")]
public void BuiltInShiftOperators02()
{
var source = @"
class Program
{
static void Main()
{
System.Console.WriteLine(1 << 2 << 3);
System.Console.WriteLine((1 << 2) << 3);
System.Console.WriteLine(1 << (2 << 3));
}
}
";
CompileAndVerify(source, expectedOutput: @"
32
32
65536");
}
[WorkItem(543568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543568")]
[Fact]
public void ImplicitConversionOperatorWithOptionalParam()
{
var source = @"
using System;
public class C
{
static public implicit operator int(C d = null) // warning CS1066
{
if (d != null) return 0;
return 1;
}
}
class TestFunction
{
public static void Main()
{
var tf = new C();
int result = tf;
Console.Write(result);
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"0");
}
[WorkItem(543569, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543569")]
[Fact()]
public void AssignmentInOperandOfIsAlwaysFalse()
{
var source = @"
using System;
public class Program
{
public static void Main()
{
int[] a = null;
bool result = (a = new[] { 4, 5, 6 }) is char[]; // warning CS0184
if (a == null)
{
Console.WriteLine(""FAIL"");
}
else
{
Console.WriteLine(""PASS"");
}
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"PASS");
}
[WorkItem(543577, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543577")]
[Fact()]
public void IsOperatorAlwaysFalseInLambda()
{
var source = @"
using System;
class C
{
static int counter = 0;
public static void Increment()
{
counter++;
}
public static void Main()
{
Func<bool> testExpr = () => Increment() is object; // warning CS0184
Console.WriteLine(counter);
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"0");
}
[WorkItem(543446, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543446"), WorkItem(543446, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543446")]
[Fact]
public void ThrowExceptionByConversion()
{
var source = @"using System;
namespace Test
{
class DException : Exception
{
public static implicit operator DException(Action d)
{
return new DException();
}
}
class Program
{
static void M() { }
static void Main()
{
try
{
throw (DException) M;
}
catch (DException)
{
Console.Write(0);
}
Console.Write(1);
}
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"01");
}
[WorkItem(543586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543586")]
[Fact]
public void ImplicitVsExplicitOverloadOperators()
{
var source = @"using System;
class Test
{
static void Main()
{
Str str = (Str)1;
Console.WriteLine(str.num);
}
}
struct Str
{
public int num;
public static explicit operator Str(int i)
{
Str temp;
temp.num = 10;
return temp;
}
public static implicit operator Str(double i)
{
Str temp;
temp.num = 100;
return temp;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"10");
}
[WorkItem(543602, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543602")]
[WorkItem(543660, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543660")]
[Fact]
public void SwitchExpressionWithImplicitConversion()
{
var source = @"using System;
public class Test
{
public static implicit operator int(Test val)
{
return 1;
}
public static implicit operator float(Test val)
{
return 2.1f;
}
public static int Main()
{
Test t = new Test();
switch (t)
{
case 1:
Console.WriteLine(0);
return 0;
default:
Console.WriteLine(1);
return 1;
}
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"0");
}
[WorkItem(543498, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543498")]
[Fact]
public void UserDefinedConversionAfterUserDefinedIncrement()
{
var source =
@"using System;
class A
{
public static C operator ++(A x)
{
Console.Write('3');
return new C();
}
}
class C : A
{
public static implicit operator B(C x)
{
Console.Write('4');
return new B();
}
}
class B : A
{
static void Main()
{
Console.Write('1');
B b = new B();
Console.Write('2');
b++;
Console.Write('5');
}
}";
CompileAndVerify(source, expectedOutput: "12345");
}
[Fact]
public void TestXor()
{
var source = @"
using System;
class Program
{
static bool t() { return true; }
static bool f() { return false; }
static void write(bool b) { Console.WriteLine(b); }
static void Main(string[] args)
{
write(t() ^ t());
write(t() ^ f());
write(f() ^ t());
write(f() ^ f());
Console.WriteLine(""---"");
write(!(t() ^ t()));
write(!(t() ^ f()));
write(!(f() ^ t()));
write(!(f() ^ f()));
Console.WriteLine(""---"");
write((t() ^ t()) || (t() ^ f()));
write((t() ^ f()) || (t() ^ t()));
write((f() ^ t()) || (f() ^ f()));
write((f() ^ f()) || (t() ^ t()));
Console.WriteLine(""---"");
write((t() ^ t()) && (t() ^ f()));
write((t() ^ f()) && (t() ^ t()));
write((f() ^ t()) && (f() ^ f()));
write((f() ^ f()) && (f() ^ t()));
Console.WriteLine(""---"");
write((t() ^ t()) || !(t() ^ f()));
write((t() ^ f()) || !(t() ^ t()));
write(!(f() ^ t()) || (f() ^ f()));
write(!(f() ^ f()) || (f() ^ t()));
Console.WriteLine(""---"");
write((t() ^ t()) && !(t() ^ f()));
write((t() ^ f()) && !(t() ^ t()));
write(!(f() ^ t()) && (f() ^ f()));
write(!(f() ^ f()) && (f() ^ t()));
}
}
";
string expectedOutput =
@"False
True
True
False
---
True
False
False
True
---
True
True
True
False
---
False
False
False
False
---
False
True
False
True
---
False
True
False
True
";
var compilation = CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void TestXorInIf()
{
var source = @"
using System;
class Program
{
static bool t() { return true; }
static bool f() { return false; }
static void Main(string[] args)
{
if (t() ^ t())
{
Console.WriteLine(""1"");
}
if (!(t() ^ f()))
{
Console.WriteLine(""2"");
}
if (f() ^ t())
{
Console.WriteLine(""3"");
}
if (f() ^ f())
{
Console.WriteLine(""4"");
}
if ((t() ^ f()) && (f() ^ t()))
{
Console.WriteLine(""5"");
}
if ((t() ^ t()) || (t() ^ f()))
{
Console.WriteLine(""6"");
}
if ((t() ^ t()) || (f() ^ f()))
{
Console.WriteLine(""7"");
}
}
}
";
string expectedOutput =
@"3
5
6";
var compilation = CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void XorIl()
{
var text = @"using System;
class MyClass
{
public static bool f = false, t = true;
public static bool r;
public static void Main()
{
r = f ^ t;
r = !(f ^ t);
}
}
";
var comp = CompileAndVerify(text, expectedOutput: "");
comp.VerifyIL("MyClass.Main", @"
{
// Code size 34 (0x22)
.maxstack 2
IL_0000: ldsfld ""bool MyClass.f""
IL_0005: ldsfld ""bool MyClass.t""
IL_000a: xor
IL_000b: stsfld ""bool MyClass.r""
IL_0010: ldsfld ""bool MyClass.f""
IL_0015: ldsfld ""bool MyClass.t""
IL_001a: ceq
IL_001c: stsfld ""bool MyClass.r""
IL_0021: ret
}");
}
[Fact, WorkItem(543446, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543446")]
public void UserDefinedConversionAfterUserDefinedConvert()
{
var source =
@"using System;
delegate void D(int p1);
class DException : Exception
{
public D d;
public static implicit operator DException(D d)
{
DException e = new DException();
e.d = d;
return e;
}
}
class Program
{
static void PM(int p1)
{
}
static void Main()
{
throw (DException)PM;
}
}
";
CompileAndVerify(source);
}
[Fact]
public void UserDefinedOperatorAfterUserDefinedConversion()
{
var source =
@"using System;
class Program
{
public static void Main(string[] args)
{
var c = new C();
var trash = c + c; // which +?
}
}
class C
{
public static string operator +(C c, string s)
{
Console.WriteLine(""+(C,string)"");
return ""+s"";
}
public static string operator +(C c, object o)
{
Console.WriteLine(""+(C,object)"");
return ""+o"";
}
public static implicit operator string(C c)
{
Console.WriteLine(""C->string"");
return ""C->string"";
}
public override string ToString()
{
Console.WriteLine(""C.ToString()"");
return ""C2"";
}
}";
CompileAndVerify(source, expectedOutput:
@"C->string
+(C,string)
");
}
[Fact, WorkItem(529248, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529248")]
public void TestNullCoalescingOperatorWithNullableConversions()
{
// Native compiler violates the language specification while binding the type for the null coalescing operator (??).
// The last bullet in section 7.13 of the specification for binding the type of ?? operator states that:
// SPEC: Otherwise, if b has a type B and an implicit conversion exists from a to B, the result type is B.
// SPEC: At run-time, a is first evaluated. If a is not null, a is unwrapped to type A0 (if A exists and is nullable)
// SPEC: and converted to type B, and this becomes the result. Otherwise, b is evaluated and becomes the result.
// Note that for this test there is no implicit conversion from 's' -> int (SnapshotPoint? -> int), but there is an implicit conversion
// from stripped type SnapshotPoint -> int.
// Native compiler instead implements this part based on whether A is a nullable type or not. We maintain compatibility with the native compiler:
// SPEC PROPOSAL: Otherwise, if A exists and is a nullable type and if b has a type B and an implicit conversion exists from A0 to B,
// SPEC PROPOSAL: the result type is B. At run-time, a is first evaluated. If a is not null, a is unwrapped to type A0 and converted to type B,
// SPEC PROPOSAL: and this becomes the result. 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 an implicit conversion exists from a to B,
// SPEC PROPOSAL: the result type is B. At run-time, a is first evaluated. If a is not null, a is converted to type B, and this becomes the result.
// SPEC PROPOSAL: Otherwise, b is evaluated and becomes the result.
string source = @"
struct SnapshotPoint
{
public static implicit operator int(SnapshotPoint snapshotPoint)
{
System.Console.WriteLine(""Pass"");
return 0;
}
}
class Program
{
static void Main(string[] args)
{
SnapshotPoint? s = new SnapshotPoint();
var r = s ?? -1;
SnapshotPoint? s2 = null;
r = s2 ?? -1;
}
}
";
var verifier = CompileAndVerify(source: source, expectedOutput: "Pass");
verifier.VerifyIL("Program.Main", @"
{
// Code size 70 (0x46)
.maxstack 1
.locals init (SnapshotPoint V_0,
SnapshotPoint? V_1)
IL_0000: ldloca.s V_0
IL_0002: initobj ""SnapshotPoint""
IL_0008: ldloc.0
IL_0009: newobj ""SnapshotPoint?..ctor(SnapshotPoint)""
IL_000e: stloc.1
IL_000f: ldloca.s V_1
IL_0011: call ""bool SnapshotPoint?.HasValue.get""
IL_0016: brfalse.s IL_0025
IL_0018: ldloca.s V_1
IL_001a: call ""SnapshotPoint SnapshotPoint?.GetValueOrDefault()""
IL_001f: call ""int SnapshotPoint.op_Implicit(SnapshotPoint)""
IL_0024: pop
IL_0025: ldloca.s V_1
IL_0027: initobj ""SnapshotPoint?""
IL_002d: ldloc.1
IL_002e: stloc.1
IL_002f: ldloca.s V_1
IL_0031: call ""bool SnapshotPoint?.HasValue.get""
IL_0036: brfalse.s IL_0045
IL_0038: ldloca.s V_1
IL_003a: call ""SnapshotPoint SnapshotPoint?.GetValueOrDefault()""
IL_003f: call ""int SnapshotPoint.op_Implicit(SnapshotPoint)""
IL_0044: pop
IL_0045: ret
}");
}
[Fact, WorkItem(543980, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543980")]
public void IsOperatorOnEnumAndTypeParameterConstraintToStruct()
{
string source = @"using System;
public enum E { One }
class Gen<T> where T : struct
{
public static void TestIsOperatorEnum(T t)
{
Console.WriteLine(t is Enum);
Console.WriteLine(t is E);
Console.WriteLine(t as Enum);
}
}
public class Test
{
public static void Main()
{
Gen<E>.TestIsOperatorEnum(new E());
}
}
";
string expectedOutput = @"True
True
One";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact, WorkItem(543982, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543982")]
public void OverloadAdditionOperatorOnGenericClass()
{
var source = @"
using System;
public class G<T>
{
public static G<T> operator ~(G<T> g)
{
Console.WriteLine(""G<{0}> unary negation"", typeof(T));
return new G<T>();
}
public static G<T> operator +(G<T> G1, G<T> G2)
{
Console.WriteLine(""G<{0}> binary addition"", typeof(T));
return new G<T>();
}
}
public class Gen<T, U> where T : G<U>
{
public static void TestLookupOnT(T obj, U val)
{
G<U> t = obj + ~obj;
}
}
public class Test
{
public static void Main()
{
Gen<G<int>, int>.TestLookupOnT(new G<int>(), 1);
}
}
";
string expected = @"G<System.Int32> unary negation
G<System.Int32> binary addition";
CompileAndVerify(
source: source,
expectedOutput: expected);
}
[Fact, WorkItem(544539, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544539"), WorkItem(544540, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544540")]
public void NonShortCircuitBoolean()
{
var source = @"using System;
struct Program
{
public static bool P()
{
Console.WriteLine(""P"");
return true;
}
public static void Main(string[] args)
{
bool x = true | P();
Console.WriteLine(P() & false);
}
}";
string expected = @"P
P
False";
CompileAndVerify(
source: source,
expectedOutput: expected);
}
[Fact]
public void EqualZero()
{
var text = @"
using System;
class MyClass
{
public enum E1
{
A,
B
}
public static void Main()
{
Test1((object)null, 0);
}
public static void Test1<T>(T x, E1 e) where T : class
{
if (x == null)
{
Console.WriteLine(!(x == null));
}
if (e == E1.A)
{
Console.WriteLine(!(e == E1.A));
}
}
}
";
var comp = CompileAndVerify(text, expectedOutput: @"False
False
");
comp.VerifyIL("MyClass.Test1<T>", @"
{
// Code size 35 (0x23)
.maxstack 2
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: brtrue.s IL_0016
IL_0008: ldarg.0
IL_0009: box ""T""
IL_000e: ldnull
IL_000f: cgt.un
IL_0011: call ""void System.Console.WriteLine(bool)""
IL_0016: ldarg.1
IL_0017: brtrue.s IL_0022
IL_0019: ldarg.1
IL_001a: ldc.i4.0
IL_001b: cgt.un
IL_001d: call ""void System.Console.WriteLine(bool)""
IL_0022: ret
}
");
}
[Fact]
public void EqualZeroUnoptimized()
{
var text = @"
using System;
class MyClass
{
public enum E1
{
A,
B
}
public static void Main()
{
Test1((object)null, 0);
}
public static void Test1<T>(T x, E1 e) where T : class
{
if (x == null)
{
Console.WriteLine(x == null);
}
if (e == E1.A)
{
Console.WriteLine(e == E1.A);
}
}
}
";
var comp = CompileAndVerify(text, options: TestOptions.DebugExe, expectedOutput: @"True
True
");
comp.VerifyIL("MyClass.Test1<T>", @"
{
// Code size 52 (0x34)
.maxstack 2
.locals init (bool V_0,
bool V_1)
-IL_0000: nop
-IL_0001: ldarg.0
IL_0002: box ""T""
IL_0007: ldnull
IL_0008: ceq
IL_000a: stloc.0
~IL_000b: ldloc.0
IL_000c: brfalse.s IL_001f
-IL_000e: nop
-IL_000f: ldarg.0
IL_0010: box ""T""
IL_0015: ldnull
IL_0016: ceq
IL_0018: call ""void System.Console.WriteLine(bool)""
IL_001d: nop
-IL_001e: nop
-IL_001f: ldarg.1
IL_0020: ldc.i4.0
IL_0021: ceq
IL_0023: stloc.1
~IL_0024: ldloc.1
IL_0025: brfalse.s IL_0033
-IL_0027: nop
-IL_0028: ldarg.1
IL_0029: ldc.i4.0
IL_002a: ceq
IL_002c: call ""void System.Console.WriteLine(bool)""
IL_0031: nop
-IL_0032: nop
-IL_0033: ret
}
", sequencePoints: "MyClass.Test1");
}
[WorkItem(543893, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543893")]
[Fact]
public void EnumBitwiseComplement()
{
var text = @"
public class A
{
enum E : ushort { one = 1, two = 2, four = 4 }
public static void Main()
{
checked {
E e = E.one;
e &= ~E.two;
System.Console.WriteLine(e);
}
}
}
";
var comp = CompileAndVerify(text, expectedOutput: @"one");
// Can't actually see an unchecked cast here since only constant values are emitted.
comp.VerifyIL("A.Main", @"
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldc.i4.1
IL_0001: ldc.i4 0xfffd
IL_0006: and
IL_0007: box ""A.E""
IL_000c: call ""void System.Console.WriteLine(object)""
IL_0011: ret
}
");
text = @"
public class A
{
enum E : ushort { one = 1, two = 2, four = 4 }
public static void Main()
{
checked {
E e = E.one;
int i = 5 + (int)~e;
System.Console.WriteLine(i);
}
}
}
";
comp = CompileAndVerify(text, expectedOutput: @"65539");
// Can't actually see an unchecked cast here since only constant values are emitted.
comp.VerifyIL("A.Main", @"
{
// Code size 13 (0xd)
.maxstack 2
.locals init (A.E V_0) //e
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.5
IL_0003: ldloc.0
IL_0004: not
IL_0005: conv.u2
IL_0006: add.ovf
IL_0007: call ""void System.Console.WriteLine(int)""
IL_000c: ret
}
");
}
[Fact]
public void EnumXor()
{
var text = @"
using System;
enum e : sbyte
{
x = sbyte.MinValue,
y = sbyte.MaxValue,
z = 1
}
enum e1 : byte
{
x = byte.MinValue,
y = byte.MaxValue,
z = 1
}
public static class Test
{
public static void Main()
{
TestE();
TestE1();
}
private static void TestE()
{
var x = e.x;
var y = e.y;
var z = x ^ y;
System.Console.WriteLine((int)z);
x ^= e.z;
y ^= unchecked((e)(-1));
x ^= e.z;
y ^= unchecked((e)(-1));
z = x ^ y;
System.Console.WriteLine((int)z);
}
private static void TestE1()
{
var x = e1.x;
var y = e1.y;
var z = x ^ y;
System.Console.WriteLine((int)z);
x ^= e1.z;
y ^= unchecked((e1)(-1));
x ^= e1.z;
y ^= unchecked((e1)(-1));
z = x ^ y;
System.Console.WriteLine((int)z);
}
}
";
var comp = CompileAndVerify(text, expectedOutput: @"
-1
-1
255
255
");
comp.VerifyIL("Test.TestE()", @"
{
// Code size 33 (0x21)
.maxstack 3
.locals init (e V_0) //y
IL_0000: ldc.i4.s -128
IL_0002: ldc.i4.s 127
IL_0004: stloc.0
IL_0005: dup
IL_0006: ldloc.0
IL_0007: xor
IL_0008: call ""void System.Console.WriteLine(int)""
IL_000d: ldc.i4.1
IL_000e: xor
IL_000f: ldloc.0
IL_0010: ldc.i4.m1
IL_0011: xor
IL_0012: stloc.0
IL_0013: ldc.i4.1
IL_0014: xor
IL_0015: ldloc.0
IL_0016: ldc.i4.m1
IL_0017: xor
IL_0018: stloc.0
IL_0019: ldloc.0
IL_001a: xor
IL_001b: call ""void System.Console.WriteLine(int)""
IL_0020: ret
}
");
comp.VerifyIL("Test.TestE1()", @"
{
// Code size 43 (0x2b)
.maxstack 3
.locals init (e1 V_0) //y
IL_0000: ldc.i4.0
IL_0001: ldc.i4 0xff
IL_0006: stloc.0
IL_0007: dup
IL_0008: ldloc.0
IL_0009: xor
IL_000a: call ""void System.Console.WriteLine(int)""
IL_000f: ldc.i4.1
IL_0010: xor
IL_0011: ldloc.0
IL_0012: ldc.i4 0xff
IL_0017: xor
IL_0018: stloc.0
IL_0019: ldc.i4.1
IL_001a: xor
IL_001b: ldloc.0
IL_001c: ldc.i4 0xff
IL_0021: xor
IL_0022: stloc.0
IL_0023: ldloc.0
IL_0024: xor
IL_0025: call ""void System.Console.WriteLine(int)""
IL_002a: ret
}
");
}
[WorkItem(544452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544452")]
[Fact]
public void LiftedByteEnumAddition()
{
var text =
@"using System;
public class Program
{
private static bool ThrowsException(Action action)
{
try
{
action();
return false;
}
catch(Exception)
{
return true;
}
}
private static void Test(bool b)
{
Console.Write(b ? 't' : 'f');
}
enum Color : byte { Red, Green, Blue }
static void Main()
{
Color? c = Color.Blue;
byte? b = byte.MaxValue - 1;
Color? r = 0;
Test(ThrowsException(()=>{ r = checked(c + b); }));
Test(ThrowsException(()=>{ r = checked(c.Value + b.Value); }));
Test(ThrowsException(()=>{ r = unchecked(c + b); }));
Test(ThrowsException(()=>{ r = unchecked(c.Value + b.Value); }));
}
static void M(Color c, byte b)
{
Console.WriteLine(checked(c + b));
Console.WriteLine(unchecked(c + b));
}
}";
string il = @"{
// Code size 29 (0x1d)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: add.ovf
IL_0003: conv.ovf.u1
IL_0004: box ""Program.Color""
IL_0009: call ""void System.Console.WriteLine(object)""
IL_000e: ldarg.0
IL_000f: ldarg.1
IL_0010: add
IL_0011: conv.u1
IL_0012: box ""Program.Color""
IL_0017: call ""void System.Console.WriteLine(object)""
IL_001c: ret
}";
var comp = CompileAndVerify(text, expectedOutput: @"ttff");
comp.VerifyIL("Program.M", il);
}
[WorkItem(7091, "https://github.com/dotnet/roslyn/issues/7091")]
[Fact]
public void LiftedBitwiseOr()
{
var text =
@"using System;
public class Program
{
static void Main()
{
var res = XX() | YY();
}
static bool XX()
{
Console.WriteLine (""XX"");
return true;
}
static bool? YY()
{
Console.WriteLine(""YY"");
return true;
}
}
";
var expectedOutput =
@"XX
YY";
var comp = CompileAndVerify(text, expectedOutput: expectedOutput);
string il = @"{
// Code size 13 (0xd)
.maxstack 2
.locals init (bool? V_0)
IL_0000: call ""bool Program.XX()""
IL_0005: call ""bool? Program.YY()""
IL_000a: stloc.0
IL_000b: pop
IL_000c: ret
}
";
comp.VerifyIL("Program.Main", il);
}
[WorkItem(544943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544943")]
[Fact]
public void OptimizedXor()
{
var text = @"
using System;
class C
{
void M(bool b)
{
Console.WriteLine(b ^ true);
Console.WriteLine(b ^ false);
Console.WriteLine(true ^ b);
Console.WriteLine(false ^ b);
}
}";
//NOTE: all xors optimized away
var comp = CompileAndVerify(text).VerifyIL("C.M", @"
{
// Code size 31 (0x1f)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.0
IL_0002: ceq
IL_0004: call ""void System.Console.WriteLine(bool)""
IL_0009: ldarg.1
IL_000a: call ""void System.Console.WriteLine(bool)""
IL_000f: ldarg.1
IL_0010: ldc.i4.0
IL_0011: ceq
IL_0013: call ""void System.Console.WriteLine(bool)""
IL_0018: ldarg.1
IL_0019: call ""void System.Console.WriteLine(bool)""
IL_001e: ret
}");
}
[WorkItem(544943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544943")]
[Fact]
public void XorMalformedTrue()
{
var text = @"
using System;
class C
{
static void Main()
{
byte[] x = { 0xFF };
bool[] y = { true };
Buffer.BlockCopy(x, 0, y, 0, 1);
Console.WriteLine(y[0]);
Console.WriteLine(y[0] ^ true);
}
}";
var comp = CompileAndVerify(text, expectedOutput: @"True
False");
}
[WorkItem(539398, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539398")]
[WorkItem(1043494, "DevDiv")]
[ConditionalFact(typeof(DesktopOnly))]
public void TestFloatNegativeZero()
{
var text = @"
using System;
class C
{
static void Main()
{
Console.WriteLine(+0f == -0f);
Console.WriteLine(1f / 0f);
Console.WriteLine(1f / -0f);
Console.WriteLine(-1f / 0f);
Console.WriteLine(-1f / -0f);
Console.WriteLine(1f / (1f * 0f));
Console.WriteLine(1f / (1f * -0f));
Console.WriteLine(1f / (-1f * 0f));
Console.WriteLine(1f / (-1f * -0f));
}
}";
var comp = CompileAndVerify(text, expectedOutput: @"
True
Infinity
-Infinity
-Infinity
Infinity
Infinity
-Infinity
-Infinity
Infinity");
}
[WorkItem(539398, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539398")]
[WorkItem(1043494, "DevDiv")]
[ConditionalFact(typeof(DesktopOnly))]
public void TestDoubleNegativeZero()
{
var text = @"
using System;
class C
{
static void Main()
{
Console.WriteLine(+0d == -0d);
Console.WriteLine(1d / 0d);
Console.WriteLine(1d / -0d);
Console.WriteLine(-1d / 0d);
Console.WriteLine(-1d / -0d);
Console.WriteLine(1d / (1d * 0d));
Console.WriteLine(1d / (1d * -0d));
Console.WriteLine(1d / (-1d * 0d));
Console.WriteLine(1d / (-1d * -0d));
}
}";
var comp = CompileAndVerify(text, expectedOutput: @"
True
Infinity
-Infinity
-Infinity
Infinity
Infinity
-Infinity
-Infinity
Infinity");
}
// NOTE: decimal doesn't have infinity, so we convert to double.
[WorkItem(539398, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539398")]
[WorkItem(1043494, "DevDiv")]
[ConditionalFact(typeof(DesktopOnly))]
public void TestDecimalNegativeZero()
{
var text = @"
using System;
class C
{
static void Main()
{
Console.WriteLine(+0m == -0m);
Console.WriteLine(1d / (double)(0m));
Console.WriteLine(1d / (double)(-0m));
Console.WriteLine(-1d / (double)(0m));
Console.WriteLine(-1d / (double)(-0m));
Console.WriteLine(1d / (double)(1m * 0m));
Console.WriteLine(1d / (double)(1m * -0m));
Console.WriteLine(1d / (double)(-1m * 0m));
Console.WriteLine(1d / (double)(-1m * -0m));
}
}";
var comp = CompileAndVerify(text, expectedOutput: @"
True
Infinity
-Infinity
-Infinity
Infinity
Infinity
-Infinity
-Infinity
Infinity");
}
[WorkItem(545239, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545239")]
[Fact()]
public void IncrementPropertyOfTypeParameterReturnValue()
{
var text = @"
public interface I
{
int IntPropI { get; set; }
}
struct S1 : I
{
public int x;
public int IntPropI
{
get
{
x ++;
return x;
}
set
{
x ++;
System.Console.WriteLine(x);
}
}
}
public class Test
{
public static void Main()
{
S1 s = new S1();
TestINop(s);
}
public static T Nop<T>(T t) { return t; }
public static void TestINop<T>(T t) where T : I
{
Nop(t).IntPropI++;
Nop(t).IntPropI++;
}
}
";
CompileAndVerify(text, expectedOutput: @"
2
2").VerifyIL("Test.TestINop<T>", @"
{
// Code size 73 (0x49)
.maxstack 3
.locals init (int V_0,
T V_1)
IL_0000: ldarg.0
IL_0001: call ""T Test.Nop<T>(T)""
IL_0006: stloc.1
IL_0007: ldloca.s V_1
IL_0009: dup
IL_000a: constrained. ""T""
IL_0010: callvirt ""int I.IntPropI.get""
IL_0015: stloc.0
IL_0016: ldloc.0
IL_0017: ldc.i4.1
IL_0018: add
IL_0019: constrained. ""T""
IL_001f: callvirt ""void I.IntPropI.set""
IL_0024: ldarg.0
IL_0025: call ""T Test.Nop<T>(T)""
IL_002a: stloc.1
IL_002b: ldloca.s V_1
IL_002d: dup
IL_002e: constrained. ""T""
IL_0034: callvirt ""int I.IntPropI.get""
IL_0039: stloc.0
IL_003a: ldloc.0
IL_003b: ldc.i4.1
IL_003c: add
IL_003d: constrained. ""T""
IL_0043: callvirt ""void I.IntPropI.set""
IL_0048: ret
}
");
}
[WorkItem(546750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546750")]
[Fact()]
public void IncrementStructFieldWithReceiverThis()
{
var text = @"
struct S
{
int x;
void Test()
{
x++;
}
}
";
// NOTE: don't need a ref local in this case.
CompileAndVerify(text).VerifyIL("S.Test", @"
{
// Code size 15 (0xf)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldfld ""int S.x""
IL_0007: ldc.i4.1
IL_0008: add
IL_0009: stfld ""int S.x""
IL_000e: ret
}
");
}
[Fact]
public void TestTernary_InterfaceRegression1a()
{
var source = @"
using System.Collections.Generic;
public class Test
{
private static bool C() { return true;}
static void Main()
{
int[] a = new int[] { };
IEnumerable<int> b = new List<int>();
IEnumerable<int> c = C()? b : a;
Goo(c);
}
static void Goo<T>(T x)
{
System.Console.WriteLine(typeof(T));
}
}";
var comp = CompileAndVerify(source, expectedOutput: "System.Collections.Generic.IEnumerable`1[System.Int32]");
comp.VerifyDiagnostics();
comp.VerifyIL("Test.Main", @"
{
// Code size 32 (0x20)
.maxstack 1
.locals init (int[] V_0, //a
System.Collections.Generic.IEnumerable<int> V_1, //b
System.Collections.Generic.IEnumerable<int> V_2)
IL_0000: ldc.i4.0
IL_0001: newarr ""int""
IL_0006: stloc.0
IL_0007: newobj ""System.Collections.Generic.List<int>..ctor()""
IL_000c: stloc.1
IL_000d: call ""bool Test.C()""
IL_0012: brtrue.s IL_0019
IL_0014: ldloc.0
IL_0015: stloc.2
IL_0016: ldloc.2
IL_0017: br.s IL_001a
IL_0019: ldloc.1
IL_001a: call ""void Test.Goo<System.Collections.Generic.IEnumerable<int>>(System.Collections.Generic.IEnumerable<int>)""
IL_001f: ret
}");
}
[Fact]
public void TestTernary_InterfaceRegression1b()
{
var source = @"
using System.Collections.Generic;
public class Test
{
private static bool C() { return true;}
static void Main()
{
int[] a = new int[] { };
IEnumerable<int> b = null;
IEnumerable<int> c = C()? (b = (IEnumerable<int>)new List<int>()) : a;
Goo(c);
Goo(b);
}
static void Goo<T>(T x)
{
System.Console.Write(typeof(T));
}
}";
var comp = CompileAndVerify(source, expectedOutput: "System.Collections.Generic.IEnumerable`1[System.Int32]System.Collections.Generic.IEnumerable`1[System.Int32]");
comp.VerifyDiagnostics();
comp.VerifyIL("Test.Main", @"
{
// Code size 42 (0x2a)
.maxstack 2
.locals init (int[] V_0, //a
System.Collections.Generic.IEnumerable<int> V_1, //b
System.Collections.Generic.IEnumerable<int> V_2)
IL_0000: ldc.i4.0
IL_0001: newarr ""int""
IL_0006: stloc.0
IL_0007: ldnull
IL_0008: stloc.1
IL_0009: call ""bool Test.C()""
IL_000e: brtrue.s IL_0015
IL_0010: ldloc.0
IL_0011: stloc.2
IL_0012: ldloc.2
IL_0013: br.s IL_001e
IL_0015: newobj ""System.Collections.Generic.List<int>..ctor()""
IL_001a: dup
IL_001b: stloc.1
IL_001c: stloc.2
IL_001d: ldloc.2
IL_001e: call ""void Test.Goo<System.Collections.Generic.IEnumerable<int>>(System.Collections.Generic.IEnumerable<int>)""
IL_0023: ldloc.1
IL_0024: call ""void Test.Goo<System.Collections.Generic.IEnumerable<int>>(System.Collections.Generic.IEnumerable<int>)""
IL_0029: ret
}");
}
[Fact]
public void TestTernary_InterfaceRegression1c()
{
var source = @"
using System.Collections.Generic;
public class Test
{
static void Main()
{
int[] a = new int[] { };
IEnumerable<int> b = new List<int>();
Goo(b, b != null ? b : a);
}
static void Goo<T, U>(T x, U y)
{
System.Console.Write(typeof(T));
}
}";
var comp = CompileAndVerify(source, expectedOutput: "System.Collections.Generic.IEnumerable`1[System.Int32]");
comp.VerifyDiagnostics();
comp.VerifyIL("Test.Main", @"
{
// Code size 29 (0x1d)
.maxstack 2
.locals init (int[] V_0, //a
System.Collections.Generic.IEnumerable<int> V_1, //b
System.Collections.Generic.IEnumerable<int> V_2)
IL_0000: ldc.i4.0
IL_0001: newarr ""int""
IL_0006: stloc.0
IL_0007: newobj ""System.Collections.Generic.List<int>..ctor()""
IL_000c: stloc.1
IL_000d: ldloc.1
IL_000e: ldloc.1
IL_000f: brtrue.s IL_0016
IL_0011: ldloc.0
IL_0012: stloc.2
IL_0013: ldloc.2
IL_0014: br.s IL_0017
IL_0016: ldloc.1
IL_0017: call ""void Test.Goo<System.Collections.Generic.IEnumerable<int>, System.Collections.Generic.IEnumerable<int>>(System.Collections.Generic.IEnumerable<int>, System.Collections.Generic.IEnumerable<int>)""
IL_001c: ret
}
");
}
[Fact]
public void TestTernary_InterfaceRegression2()
{
var source = @"
public interface IA { }
public interface IB { int f(); }
public class AB1 : IA, IB { public int f() { return 42; } }
public class AB2 : IA, IB { public int f() { return 1; } }
class MainClass
{
private static bool C() { return true;}
public static void g(AB1 ab1)
{
(C()? (IB)ab1 : (IB)new AB2()).f();
}
}";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("MainClass.g", @"
{
// Code size 26 (0x1a)
.maxstack 1
.locals init (IB V_0)
IL_0000: call ""bool MainClass.C()""
IL_0005: brtrue.s IL_0010
IL_0007: newobj ""AB2..ctor()""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: br.s IL_0013
IL_0010: ldarg.0
IL_0011: stloc.0
IL_0012: ldloc.0
IL_0013: callvirt ""int IB.f()""
IL_0018: pop
IL_0019: ret
}");
}
[Fact]
public void TestTernary_FuncVariance()
{
var source = @"
using System;
using System.Collections.Generic;
class Program
{
private static bool C() { return true;}
static void Main(string[] args)
{
Func<Exception[]> f1 = null;
Func<IEnumerable<object>> f2 = null;
var oo = C()? f1 : f2;
Console.WriteLine(oo);
oo = C()? f2 : f1;
Console.WriteLine(oo);
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"
{
// Code size 41 (0x29)
.maxstack 1
.locals init (System.Func<System.Exception[]> V_0, //f1
System.Func<System.Collections.Generic.IEnumerable<object>> V_1, //f2
System.Func<System.Collections.Generic.IEnumerable<object>> V_2)
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldnull
IL_0003: stloc.1
IL_0004: call ""bool Program.C()""
IL_0009: brtrue.s IL_000e
IL_000b: ldloc.1
IL_000c: br.s IL_0011
IL_000e: ldloc.0
IL_000f: stloc.2
IL_0010: ldloc.2
IL_0011: call ""void System.Console.WriteLine(object)""
IL_0016: call ""bool Program.C()""
IL_001b: brtrue.s IL_0022
IL_001d: ldloc.0
IL_001e: stloc.2
IL_001f: ldloc.2
IL_0020: br.s IL_0023
IL_0022: ldloc.1
IL_0023: call ""void System.Console.WriteLine(object)""
IL_0028: ret
}
");
}
[Fact]
public void TestTernary_FuncVariance01()
{
var source = @"
using System;
using System.Collections;
using System.Collections.Generic;
class Program
{
private static bool C() { return true;}
static void Main(string[] args)
{
Func<Exception[]> f1 = null;
Func<IEnumerable<object>> f2 = null;
var oo = C()? (Func<IEnumerable>)f1 : (Func<IEnumerable>)f2;
Console.WriteLine(oo);
oo = C()? (Func<IEnumerable>)f2 : (Func<IEnumerable>)f1;
Console.WriteLine(oo);
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"
{
// Code size 45 (0x2d)
.maxstack 1
.locals init (System.Func<System.Exception[]> V_0, //f1
System.Func<System.Collections.Generic.IEnumerable<object>> V_1, //f2
System.Func<System.Collections.IEnumerable> V_2)
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldnull
IL_0003: stloc.1
IL_0004: call ""bool Program.C()""
IL_0009: brtrue.s IL_0010
IL_000b: ldloc.1
IL_000c: stloc.2
IL_000d: ldloc.2
IL_000e: br.s IL_0013
IL_0010: ldloc.0
IL_0011: stloc.2
IL_0012: ldloc.2
IL_0013: call ""void System.Console.WriteLine(object)""
IL_0018: call ""bool Program.C()""
IL_001d: brtrue.s IL_0024
IL_001f: ldloc.0
IL_0020: stloc.2
IL_0021: ldloc.2
IL_0022: br.s IL_0027
IL_0024: ldloc.1
IL_0025: stloc.2
IL_0026: ldloc.2
IL_0027: call ""void System.Console.WriteLine(object)""
IL_002c: ret
}
");
}
[Fact]
public void TestTernary_InterfaceVariance()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Security;
[assembly: SecurityTransparent()]
class Program
{
private static bool C() { return true;}
interface CoInter<out T>
{
}
static void Main(string[] args)
{
CoInter<Exception[]> f1 = null;
CoInter<IEnumerable<object>> f2 = null;
var oo = C()? f1 : f2;
Console.WriteLine(oo);
oo = C()? f2 : f1;
Console.WriteLine(oo);
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"
{
// Code size 41 (0x29)
.maxstack 1
.locals init (Program.CoInter<System.Exception[]> V_0, //f1
Program.CoInter<System.Collections.Generic.IEnumerable<object>> V_1, //f2
Program.CoInter<System.Collections.Generic.IEnumerable<object>> V_2)
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldnull
IL_0003: stloc.1
IL_0004: call ""bool Program.C()""
IL_0009: brtrue.s IL_000e
IL_000b: ldloc.1
IL_000c: br.s IL_0011
IL_000e: ldloc.0
IL_000f: stloc.2
IL_0010: ldloc.2
IL_0011: call ""void System.Console.WriteLine(object)""
IL_0016: call ""bool Program.C()""
IL_001b: brtrue.s IL_0022
IL_001d: ldloc.0
IL_001e: stloc.2
IL_001f: ldloc.2
IL_0020: br.s IL_0023
IL_0022: ldloc.1
IL_0023: call ""void System.Console.WriteLine(object)""
IL_0028: ret
}
");
}
[Fact]
public void TestTernary_InterfaceVarianceA()
{
var source = @"
using System;
using System.Security;
[assembly: SecurityTransparent()]
class Program
{
private static bool C() { return true;}
interface CoInter<out T>
{
}
static void Main(string[] args)
{
CoInter<Exception> f1 = null;
CoInter<object> f2 = null;
var oo = C()? f1 : f2;
Console.WriteLine(oo);
oo = C()? f2 : f1;
Console.WriteLine(oo);
}
}
";
var comp = CompileAndVerify(new string[] { source }, expectedOutput: @"");
// var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"
{
// Code size 41 (0x29)
.maxstack 1
.locals init (Program.CoInter<System.Exception> V_0, //f1
Program.CoInter<object> V_1, //f2
Program.CoInter<object> V_2)
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldnull
IL_0003: stloc.1
IL_0004: call ""bool Program.C()""
IL_0009: brtrue.s IL_000e
IL_000b: ldloc.1
IL_000c: br.s IL_0011
IL_000e: ldloc.0
IL_000f: stloc.2
IL_0010: ldloc.2
IL_0011: call ""void System.Console.WriteLine(object)""
IL_0016: call ""bool Program.C()""
IL_001b: brtrue.s IL_0022
IL_001d: ldloc.0
IL_001e: stloc.2
IL_001f: ldloc.2
IL_0020: br.s IL_0023
IL_0022: ldloc.1
IL_0023: call ""void System.Console.WriteLine(object)""
IL_0028: ret
}
");
}
[Fact]
public void TestTernary_InterfaceVariance01()
{
var source = @"
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security;
[assembly: SecurityTransparent()]
class Program
{
private static bool C() { return true;}
interface CoInter<out T>
{
}
static void Main(string[] args)
{
CoInter<Exception[]> f1 = null;
CoInter<IEnumerable<object>> f2 = null;
var oo = C()? (CoInter<IEnumerable>)f1 : (CoInter<IEnumerable>)f2;
Console.WriteLine(oo);
oo = C()? (CoInter<IEnumerable>)f2 : (CoInter<IEnumerable>)f1;
Console.WriteLine(oo);
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"
{
// Code size 45 (0x2d)
.maxstack 1
.locals init (Program.CoInter<System.Exception[]> V_0, //f1
Program.CoInter<System.Collections.Generic.IEnumerable<object>> V_1, //f2
Program.CoInter<System.Collections.IEnumerable> V_2)
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldnull
IL_0003: stloc.1
IL_0004: call ""bool Program.C()""
IL_0009: brtrue.s IL_0010
IL_000b: ldloc.1
IL_000c: stloc.2
IL_000d: ldloc.2
IL_000e: br.s IL_0013
IL_0010: ldloc.0
IL_0011: stloc.2
IL_0012: ldloc.2
IL_0013: call ""void System.Console.WriteLine(object)""
IL_0018: call ""bool Program.C()""
IL_001d: brtrue.s IL_0024
IL_001f: ldloc.0
IL_0020: stloc.2
IL_0021: ldloc.2
IL_0022: br.s IL_0027
IL_0024: ldloc.1
IL_0025: stloc.2
IL_0026: ldloc.2
IL_0027: call ""void System.Console.WriteLine(object)""
IL_002c: ret
}
");
}
[Fact]
public void TestTernary_ToBase()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Security;
[assembly: SecurityTransparent()]
class Program
{
private static bool C() { return true;}
static void Main(string[] args)
{
Exception[] f1 = null;
IEnumerable<object> f2 = null;
var oo = C()? (object)f1 : (object)f2;
Console.WriteLine(oo);
oo = C()? (object)f2 : (object)f1;
Console.WriteLine(oo);
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"
{
// Code size 37 (0x25)
.maxstack 1
.locals init (System.Exception[] V_0, //f1
System.Collections.Generic.IEnumerable<object> V_1) //f2
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldnull
IL_0003: stloc.1
IL_0004: call ""bool Program.C()""
IL_0009: brtrue.s IL_000e
IL_000b: ldloc.1
IL_000c: br.s IL_000f
IL_000e: ldloc.0
IL_000f: call ""void System.Console.WriteLine(object)""
IL_0014: call ""bool Program.C()""
IL_0019: brtrue.s IL_001e
IL_001b: ldloc.0
IL_001c: br.s IL_001f
IL_001e: ldloc.1
IL_001f: call ""void System.Console.WriteLine(object)""
IL_0024: ret
}
");
}
[WorkItem(634407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/634407")]
[Fact]
public void TestTernary_Null()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Security;
[assembly: SecurityTransparent()]
class Program
{
private static bool C() { return true;}
static void Main(string[] args)
{
Exception[] f1 = null;
var oo = C()? f1 : null as IEnumerable<object>;
Console.WriteLine(oo);
var oo1 = C()? null as IEnumerable<object> : f1 as IEnumerable<Exception>;
Console.WriteLine(oo1);
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"
{
// Code size 39 (0x27)
.maxstack 1
.locals init (System.Exception[] V_0, //f1
System.Collections.Generic.IEnumerable<object> V_1)
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: call ""bool Program.C()""
IL_0007: brtrue.s IL_000c
IL_0009: ldnull
IL_000a: br.s IL_000f
IL_000c: ldloc.0
IL_000d: stloc.1
IL_000e: ldloc.1
IL_000f: call ""void System.Console.WriteLine(object)""
IL_0014: call ""bool Program.C()""
IL_0019: brtrue.s IL_0020
IL_001b: ldloc.0
IL_001c: stloc.1
IL_001d: ldloc.1
IL_001e: br.s IL_0021
IL_0020: ldnull
IL_0021: call ""void System.Console.WriteLine(object)""
IL_0026: ret
}");
}
[WorkItem(634406, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/634406")]
[Fact]
public void TestBinary_Implicit()
{
var source = @"
using System;
using System.Security;
[assembly: SecurityTransparent()]
class Program
{
private static bool C() { return true; }
class cls1
{
public static implicit operator int(cls1 from)
{
return 42;
}
}
static void Main(string[] args)
{
cls1 f1 = null;
var oo = f1 ?? 33;
Console.WriteLine(oo);
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"
{
// Code size 21 (0x15)
.maxstack 1
.locals init (Program.cls1 V_0)
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: brtrue.s IL_0009
IL_0005: ldc.i4.s 33
IL_0007: br.s IL_000f
IL_0009: ldloc.0
IL_000a: call ""int Program.cls1.op_Implicit(Program.cls1)""
IL_000f: call ""void System.Console.WriteLine(int)""
IL_0014: ret
}
");
}
[WorkItem(656807, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/656807")]
[Fact]
public void DelegateEqualsNull()
{
var source = @"
public delegate int D(int x);
public class Program
{
public static D d1 = null;
public static int r1;
public static bool r2;
public static void Main(string[] args)
{
if (d1 == null) { r1 = 1; }
if (d1 != null) { r1 = 2; }
r2 = (d1 == null);
r2 = (d1 != null);
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"
{
// Code size 53 (0x35)
.maxstack 2
IL_0000: ldsfld ""D Program.d1""
IL_0005: brtrue.s IL_000d
IL_0007: ldc.i4.1
IL_0008: stsfld ""int Program.r1""
IL_000d: ldsfld ""D Program.d1""
IL_0012: brfalse.s IL_001a
IL_0014: ldc.i4.2
IL_0015: stsfld ""int Program.r1""
IL_001a: ldsfld ""D Program.d1""
IL_001f: ldnull
IL_0020: ceq
IL_0022: stsfld ""bool Program.r2""
IL_0027: ldsfld ""D Program.d1""
IL_002c: ldnull
IL_002d: cgt.un
IL_002f: stsfld ""bool Program.r2""
IL_0034: ret
}");
}
[WorkItem(717072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/717072")]
[Fact]
public void DecimalOperators()
{
var source = @"
class Program
{
static void Main()
{
decimal d1 = 1.0201m;
if (d1 == 10201M)
{
}
if (d1 != 10201M)
{
}
decimal d2 = d1 + d1;
decimal d3 = d1 - d1;
decimal d4 = d1 * d1;
decimal d5 = d1 / d1;
decimal d6 = d1 % d1;
decimal d7 = d1 ++;
decimal d8 = d1--;
decimal d9 = -d1;
decimal d10 = +d1;
}
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"
{
// Code size 116 (0x74)
.maxstack 6
.locals init (decimal V_0) //d1
IL_0000: ldloca.s V_0
IL_0002: ldc.i4 0x27d9
IL_0007: ldc.i4.0
IL_0008: ldc.i4.0
IL_0009: ldc.i4.0
IL_000a: ldc.i4.4
IL_000b: call ""decimal..ctor(int, int, int, bool, byte)""
IL_0010: ldloc.0
IL_0011: ldc.i4 0x27d9
IL_0016: newobj ""decimal..ctor(int)""
IL_001b: call ""bool decimal.op_Equality(decimal, decimal)""
IL_0020: pop
IL_0021: ldloc.0
IL_0022: ldc.i4 0x27d9
IL_0027: newobj ""decimal..ctor(int)""
IL_002c: call ""bool decimal.op_Inequality(decimal, decimal)""
IL_0031: pop
IL_0032: ldloc.0
IL_0033: ldloc.0
IL_0034: call ""decimal decimal.op_Addition(decimal, decimal)""
IL_0039: pop
IL_003a: ldloc.0
IL_003b: ldloc.0
IL_003c: call ""decimal decimal.op_Subtraction(decimal, decimal)""
IL_0041: pop
IL_0042: ldloc.0
IL_0043: ldloc.0
IL_0044: call ""decimal decimal.op_Multiply(decimal, decimal)""
IL_0049: pop
IL_004a: ldloc.0
IL_004b: ldloc.0
IL_004c: call ""decimal decimal.op_Division(decimal, decimal)""
IL_0051: pop
IL_0052: ldloc.0
IL_0053: ldloc.0
IL_0054: call ""decimal decimal.op_Modulus(decimal, decimal)""
IL_0059: pop
IL_005a: ldloc.0
IL_005b: dup
IL_005c: call ""decimal decimal.op_Increment(decimal)""
IL_0061: stloc.0
IL_0062: pop
IL_0063: ldloc.0
IL_0064: dup
IL_0065: call ""decimal decimal.op_Decrement(decimal)""
IL_006a: stloc.0
IL_006b: pop
IL_006c: ldloc.0
IL_006d: call ""decimal decimal.op_UnaryNegation(decimal)""
IL_0072: pop
IL_0073: ret
}
");
}
[WorkItem(732269, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/732269")]
[Fact]
public void NullCoalesce()
{
var source = @"
class Program
{
static int Main(int? x, int y) { return x ?? y; }
}
";
var comp = CompileAndVerify(source);
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"
{
// Code size 21 (0x15)
.maxstack 1
.locals init (int? V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool int?.HasValue.get""
IL_0009: brtrue.s IL_000d
IL_000b: ldarg.1
IL_000c: ret
IL_000d: ldloca.s V_0
IL_000f: call ""int int?.GetValueOrDefault()""
IL_0014: ret
}
");
}
[Fact]
public void TestCompoundOnAFieldOfGeneric()
{
var source = @"
class Program
{
static void Main(string[] args)
{
var x = new c0();
test<c0>.Repro1(x);
System.Console.WriteLine(x.x);
test<c0>.Repro2(x);
System.Console.WriteLine(x.x);
}
}
class c0
{
public int x;
public int P1
{
get { return x; }
set { x = value; }
}
public int this[int i]
{
get { return x; }
set { x = value; }
}
public static int Goo(c0 arg)
{
return 1;
}
public int Goo()
{
return 1;
}
}
class test<T> where T : c0
{
public static void Repro1(T arg)
{
arg.x += 1;
arg.P1 += 1;
arg[1] += 1;
}
public static void Repro2(T arg)
{
arg.x = c0.Goo(arg);
arg.x = arg.Goo();
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"3
1");
compilation.VerifyIL("test<T>.Repro1(T)", @"
{
// Code size 80 (0x50)
.maxstack 4
.locals init (T& V_0)
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: dup
IL_0007: ldfld ""int c0.x""
IL_000c: ldc.i4.1
IL_000d: add
IL_000e: stfld ""int c0.x""
IL_0013: ldarga.s V_0
IL_0015: stloc.0
IL_0016: ldloc.0
IL_0017: ldloc.0
IL_0018: constrained. ""T""
IL_001e: callvirt ""int c0.P1.get""
IL_0023: ldc.i4.1
IL_0024: add
IL_0025: constrained. ""T""
IL_002b: callvirt ""void c0.P1.set""
IL_0030: ldarga.s V_0
IL_0032: stloc.0
IL_0033: ldloc.0
IL_0034: ldc.i4.1
IL_0035: ldloc.0
IL_0036: ldc.i4.1
IL_0037: constrained. ""T""
IL_003d: callvirt ""int c0.this[int].get""
IL_0042: ldc.i4.1
IL_0043: add
IL_0044: constrained. ""T""
IL_004a: callvirt ""void c0.this[int].set""
IL_004f: ret
}
").VerifyIL("test<T>.Repro2(T)", @"
{
// Code size 45 (0x2d)
.maxstack 2
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: ldarg.0
IL_0007: box ""T""
IL_000c: call ""int c0.Goo(c0)""
IL_0011: stfld ""int c0.x""
IL_0016: ldarg.0
IL_0017: box ""T""
IL_001c: ldarg.0
IL_001d: box ""T""
IL_0022: callvirt ""int c0.Goo()""
IL_0027: stfld ""int c0.x""
IL_002c: ret
}
");
}
[Fact()]
[WorkItem(4828, "https://github.com/dotnet/roslyn/issues/4828")]
public void OptimizeOutLocals_01()
{
const string source = @"
class Program
{
static void Main(string[] args)
{
int a = 0;
int b = a + a / 1;
}
}";
var result = CompileAndVerify(source, options: TestOptions.ReleaseExe);
result.VerifyIL("Program.Main",
@"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldc.i4.0
IL_0001: ldc.i4.1
IL_0002: div
IL_0003: pop
IL_0004: ret
}
");
}
[ConditionalFact(typeof(NoIOperationValidation))]
[WorkItem(5395, "https://github.com/dotnet/roslyn/issues/5395")]
public void EmitSequenceOfBinaryExpressions_01()
{
var source =
@"
class Test
{
static void Main()
{
var f = new long[4096];
for (int i = 0; i < 4096 ; i++)
{
f[i] = 4096 - i;
}
System.Console.WriteLine((Calculate1(f) == Calculate2(f)) ? ""True"" : ""False"");
}
public static long Calculate1(long[] f)
{
" + $" return { BuildSequenceOfBinaryExpressions_01() };" + @"
}
public static long Calculate2(long[] f)
{
long result = 0;
int i;
for (i = 0; i < f.Length; i++)
{
result+=(i + 1)*f[i];
}
return result + (i + 1);
}
}
";
var result = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: "True");
}
private static string BuildSequenceOfBinaryExpressions_01(int count = 4096)
{
var builder = new System.Text.StringBuilder();
int i;
for (i = 0; i < count; i++)
{
builder.Append(i + 1);
builder.Append(" * ");
builder.Append("f[");
builder.Append(i);
builder.Append("] + ");
}
builder.Append(i + 1);
return builder.ToString();
}
[ConditionalFact(typeof(NoIOperationValidation))]
[WorkItem(5395, "https://github.com/dotnet/roslyn/issues/5395")]
public void EmitSequenceOfBinaryExpressions_02()
{
var source =
@"
class Test
{
static void Main()
{
var f = new long[4096];
for (int i = 0; i < 4096 ; i++)
{
f[i] = 4096 - i;
}
System.Console.WriteLine(Calculate(f));
}
public static double Calculate(long[] f)
{
" + $" return checked({ BuildSequenceOfBinaryExpressions_01() });" + @"
}
}
";
var result = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: "11461640193");
}
[ConditionalFact(typeof(ClrOnly), typeof(NoIOperationValidation), Reason = "https://github.com/dotnet/roslyn/issues/29428")]
[WorkItem(6077, "https://github.com/dotnet/roslyn/issues/6077")]
[WorkItem(5395, "https://github.com/dotnet/roslyn/issues/5395")]
public void EmitSequenceOfBinaryExpressions_03()
{
var diagnostics = ImmutableArray<Diagnostic>.Empty;
const int start = 8192;
const int step = 4096;
const int limit = start * 4;
for (int count = start; count <= limit && diagnostics.IsEmpty; count += step)
{
var source =
@"
class Test
{
static void Main()
{
}
public static bool Calculate(bool[] a, bool[] f)
{
" + $" return { BuildSequenceOfBinaryExpressions_03(count) };" + @"
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
diagnostics = compilation.GetEmitDiagnostics();
}
diagnostics.Verify(
// (10,16): error CS8078: An expression is too long or complex to compile
// return a[0] && f[0] || a[1] && f[1] || a[2] && f[2] || ...
Diagnostic(ErrorCode.ERR_InsufficientStack, "a").WithLocation(10, 16)
);
}
private static string BuildSequenceOfBinaryExpressions_03(int count = 8192)
{
var builder = new System.Text.StringBuilder();
int i;
for (i = 0; i < count; i++)
{
builder.Append("a[");
builder.Append(i);
builder.Append("]");
builder.Append(" && ");
builder.Append("f[");
builder.Append(i);
builder.Append("] || ");
}
builder.Append("a[");
builder.Append(i);
builder.Append("]");
return builder.ToString();
}
[ConditionalFact(typeof(ClrOnly), typeof(NoIOperationValidation), Reason = "https://github.com/dotnet/roslyn/issues/29428")]
[WorkItem(5395, "https://github.com/dotnet/roslyn/issues/5395")]
public void EmitSequenceOfBinaryExpressions_04()
{
var source =
@"
class Test
{
static void Main()
{
var f = new float?[4096];
for (int i = 0; i < 4096 ; i++)
{
f[i] = 4096 - i;
}
System.Console.WriteLine(Calculate(f));
}
public static double? Calculate(float?[] f)
{
" + $" return { BuildSequenceOfBinaryExpressions_01() };" + @"
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyEmitDiagnostics(
// (17,16): error CS8078: An expression is too long or complex to compile
// return 1 * f[0] + 2 * f[1] + 3 * f[2] + 4 * f[3] + ...
Diagnostic(ErrorCode.ERR_InsufficientStack, "1").WithLocation(17, 16)
);
}
[ConditionalFact(typeof(NoIOperationValidation))]
[WorkItem(5395, "https://github.com/dotnet/roslyn/issues/5395")]
public void EmitSequenceOfBinaryExpressions_05()
{
int count = 50;
var source =
@"
class Test
{
static void Main()
{
Test1();
Test2();
}
static void Test1()
{
var f = new double?[" + $"{count}" + @"];
for (int i = 0; i < " + $"{count}" + @" ; i++)
{
f[i] = 4096 - i;
}
System.Console.WriteLine(Calculate(f));
}
public static double? Calculate(double?[] f)
{
" + $" return { BuildSequenceOfBinaryExpressions_01(count) };" + @"
}
static void Test2()
{
var f = new double[" + $"{count}" + @"];
for (int i = 0; i < " + $"{count}" + @" ; i++)
{
f[i] = 4096 - i;
}
System.Console.WriteLine(Calculate(f));
}
public static double Calculate(double[] f)
{
" + $" return { BuildSequenceOfBinaryExpressions_01(count) };" + @"
}
}
";
var result = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: @"5180801
5180801");
}
[ConditionalFact(typeof(ClrOnly), typeof(NoIOperationValidation), Reason = "https://github.com/dotnet/roslyn/issues/29428", AlwaysSkip = "https://github.com/dotnet/roslyn/issues/46361")]
[WorkItem(5395, "https://github.com/dotnet/roslyn/issues/5395")]
public void EmitSequenceOfBinaryExpressions_06()
{
var source =
@"
class Test
{
static void Main()
{
}
public static bool Calculate(S1[] a, S1[] f)
{
" + $" return { BuildSequenceOfBinaryExpressions_03() };" + @"
}
}
struct S1
{
public static S1 operator & (S1 x, S1 y)
{
return new S1();
}
public static S1 operator |(S1 x, S1 y)
{
return new S1();
}
public static bool operator true(S1 x)
{
return true;
}
public static bool operator false(S1 x)
{
return true;
}
public static implicit operator bool (S1 x)
{
return true;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyEmitDiagnostics(
// (10,16): error CS8078: An expression is too long or complex to compile
// return a[0] && f[0] || a[1] && f[1] || a[2] && f[2] || ...
Diagnostic(ErrorCode.ERR_InsufficientStack, "a").WithLocation(10, 16)
);
}
[Fact, WorkItem(7262, "https://github.com/dotnet/roslyn/issues/7262")]
public void TruncatePrecisionOnCast()
{
var source =
@"
class Test
{
static void Main()
{
float temp1 = (float)(23334800f / 5.5f);
System.Console.WriteLine((int)temp1);
const float temp2 = (float)(23334800f / 5.5f);
System.Console.WriteLine((int)temp2);
System.Console.WriteLine((int)(23334800f / 5.5f));
}
}
";
var expectedOutput =
@"4242691
4242691
4242691";
var result = CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput);
}
[Fact, WorkItem(17756, "https://github.com/dotnet/roslyn/issues/17756")]
public void TestCoalesceNotLvalue()
{
var source = @"
class Program
{
struct S1
{
public int field;
public int Increment() => field++;
}
static void Main()
{
S1 v = default(S1);
v.Increment();
((S1?)null ?? v).Increment();
System.Console.WriteLine(v.field);
}
}
";
string expectedOutput = @"1";
CompileAndVerify(source, expectedOutput: expectedOutput);
}
[Fact]
public void TestNullCoalesce_NullableWithDefault_Optimization()
{
var source = @"
class Program
{
struct S
{
int _a;
System.Guid _b;
public S(int a, System.Guid b)
{
_a = a;
_b = b;
}
public override string ToString() => (_a, _b).ToString();
}
static int CoalesceInt32(int? x)
{
return x ?? 0;
}
static T CoalesceGeneric<T>(T? x) where T : struct
{
return x ?? default(T);
}
static (bool a, System.Guid b) CoalesceTuple((bool a, System.Guid b)? x)
{
return x ?? default((bool a, System.Guid b));
}
static S CoalesceUserStruct(S? x)
{
return x ?? default(S);
}
static S CoalesceStructWithImplicitConstructor(S? x)
{
return x ?? new S();
}
static void Main()
{
System.Console.WriteLine(CoalesceInt32(42));
System.Console.WriteLine(CoalesceInt32(null));
System.Console.WriteLine(CoalesceGeneric<System.Guid>(new System.Guid(""44ed2f0b-c2fa-4791-81f6-97222fffa466"")));
System.Console.WriteLine(CoalesceGeneric<System.Guid>(null));
System.Console.WriteLine(CoalesceTuple((true, new System.Guid(""1c95cef0-1aae-4adb-a43c-54b2e7c083a0""))));
System.Console.WriteLine(CoalesceTuple(null));
System.Console.WriteLine(CoalesceUserStruct(new S(42, new System.Guid(""8683f371-81b4-45f6-aaed-1c665b371594""))));
System.Console.WriteLine(CoalesceUserStruct(null));
System.Console.WriteLine(CoalesceStructWithImplicitConstructor(new S()));
System.Console.WriteLine(CoalesceStructWithImplicitConstructor(null));
}
}";
var expectedOutput =
@"42
0
44ed2f0b-c2fa-4791-81f6-97222fffa466
00000000-0000-0000-0000-000000000000
(True, 1c95cef0-1aae-4adb-a43c-54b2e7c083a0)
(False, 00000000-0000-0000-0000-000000000000)
(42, 8683f371-81b4-45f6-aaed-1c665b371594)
(0, 00000000-0000-0000-0000-000000000000)
(0, 00000000-0000-0000-0000-000000000000)
(0, 00000000-0000-0000-0000-000000000000)";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyIL("Program.CoalesceInt32", @"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""int int?.GetValueOrDefault()""
IL_0007: ret
}");
comp.VerifyIL("Program.CoalesceGeneric<T>", @"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""T T?.GetValueOrDefault()""
IL_0007: ret
}");
comp.VerifyIL("Program.CoalesceTuple", @"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""System.ValueTuple<bool, System.Guid> System.ValueTuple<bool, System.Guid>?.GetValueOrDefault()""
IL_0007: ret
}");
comp.VerifyIL("Program.CoalesceUserStruct", @"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""Program.S Program.S?.GetValueOrDefault()""
IL_0007: ret
}");
comp.VerifyIL("Program.CoalesceStructWithImplicitConstructor", @"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""Program.S Program.S?.GetValueOrDefault()""
IL_0007: ret
}");
}
[Fact]
public void TestNullCoalesce_NullableWithConvertedDefault_Optimization()
{
var source = @"
class Program
{
static (bool a, System.Guid b, string c) CoalesceDifferentTupleNames((bool a, System.Guid b, string c)? x)
{
return x ?? default((bool c, System.Guid d, string e));
}
static void Main()
{
System.Console.WriteLine(CoalesceDifferentTupleNames((true, new System.Guid(""533d4d3b-5013-461e-ae9e-b98eb593d761""), ""value"")));
System.Console.WriteLine(CoalesceDifferentTupleNames(null));
}
}";
var expectedOutput =
@"(True, 533d4d3b-5013-461e-ae9e-b98eb593d761, value)
(False, 00000000-0000-0000-0000-000000000000, )";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyIL("Program.CoalesceDifferentTupleNames", @"{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""System.ValueTuple<bool, System.Guid, string> System.ValueTuple<bool, System.Guid, string>?.GetValueOrDefault()""
IL_0007: ret
}");
}
[Fact]
public void TestNullCoalesce_NullableWithNonDefault_NoOptimization()
{
var source = @"
class Program
{
static int CoalesceWithNonDefault1(int? x)
{
return x ?? 2;
}
static int CoalesceWithNonDefault2(int? x, int y)
{
return x ?? y;
}
static int? CoalesceWithNonDefault3(int? x, int? y)
{
return x ?? y;
}
static int? CoalesceWithNonDefault4(int? x)
{
return x ?? default(int?);
}
static void Main()
{
void WriteLine(object value) => System.Console.WriteLine(value?.ToString() ?? ""*null*"");
WriteLine(CoalesceWithNonDefault1(42));
WriteLine(CoalesceWithNonDefault1(null));
WriteLine(CoalesceWithNonDefault2(12, 34));
WriteLine(CoalesceWithNonDefault2(null, 34));
WriteLine(CoalesceWithNonDefault3(123, 456));
WriteLine(CoalesceWithNonDefault3(123, null));
WriteLine(CoalesceWithNonDefault3(null, 456));
WriteLine(CoalesceWithNonDefault3(null, null));
WriteLine(CoalesceWithNonDefault4(42));
WriteLine(CoalesceWithNonDefault4(null));
}
}";
var expectedOutput =
@"42
2
12
34
123
123
456
*null*
42
*null*";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyIL("Program.CoalesceWithNonDefault1", @"{
// Code size 21 (0x15)
.maxstack 1
.locals init (int? V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool int?.HasValue.get""
IL_0009: brtrue.s IL_000d
IL_000b: ldc.i4.2
IL_000c: ret
IL_000d: ldloca.s V_0
IL_000f: call ""int int?.GetValueOrDefault()""
IL_0014: ret
}");
comp.VerifyIL("Program.CoalesceWithNonDefault2", @"{
// Code size 21 (0x15)
.maxstack 1
.locals init (int? V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool int?.HasValue.get""
IL_0009: brtrue.s IL_000d
IL_000b: ldarg.1
IL_000c: ret
IL_000d: ldloca.s V_0
IL_000f: call ""int int?.GetValueOrDefault()""
IL_0014: ret
}");
comp.VerifyIL("Program.CoalesceWithNonDefault3", @"{
// Code size 15 (0xf)
.maxstack 1
.locals init (int? V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool int?.HasValue.get""
IL_0009: brtrue.s IL_000d
IL_000b: ldarg.1
IL_000c: ret
IL_000d: ldloc.0
IL_000e: ret
}");
comp.VerifyIL("Program.CoalesceWithNonDefault4", @"{
// Code size 23 (0x17)
.maxstack 1
.locals init (int? V_0,
int? V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool int?.HasValue.get""
IL_0009: brtrue.s IL_0015
IL_000b: ldloca.s V_1
IL_000d: initobj ""int?""
IL_0013: ldloc.1
IL_0014: ret
IL_0015: ldloc.0
IL_0016: ret
}");
}
[Fact]
public void TestNullCoalesce_NonNullableWithDefault_NoOptimization()
{
var source = @"
class Program
{
static string CoalesceNonNullableWithDefault(string x)
{
return x ?? default(string);
}
static void Main()
{
void WriteLine(object value) => System.Console.WriteLine(value?.ToString() ?? ""*null*"");
WriteLine(CoalesceNonNullableWithDefault(""value""));
WriteLine(CoalesceNonNullableWithDefault(null));
}
}";
var expectedOutput =
@"value
*null*";
var comp = CompileAndVerify(source, expectedOutput: expectedOutput);
comp.VerifyIL("Program.CoalesceNonNullableWithDefault", @"{
// Code size 7 (0x7)
.maxstack 2
IL_0000: ldarg.0
IL_0001: dup
IL_0002: brtrue.s IL_0006
IL_0004: pop
IL_0005: ldnull
IL_0006: ret
}");
}
[Fact]
public void TestNullCoalesce_NullableDefault_MissingGetValueOrDefault()
{
var source = @"
class Program
{
static int Coalesce(int? x)
{
return x ?? 0;
}
}";
var comp = CreateCompilation(source);
comp.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault);
comp.VerifyEmitDiagnostics(
// (6,16): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault'
// return x ?? 0;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "x").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(6, 16),
// (6,16): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault'
// return x ?? 0;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "x").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(6, 16)
);
}
[Fact]
public void TestNullCoalesce_UnconstrainedTypeParameter_OldLanguageVersion()
{
var source = @"
class C
{
void M<T>(T t1, T t2)
{
t1 = t1 ?? t2;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (6,14): error CS8652: The feature 'unconstrained type parameters in null coalescing operator' is not available in C# 7.3. Please use language version 8.0 or greater.
// t1 = t1 ?? t2;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "t1 ?? t2").WithArguments("unconstrained type parameters in null coalescing operator", "8.0").WithLocation(6, 14));
}
[Fact, WorkItem(41760, "https://github.com/dotnet/roslyn/issues/41760")]
public void NullableBoolOperatorSemantics_01()
{
// The C# specification has a section outlining the behavior of the bool operators `|` and `&`
// on operands of type `bool?`. We check that these are the semantics obeyed by the compiler.
var sourceStart = @"
using System;
public class C
{
bool T => true;
bool F => false;
static bool? True => true;
static bool? False => false;
static bool? Null => null;
static void Main()
{
C n = null;
C c = new C();
bool t = true;
bool f = false;
bool? nt = true;
bool? nf = false;
bool? nn = null;
";
var sourceEnd =
@" Console.WriteLine(""Done."");
}
static bool? And(bool? x, bool? y)
{
if (x == false || y == false)
return false;
if (x == null || y == null)
return null;
return true;
}
static bool? Or(bool? x, bool? y)
{
if (x == true || y == true)
return true;
if (x == null || y == null)
return null;
return false;
}
static bool? Xor(bool? x, bool? y)
{
if (x == null || y == null)
return null;
return x.Value != y.Value;
}
}
static class Assert
{
public static void Equal<T>(T expected, T actual, string message)
{
if (!object.Equals(expected, actual))
Console.WriteLine($""Wrong for {message,-15} Expected: {expected?.ToString() ?? ""null"",-5} Actual: {actual?.ToString() ?? ""null""}"");
}
}
";
var builder = new StringBuilder();
var forms = new string[]
{
"null",
"nn",
"true",
"t",
"nt",
"false",
"f",
"nf",
"c?.T",
"c?.F",
"n?.T",
"Null",
"True",
"False",
};
foreach (var left in forms)
{
foreach (var right in forms)
{
if (left == "null" && right == "null")
continue;
builder.AppendLine(@$" Assert.Equal<bool?>(Or({left}, {right}), {left} | {right}, ""{left} | {right}"");");
builder.AppendLine(@$" Assert.Equal<bool?>(And({left}, {right}), {left} & {right}, ""{left} & {right}"");");
if (left != "null" && right != "null")
builder.AppendLine(@$" Assert.Equal<bool?>(Xor({left}, {right}), {left} ^ {right}, ""{left} ^ {right}"");");
}
}
var source = sourceStart + builder.ToString() + sourceEnd;
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics(
);
CompileAndVerify(comp, expectedOutput: @"Done.");
}
[Fact, WorkItem(41760, "https://github.com/dotnet/roslyn/issues/41760")]
public void NullableBoolOperatorSemantics_02()
{
var source = @"
using System;
public class C
{
public bool BoolValue;
static void Main()
{
C obj = null;
Console.Write(obj?.BoolValue | true);
Console.Write(obj?.BoolValue & false);
}
}
";
var comp = CreateCompilation(source, options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics(
);
var cv = CompileAndVerify(comp, expectedOutput: @"TrueFalse");
cv.VerifyIL("C.Main", @"
{
// Code size 99 (0x63)
.maxstack 3
.locals init (bool? V_0,
bool? V_1)
IL_0000: ldnull
IL_0001: dup
IL_0002: dup
IL_0003: brtrue.s IL_0011
IL_0005: pop
IL_0006: ldloca.s V_1
IL_0008: initobj ""bool?""
IL_000e: ldloc.1
IL_000f: br.s IL_001b
IL_0011: ldfld ""bool C.BoolValue""
IL_0016: newobj ""bool?..ctor(bool)""
IL_001b: stloc.0
IL_001c: ldc.i4.1
IL_001d: brtrue.s IL_0022
IL_001f: ldloc.0
IL_0020: br.s IL_0028
IL_0022: ldc.i4.1
IL_0023: newobj ""bool?..ctor(bool)""
IL_0028: box ""bool?""
IL_002d: call ""void System.Console.Write(object)""
IL_0032: dup
IL_0033: brtrue.s IL_0041
IL_0035: pop
IL_0036: ldloca.s V_1
IL_0038: initobj ""bool?""
IL_003e: ldloc.1
IL_003f: br.s IL_004b
IL_0041: ldfld ""bool C.BoolValue""
IL_0046: newobj ""bool?..ctor(bool)""
IL_004b: stloc.0
IL_004c: ldc.i4.0
IL_004d: brtrue.s IL_0057
IL_004f: ldc.i4.0
IL_0050: newobj ""bool?..ctor(bool)""
IL_0055: br.s IL_0058
IL_0057: ldloc.0
IL_0058: box ""bool?""
IL_005d: call ""void System.Console.Write(object)""
IL_0062: ret
}
");
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Scripting/Core/Hosting/ObjectFormatter/CommonObjectFormatter.Visitor.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Microsoft.Cci;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Scripting.Hosting
{
using static ObjectFormatterHelpers;
using TypeInfo = System.Reflection.TypeInfo;
internal abstract partial class CommonObjectFormatter
{
private sealed partial class Visitor
{
private readonly CommonObjectFormatter _formatter;
private readonly BuilderOptions _builderOptions;
private CommonPrimitiveFormatterOptions _primitiveOptions;
private readonly CommonTypeNameFormatterOptions _typeNameOptions;
private MemberDisplayFormat _memberDisplayFormat;
private HashSet<object> _lazyVisitedObjects;
private HashSet<object> VisitedObjects
{
get
{
if (_lazyVisitedObjects == null)
{
_lazyVisitedObjects = new HashSet<object>(ReferenceEqualityComparer.Instance);
}
return _lazyVisitedObjects;
}
}
public Visitor(
CommonObjectFormatter formatter,
BuilderOptions builderOptions,
CommonPrimitiveFormatterOptions primitiveOptions,
CommonTypeNameFormatterOptions typeNameOptions,
MemberDisplayFormat memberDisplayFormat)
{
_formatter = formatter;
_builderOptions = builderOptions;
_primitiveOptions = primitiveOptions;
_typeNameOptions = typeNameOptions;
_memberDisplayFormat = memberDisplayFormat;
}
private Builder MakeMemberBuilder(int limit)
{
return new Builder(_builderOptions.WithMaximumOutputLength(Math.Min(_builderOptions.MaximumLineLength, limit)), suppressEllipsis: true);
}
public string FormatObject(object obj)
{
try
{
var builder = new Builder(_builderOptions, suppressEllipsis: false);
string _;
return FormatObjectRecursive(builder, obj, isRoot: true, debuggerDisplayName: out _).ToString();
}
catch (InsufficientExecutionStackException)
{
return ScriptingResources.StackOverflowWhileEvaluating;
}
}
private Builder FormatObjectRecursive(Builder result, object obj, bool isRoot, out string debuggerDisplayName)
{
// TODO (https://github.com/dotnet/roslyn/issues/6689): remove this
if (!isRoot && _memberDisplayFormat == MemberDisplayFormat.SeparateLines)
{
_memberDisplayFormat = MemberDisplayFormat.SingleLine;
}
debuggerDisplayName = null;
string primitive = _formatter.PrimitiveFormatter.FormatPrimitive(obj, _primitiveOptions);
if (primitive != null)
{
result.Append(primitive);
return result;
}
Type type = obj.GetType();
TypeInfo typeInfo = type.GetTypeInfo();
//
// Override KeyValuePair<,>.ToString() to get better dictionary elements formatting:
//
// { { format(key), format(value) }, ... }
// instead of
// { [key.ToString(), value.ToString()], ... }
//
// This is more general than overriding Dictionary<,> debugger proxy attribute since it applies on all
// types that return an array of KeyValuePair in their DebuggerDisplay to display items.
//
if (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == typeof(KeyValuePair<,>))
{
if (isRoot)
{
result.Append(_formatter.TypeNameFormatter.FormatTypeName(type, _typeNameOptions));
result.Append(' ');
}
FormatKeyValuePair(result, obj);
return result;
}
if (typeInfo.IsArray)
{
if (VisitedObjects.Add(obj))
{
FormatArray(result, (Array)obj);
VisitedObjects.Remove(obj);
}
else
{
result.AppendInfiniteRecursionMarker();
}
return result;
}
DebuggerDisplayAttribute debuggerDisplay = GetApplicableDebuggerDisplayAttribute(typeInfo);
if (debuggerDisplay != null)
{
debuggerDisplayName = debuggerDisplay.Name;
}
// Suppresses members if inlineMembers is true,
// does nothing otherwise.
bool suppressInlineMembers = false;
//
// TypeName(count) for ICollection implementers
// or
// TypeName([[DebuggerDisplay.Value]]) // Inline
// [[DebuggerDisplay.Value]] // Inline && !isRoot
// or
// [[ToString()]] if ToString overridden
// or
// TypeName
//
ICollection collection;
if ((collection = obj as ICollection) != null)
{
FormatCollectionHeader(result, collection);
}
else if (debuggerDisplay != null && !string.IsNullOrEmpty(debuggerDisplay.Value))
{
if (isRoot)
{
result.Append(_formatter.TypeNameFormatter.FormatTypeName(type, _typeNameOptions));
result.Append('(');
}
FormatWithEmbeddedExpressions(result, debuggerDisplay.Value, obj);
if (isRoot)
{
result.Append(')');
}
suppressInlineMembers = true;
}
else if (HasOverriddenToString(typeInfo))
{
ObjectToString(result, obj);
suppressInlineMembers = true;
}
else
{
result.Append(_formatter.TypeNameFormatter.FormatTypeName(type, _typeNameOptions));
}
MemberDisplayFormat memberFormat = _memberDisplayFormat;
if (memberFormat == MemberDisplayFormat.Hidden)
{
if (collection != null)
{
// NB: Collections specifically ignore MemberDisplayFormat.Hidden.
memberFormat = MemberDisplayFormat.SingleLine;
}
else
{
return result;
}
}
bool includeNonPublic = memberFormat == MemberDisplayFormat.SeparateLines;
bool inlineMembers = memberFormat == MemberDisplayFormat.SingleLine;
object proxy = GetDebuggerTypeProxy(obj);
if (proxy != null)
{
includeNonPublic = false;
suppressInlineMembers = false;
}
if (!suppressInlineMembers || !inlineMembers)
{
FormatMembers(result, obj, proxy, includeNonPublic, inlineMembers);
}
return result;
}
#region Members
private void FormatMembers(Builder result, object obj, object proxy, bool includeNonPublic, bool inlineMembers)
{
// TODO (tomat): we should not use recursion
RuntimeHelpers.EnsureSufficientExecutionStack();
result.Append(' ');
// Note: Even if we've seen it before, we show a header
if (!VisitedObjects.Add(obj))
{
result.AppendInfiniteRecursionMarker();
return;
}
bool membersFormatted = false;
// handle special types only if a proxy isn't defined
if (proxy == null)
{
IDictionary dictionary;
IEnumerable enumerable;
if ((dictionary = obj as IDictionary) != null)
{
FormatDictionaryMembers(result, dictionary, inlineMembers);
membersFormatted = true;
}
else if ((enumerable = obj as IEnumerable) != null)
{
FormatSequenceMembers(result, enumerable, inlineMembers);
membersFormatted = true;
}
}
if (!membersFormatted)
{
FormatObjectMembers(result, proxy ?? obj, obj.GetType().GetTypeInfo(), includeNonPublic, inlineMembers);
}
VisitedObjects.Remove(obj);
}
/// <summary>
/// Formats object members to a list.
///
/// Inline == false:
/// <code>
/// { A=true, B=false, C=new int[3] { 1, 2, 3 } }
/// </code>
///
/// Inline == true:
/// <code>
/// {
/// A: true,
/// B: false,
/// C: new int[3] { 1, 2, 3 }
/// }
/// </code>
/// </summary>
private void FormatObjectMembers(Builder result, object obj, TypeInfo preProxyTypeInfo, bool includeNonPublic, bool inline)
{
int lengthLimit = result.Remaining;
if (lengthLimit < 0)
{
return;
}
var members = new List<FormattedMember>();
// Limits the number of members added into the result. Some more members may be added than it will fit into the result
// and will be thrown away later but not many more.
FormatObjectMembersRecursive(members, obj, includeNonPublic, ref lengthLimit);
bool useCollectionFormat = UseCollectionFormat(members, preProxyTypeInfo);
result.AppendGroupOpening();
for (int i = 0; i < members.Count; i++)
{
result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline);
if (useCollectionFormat)
{
members[i].AppendAsCollectionEntry(result);
}
else
{
members[i].Append(result, inline ? "=" : ": ");
}
if (result.Remaining <= 0)
{
break;
}
}
result.AppendGroupClosing(inline);
}
private static bool UseCollectionFormat(IEnumerable<FormattedMember> members, TypeInfo originalType)
{
return typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(originalType) && members.All(member => member.Index >= 0);
}
/// <summary>
/// Enumerates sorted object members to display.
/// </summary>
private void FormatObjectMembersRecursive(List<FormattedMember> result, object obj, bool includeNonPublic, ref int lengthLimit)
{
Debug.Assert(obj != null);
var members = new List<MemberInfo>();
var type = obj.GetType().GetTypeInfo();
while (type != null)
{
members.AddRange(type.DeclaredFields.Where(f => !f.IsStatic));
members.AddRange(type.DeclaredProperties.Where(f => f.GetMethod != null && !f.GetMethod.IsStatic));
type = type.BaseType?.GetTypeInfo();
}
members.Sort((x, y) =>
{
// Need case-sensitive comparison here so that the order of members is
// always well-defined (members can differ by case only). And we don't want to
// depend on that order.
int comparisonResult = StringComparer.OrdinalIgnoreCase.Compare(x.Name, y.Name);
if (comparisonResult == 0)
{
comparisonResult = StringComparer.Ordinal.Compare(x.Name, y.Name);
}
return comparisonResult;
});
foreach (var member in members)
{
if (!_formatter.Filter.Include(member))
{
continue;
}
bool rootHidden = false, ignoreVisibility = false;
var browsable = (DebuggerBrowsableAttribute)member.GetCustomAttributes(typeof(DebuggerBrowsableAttribute), false).FirstOrDefault();
if (browsable != null)
{
if (browsable.State == DebuggerBrowsableState.Never)
{
continue;
}
ignoreVisibility = true;
rootHidden = browsable.State == DebuggerBrowsableState.RootHidden;
}
if (member is FieldInfo field)
{
if (!(includeNonPublic || ignoreVisibility || field.IsPublic || field.IsFamily || field.IsFamilyOrAssembly))
{
continue;
}
}
else
{
PropertyInfo property = (PropertyInfo)member;
var getter = property.GetMethod;
if (getter == null)
{
continue;
}
var setter = property.SetMethod;
// If not ignoring visibility include properties that has a visible getter or setter.
if (!(includeNonPublic || ignoreVisibility ||
getter.IsPublic || getter.IsFamily || getter.IsFamilyOrAssembly ||
(setter != null && (setter.IsPublic || setter.IsFamily || setter.IsFamilyOrAssembly))))
{
continue;
}
if (getter.GetParameters().Length > 0)
{
continue;
}
}
var debuggerDisplay = GetApplicableDebuggerDisplayAttribute(member);
if (debuggerDisplay != null)
{
string k = FormatWithEmbeddedExpressions(lengthLimit, debuggerDisplay.Name, obj) ?? member.Name;
string v = FormatWithEmbeddedExpressions(lengthLimit, debuggerDisplay.Value, obj) ?? string.Empty; // TODO: ?
if (!AddMember(result, new FormattedMember(-1, k, v), ref lengthLimit))
{
return;
}
continue;
}
Exception exception;
object value = GetMemberValue(member, obj, out exception);
if (exception != null)
{
var memberValueBuilder = MakeMemberBuilder(lengthLimit);
FormatException(memberValueBuilder, exception);
if (!AddMember(result, new FormattedMember(-1, member.Name, memberValueBuilder.ToString()), ref lengthLimit))
{
return;
}
continue;
}
if (rootHidden)
{
if (value != null && !VisitedObjects.Contains(value))
{
Array array;
if ((array = value as Array) != null) // TODO (tomat): n-dim arrays
{
int i = 0;
foreach (object item in array)
{
string name;
Builder valueBuilder = MakeMemberBuilder(lengthLimit);
FormatObjectRecursive(valueBuilder, item, isRoot: false, debuggerDisplayName: out name);
if (!string.IsNullOrEmpty(name))
{
name = FormatWithEmbeddedExpressions(MakeMemberBuilder(lengthLimit), name, item).ToString();
}
if (!AddMember(result, new FormattedMember(i, name, valueBuilder.ToString()), ref lengthLimit))
{
return;
}
i++;
}
}
else if (_formatter.PrimitiveFormatter.FormatPrimitive(value, _primitiveOptions) == null && VisitedObjects.Add(value))
{
FormatObjectMembersRecursive(result, value, includeNonPublic, ref lengthLimit);
VisitedObjects.Remove(value);
}
}
}
else
{
string name;
Builder valueBuilder = MakeMemberBuilder(lengthLimit);
FormatObjectRecursive(valueBuilder, value, isRoot: false, debuggerDisplayName: out name);
if (string.IsNullOrEmpty(name))
{
name = member.Name;
}
else
{
name = FormatWithEmbeddedExpressions(MakeMemberBuilder(lengthLimit), name, value).ToString();
}
if (!AddMember(result, new FormattedMember(-1, name, valueBuilder.ToString()), ref lengthLimit))
{
return;
}
}
}
}
private bool AddMember(List<FormattedMember> members, FormattedMember member, ref int remainingLength)
{
// Add this item even if we exceed the limit - its prefix might be appended to the result.
members.Add(member);
// We don't need to calculate an exact length, just a lower bound on the size.
// We can add more members to the result than it will eventually fit, we shouldn't add less.
// Add 2 more, even if only one or half of it fit, so that the separator is included in edge cases.
if (remainingLength == int.MinValue)
{
return false;
}
remainingLength -= member.MinimalLength;
if (remainingLength <= 0)
{
remainingLength = int.MinValue;
}
return true;
}
private void FormatException(Builder result, Exception exception)
{
result.Append("!<");
result.Append(_formatter.TypeNameFormatter.FormatTypeName(exception.GetType(), _typeNameOptions));
result.Append('>');
}
#endregion
#region Collections
private void FormatKeyValuePair(Builder result, object obj)
{
TypeInfo type = obj.GetType().GetTypeInfo();
object key = type.GetDeclaredProperty("Key").GetValue(obj, Array.Empty<object>());
object value = type.GetDeclaredProperty("Value").GetValue(obj, Array.Empty<object>());
string _;
result.AppendGroupOpening();
result.AppendCollectionItemSeparator(isFirst: true, inline: true);
FormatObjectRecursive(result, key, isRoot: false, debuggerDisplayName: out _);
result.AppendCollectionItemSeparator(isFirst: false, inline: true);
FormatObjectRecursive(result, value, isRoot: false, debuggerDisplayName: out _);
result.AppendGroupClosing(inline: true);
}
private void FormatCollectionHeader(Builder result, ICollection collection)
{
if (collection is Array array)
{
result.Append(_formatter.TypeNameFormatter.FormatArrayTypeName(array.GetType(), array, _typeNameOptions));
return;
}
result.Append(_formatter.TypeNameFormatter.FormatTypeName(collection.GetType(), _typeNameOptions));
try
{
result.Append('(');
result.Append(collection.Count.ToString());
result.Append(')');
}
catch (Exception)
{
// skip
}
}
private void FormatArray(Builder result, Array array)
{
FormatCollectionHeader(result, array);
// NB: Arrays specifically ignore MemberDisplayFormat.Hidden.
if (array.Rank > 1)
{
FormatMultidimensionalArrayElements(result, array, inline: _memberDisplayFormat != MemberDisplayFormat.SeparateLines);
}
else
{
result.Append(' ');
FormatSequenceMembers(result, array, inline: _memberDisplayFormat != MemberDisplayFormat.SeparateLines);
}
}
private void FormatDictionaryMembers(Builder result, IDictionary dict, bool inline)
{
result.AppendGroupOpening();
int i = 0;
try
{
IDictionaryEnumerator enumerator = dict.GetEnumerator();
IDisposable disposable = enumerator as IDisposable;
try
{
while (enumerator.MoveNext())
{
var entry = enumerator.Entry;
string _;
result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline);
result.AppendGroupOpening();
result.AppendCollectionItemSeparator(isFirst: true, inline: true);
FormatObjectRecursive(result, entry.Key, isRoot: false, debuggerDisplayName: out _);
result.AppendCollectionItemSeparator(isFirst: false, inline: true);
FormatObjectRecursive(result, entry.Value, isRoot: false, debuggerDisplayName: out _);
result.AppendGroupClosing(inline: true);
i++;
}
}
finally
{
if (disposable != null)
{
disposable.Dispose();
}
}
}
catch (Exception e)
{
result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline);
FormatException(result, e);
result.Append(' ');
result.Append(_builderOptions.Ellipsis);
}
result.AppendGroupClosing(inline);
}
private void FormatSequenceMembers(Builder result, IEnumerable sequence, bool inline)
{
result.AppendGroupOpening();
int i = 0;
try
{
foreach (var item in sequence)
{
string _;
result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline);
FormatObjectRecursive(result, item, isRoot: false, debuggerDisplayName: out _);
i++;
}
}
catch (Exception e)
{
result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline);
FormatException(result, e);
result.Append(" ...");
}
result.AppendGroupClosing(inline);
}
private void FormatMultidimensionalArrayElements(Builder result, Array array, bool inline)
{
Debug.Assert(array.Rank > 1);
if (array.Length == 0)
{
result.AppendCollectionItemSeparator(isFirst: true, inline: true);
result.AppendGroupOpening();
result.AppendGroupClosing(inline: true);
return;
}
int[] indices = new int[array.Rank];
for (int i = array.Rank - 1; i >= 0; i--)
{
indices[i] = array.GetLowerBound(i);
}
int nesting = 0;
int flatIndex = 0;
while (true)
{
// increment indices (lower index overflows to higher):
int i = indices.Length - 1;
while (indices[i] > array.GetUpperBound(i))
{
indices[i] = array.GetLowerBound(i);
result.AppendGroupClosing(inline: inline || nesting != 1);
nesting--;
i--;
if (i < 0)
{
return;
}
indices[i]++;
}
result.AppendCollectionItemSeparator(isFirst: flatIndex == 0, inline: inline || nesting != 1);
i = indices.Length - 1;
while (i >= 0 && indices[i] == array.GetLowerBound(i))
{
result.AppendGroupOpening();
nesting++;
// array isn't empty, so there is always an element following this separator
result.AppendCollectionItemSeparator(isFirst: true, inline: inline || nesting != 1);
i--;
}
string _;
FormatObjectRecursive(result, array.GetValue(indices), isRoot: false, debuggerDisplayName: out _);
indices[indices.Length - 1]++;
flatIndex++;
}
}
#endregion
#region Scalars
private bool IsTuple(object obj)
{
#if NETSTANDARD2_0
if (obj is null)
{
return false;
}
var type = obj.GetType();
if (!type.IsGenericType)
{
return false;
}
int backtick = type.FullName.IndexOf('`');
if (backtick < 0)
{
return false;
}
var nonGenericName = type.FullName[0..backtick];
return nonGenericName == "System.ValueTuple" || nonGenericName == "System.Tuple";
#else
return obj is ITuple;
#endif
}
private void ObjectToString(Builder result, object obj)
{
try
{
string str = obj.ToString();
if (IsTuple(obj))
{
result.Append(str);
}
else
{
result.Append('[');
result.Append(str);
result.Append(']');
}
}
catch (Exception e)
{
FormatException(result, e);
}
}
#endregion
#region DebuggerDisplay Embedded Expressions
/// <summary>
/// Evaluate a format string with possible member references enclosed in braces.
/// E.g. "goo = {GetGooString(),nq}, bar = {Bar}".
/// </summary>
/// <remarks>
/// Although in theory any expression is allowed to be embedded in the string such behavior is in practice fundamentally broken.
/// The attribute doesn't specify what language (VB, C#, F#, etc.) to use to parse these expressions. Even if it did all languages
/// would need to be able to evaluate each other language's expressions, which is not viable and the Expression Evaluator doesn't
/// work that way today. Instead it evaluates the embedded expressions in the language of the current method frame. When consuming
/// VB objects from C#, for example, the evaluation might fail due to language mismatch (evaluating VB expression using C# parser).
///
/// Therefore we limit the expressions to a simple language independent syntax: {clr-member-name} '(' ')' ',nq',
/// where parentheses and ,nq suffix (no-quotes) are optional and the name is an arbitrary CLR field, property, or method name.
/// We then resolve the member by name using case-sensitive lookup first with fallback to case insensitive and evaluate it.
/// If parentheses are present we only look for methods.
/// Only parameterless members are considered.
/// </remarks>
private string FormatWithEmbeddedExpressions(int lengthLimit, string format, object obj)
{
if (string.IsNullOrEmpty(format))
{
return null;
}
var builder = new Builder(_builderOptions.WithMaximumOutputLength(lengthLimit), suppressEllipsis: true);
return FormatWithEmbeddedExpressions(builder, format, obj).ToString();
}
private Builder FormatWithEmbeddedExpressions(Builder result, string format, object obj)
{
int i = 0;
while (i < format.Length)
{
char c = format[i++];
if (c == '{')
{
if (i >= 2 && format[i - 2] == '\\')
{
result.Append('{');
}
else
{
int expressionEnd = format.IndexOf('}', i);
bool noQuotes, callableOnly;
string memberName;
if (expressionEnd == -1 || (memberName = ParseSimpleMemberName(format, i, expressionEnd, out noQuotes, out callableOnly)) == null)
{
// the expression isn't properly formatted
result.Append(format, i - 1, format.Length - i + 1);
break;
}
MemberInfo member = ResolveMember(obj, memberName, callableOnly);
if (member == null)
{
result.AppendFormat(callableOnly ? "!<Method '{0}' not found>" : "!<Member '{0}' not found>", memberName);
}
else
{
Exception exception;
object value = GetMemberValue(member, obj, out exception);
if (exception != null)
{
FormatException(result, exception);
}
else
{
MemberDisplayFormat oldMemberDisplayFormat = _memberDisplayFormat;
CommonPrimitiveFormatterOptions oldPrimitiveOptions = _primitiveOptions;
_memberDisplayFormat = MemberDisplayFormat.Hidden;
_primitiveOptions = new CommonPrimitiveFormatterOptions(
_primitiveOptions.NumberRadix,
_primitiveOptions.IncludeCharacterCodePoints,
quoteStringsAndCharacters: !noQuotes,
escapeNonPrintableCharacters: _primitiveOptions.EscapeNonPrintableCharacters,
cultureInfo: _primitiveOptions.CultureInfo);
string _;
FormatObjectRecursive(result, value, isRoot: false, debuggerDisplayName: out _);
_primitiveOptions = oldPrimitiveOptions;
_memberDisplayFormat = oldMemberDisplayFormat;
}
}
i = expressionEnd + 1;
}
}
else
{
result.Append(c);
}
}
return result;
}
#endregion
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Microsoft.Cci;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Scripting.Hosting
{
using static ObjectFormatterHelpers;
using TypeInfo = System.Reflection.TypeInfo;
internal abstract partial class CommonObjectFormatter
{
private sealed partial class Visitor
{
private readonly CommonObjectFormatter _formatter;
private readonly BuilderOptions _builderOptions;
private CommonPrimitiveFormatterOptions _primitiveOptions;
private readonly CommonTypeNameFormatterOptions _typeNameOptions;
private MemberDisplayFormat _memberDisplayFormat;
private HashSet<object> _lazyVisitedObjects;
private HashSet<object> VisitedObjects
{
get
{
if (_lazyVisitedObjects == null)
{
_lazyVisitedObjects = new HashSet<object>(ReferenceEqualityComparer.Instance);
}
return _lazyVisitedObjects;
}
}
public Visitor(
CommonObjectFormatter formatter,
BuilderOptions builderOptions,
CommonPrimitiveFormatterOptions primitiveOptions,
CommonTypeNameFormatterOptions typeNameOptions,
MemberDisplayFormat memberDisplayFormat)
{
_formatter = formatter;
_builderOptions = builderOptions;
_primitiveOptions = primitiveOptions;
_typeNameOptions = typeNameOptions;
_memberDisplayFormat = memberDisplayFormat;
}
private Builder MakeMemberBuilder(int limit)
{
return new Builder(_builderOptions.WithMaximumOutputLength(Math.Min(_builderOptions.MaximumLineLength, limit)), suppressEllipsis: true);
}
public string FormatObject(object obj)
{
try
{
var builder = new Builder(_builderOptions, suppressEllipsis: false);
string _;
return FormatObjectRecursive(builder, obj, isRoot: true, debuggerDisplayName: out _).ToString();
}
catch (InsufficientExecutionStackException)
{
return ScriptingResources.StackOverflowWhileEvaluating;
}
}
private Builder FormatObjectRecursive(Builder result, object obj, bool isRoot, out string debuggerDisplayName)
{
// TODO (https://github.com/dotnet/roslyn/issues/6689): remove this
if (!isRoot && _memberDisplayFormat == MemberDisplayFormat.SeparateLines)
{
_memberDisplayFormat = MemberDisplayFormat.SingleLine;
}
debuggerDisplayName = null;
string primitive = _formatter.PrimitiveFormatter.FormatPrimitive(obj, _primitiveOptions);
if (primitive != null)
{
result.Append(primitive);
return result;
}
Type type = obj.GetType();
TypeInfo typeInfo = type.GetTypeInfo();
//
// Override KeyValuePair<,>.ToString() to get better dictionary elements formatting:
//
// { { format(key), format(value) }, ... }
// instead of
// { [key.ToString(), value.ToString()], ... }
//
// This is more general than overriding Dictionary<,> debugger proxy attribute since it applies on all
// types that return an array of KeyValuePair in their DebuggerDisplay to display items.
//
if (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == typeof(KeyValuePair<,>))
{
if (isRoot)
{
result.Append(_formatter.TypeNameFormatter.FormatTypeName(type, _typeNameOptions));
result.Append(' ');
}
FormatKeyValuePair(result, obj);
return result;
}
if (typeInfo.IsArray)
{
if (VisitedObjects.Add(obj))
{
FormatArray(result, (Array)obj);
VisitedObjects.Remove(obj);
}
else
{
result.AppendInfiniteRecursionMarker();
}
return result;
}
DebuggerDisplayAttribute debuggerDisplay = GetApplicableDebuggerDisplayAttribute(typeInfo);
if (debuggerDisplay != null)
{
debuggerDisplayName = debuggerDisplay.Name;
}
// Suppresses members if inlineMembers is true,
// does nothing otherwise.
bool suppressInlineMembers = false;
//
// TypeName(count) for ICollection implementers
// or
// TypeName([[DebuggerDisplay.Value]]) // Inline
// [[DebuggerDisplay.Value]] // Inline && !isRoot
// or
// [[ToString()]] if ToString overridden
// or
// TypeName
//
ICollection collection;
if ((collection = obj as ICollection) != null)
{
FormatCollectionHeader(result, collection);
}
else if (debuggerDisplay != null && !string.IsNullOrEmpty(debuggerDisplay.Value))
{
if (isRoot)
{
result.Append(_formatter.TypeNameFormatter.FormatTypeName(type, _typeNameOptions));
result.Append('(');
}
FormatWithEmbeddedExpressions(result, debuggerDisplay.Value, obj);
if (isRoot)
{
result.Append(')');
}
suppressInlineMembers = true;
}
else if (HasOverriddenToString(typeInfo))
{
ObjectToString(result, obj);
suppressInlineMembers = true;
}
else
{
result.Append(_formatter.TypeNameFormatter.FormatTypeName(type, _typeNameOptions));
}
MemberDisplayFormat memberFormat = _memberDisplayFormat;
if (memberFormat == MemberDisplayFormat.Hidden)
{
if (collection != null)
{
// NB: Collections specifically ignore MemberDisplayFormat.Hidden.
memberFormat = MemberDisplayFormat.SingleLine;
}
else
{
return result;
}
}
bool includeNonPublic = memberFormat == MemberDisplayFormat.SeparateLines;
bool inlineMembers = memberFormat == MemberDisplayFormat.SingleLine;
object proxy = GetDebuggerTypeProxy(obj);
if (proxy != null)
{
includeNonPublic = false;
suppressInlineMembers = false;
}
if (!suppressInlineMembers || !inlineMembers)
{
FormatMembers(result, obj, proxy, includeNonPublic, inlineMembers);
}
return result;
}
#region Members
private void FormatMembers(Builder result, object obj, object proxy, bool includeNonPublic, bool inlineMembers)
{
// TODO (tomat): we should not use recursion
RuntimeHelpers.EnsureSufficientExecutionStack();
result.Append(' ');
// Note: Even if we've seen it before, we show a header
if (!VisitedObjects.Add(obj))
{
result.AppendInfiniteRecursionMarker();
return;
}
bool membersFormatted = false;
// handle special types only if a proxy isn't defined
if (proxy == null)
{
IDictionary dictionary;
IEnumerable enumerable;
if ((dictionary = obj as IDictionary) != null)
{
FormatDictionaryMembers(result, dictionary, inlineMembers);
membersFormatted = true;
}
else if ((enumerable = obj as IEnumerable) != null)
{
FormatSequenceMembers(result, enumerable, inlineMembers);
membersFormatted = true;
}
}
if (!membersFormatted)
{
FormatObjectMembers(result, proxy ?? obj, obj.GetType().GetTypeInfo(), includeNonPublic, inlineMembers);
}
VisitedObjects.Remove(obj);
}
/// <summary>
/// Formats object members to a list.
///
/// Inline == false:
/// <code>
/// { A=true, B=false, C=new int[3] { 1, 2, 3 } }
/// </code>
///
/// Inline == true:
/// <code>
/// {
/// A: true,
/// B: false,
/// C: new int[3] { 1, 2, 3 }
/// }
/// </code>
/// </summary>
private void FormatObjectMembers(Builder result, object obj, TypeInfo preProxyTypeInfo, bool includeNonPublic, bool inline)
{
int lengthLimit = result.Remaining;
if (lengthLimit < 0)
{
return;
}
var members = new List<FormattedMember>();
// Limits the number of members added into the result. Some more members may be added than it will fit into the result
// and will be thrown away later but not many more.
FormatObjectMembersRecursive(members, obj, includeNonPublic, ref lengthLimit);
bool useCollectionFormat = UseCollectionFormat(members, preProxyTypeInfo);
result.AppendGroupOpening();
for (int i = 0; i < members.Count; i++)
{
result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline);
if (useCollectionFormat)
{
members[i].AppendAsCollectionEntry(result);
}
else
{
members[i].Append(result, inline ? "=" : ": ");
}
if (result.Remaining <= 0)
{
break;
}
}
result.AppendGroupClosing(inline);
}
private static bool UseCollectionFormat(IEnumerable<FormattedMember> members, TypeInfo originalType)
{
return typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(originalType) && members.All(member => member.Index >= 0);
}
/// <summary>
/// Enumerates sorted object members to display.
/// </summary>
private void FormatObjectMembersRecursive(List<FormattedMember> result, object obj, bool includeNonPublic, ref int lengthLimit)
{
Debug.Assert(obj != null);
var members = new List<MemberInfo>();
var type = obj.GetType().GetTypeInfo();
while (type != null)
{
members.AddRange(type.DeclaredFields.Where(f => !f.IsStatic));
members.AddRange(type.DeclaredProperties.Where(f => f.GetMethod != null && !f.GetMethod.IsStatic));
type = type.BaseType?.GetTypeInfo();
}
members.Sort((x, y) =>
{
// Need case-sensitive comparison here so that the order of members is
// always well-defined (members can differ by case only). And we don't want to
// depend on that order.
int comparisonResult = StringComparer.OrdinalIgnoreCase.Compare(x.Name, y.Name);
if (comparisonResult == 0)
{
comparisonResult = StringComparer.Ordinal.Compare(x.Name, y.Name);
}
return comparisonResult;
});
foreach (var member in members)
{
if (!_formatter.Filter.Include(member))
{
continue;
}
bool rootHidden = false, ignoreVisibility = false;
var browsable = (DebuggerBrowsableAttribute)member.GetCustomAttributes(typeof(DebuggerBrowsableAttribute), false).FirstOrDefault();
if (browsable != null)
{
if (browsable.State == DebuggerBrowsableState.Never)
{
continue;
}
ignoreVisibility = true;
rootHidden = browsable.State == DebuggerBrowsableState.RootHidden;
}
if (member is FieldInfo field)
{
if (!(includeNonPublic || ignoreVisibility || field.IsPublic || field.IsFamily || field.IsFamilyOrAssembly))
{
continue;
}
}
else
{
PropertyInfo property = (PropertyInfo)member;
var getter = property.GetMethod;
if (getter == null)
{
continue;
}
var setter = property.SetMethod;
// If not ignoring visibility include properties that has a visible getter or setter.
if (!(includeNonPublic || ignoreVisibility ||
getter.IsPublic || getter.IsFamily || getter.IsFamilyOrAssembly ||
(setter != null && (setter.IsPublic || setter.IsFamily || setter.IsFamilyOrAssembly))))
{
continue;
}
if (getter.GetParameters().Length > 0)
{
continue;
}
}
var debuggerDisplay = GetApplicableDebuggerDisplayAttribute(member);
if (debuggerDisplay != null)
{
string k = FormatWithEmbeddedExpressions(lengthLimit, debuggerDisplay.Name, obj) ?? member.Name;
string v = FormatWithEmbeddedExpressions(lengthLimit, debuggerDisplay.Value, obj) ?? string.Empty; // TODO: ?
if (!AddMember(result, new FormattedMember(-1, k, v), ref lengthLimit))
{
return;
}
continue;
}
Exception exception;
object value = GetMemberValue(member, obj, out exception);
if (exception != null)
{
var memberValueBuilder = MakeMemberBuilder(lengthLimit);
FormatException(memberValueBuilder, exception);
if (!AddMember(result, new FormattedMember(-1, member.Name, memberValueBuilder.ToString()), ref lengthLimit))
{
return;
}
continue;
}
if (rootHidden)
{
if (value != null && !VisitedObjects.Contains(value))
{
Array array;
if ((array = value as Array) != null) // TODO (tomat): n-dim arrays
{
int i = 0;
foreach (object item in array)
{
string name;
Builder valueBuilder = MakeMemberBuilder(lengthLimit);
FormatObjectRecursive(valueBuilder, item, isRoot: false, debuggerDisplayName: out name);
if (!string.IsNullOrEmpty(name))
{
name = FormatWithEmbeddedExpressions(MakeMemberBuilder(lengthLimit), name, item).ToString();
}
if (!AddMember(result, new FormattedMember(i, name, valueBuilder.ToString()), ref lengthLimit))
{
return;
}
i++;
}
}
else if (_formatter.PrimitiveFormatter.FormatPrimitive(value, _primitiveOptions) == null && VisitedObjects.Add(value))
{
FormatObjectMembersRecursive(result, value, includeNonPublic, ref lengthLimit);
VisitedObjects.Remove(value);
}
}
}
else
{
string name;
Builder valueBuilder = MakeMemberBuilder(lengthLimit);
FormatObjectRecursive(valueBuilder, value, isRoot: false, debuggerDisplayName: out name);
if (string.IsNullOrEmpty(name))
{
name = member.Name;
}
else
{
name = FormatWithEmbeddedExpressions(MakeMemberBuilder(lengthLimit), name, value).ToString();
}
if (!AddMember(result, new FormattedMember(-1, name, valueBuilder.ToString()), ref lengthLimit))
{
return;
}
}
}
}
private bool AddMember(List<FormattedMember> members, FormattedMember member, ref int remainingLength)
{
// Add this item even if we exceed the limit - its prefix might be appended to the result.
members.Add(member);
// We don't need to calculate an exact length, just a lower bound on the size.
// We can add more members to the result than it will eventually fit, we shouldn't add less.
// Add 2 more, even if only one or half of it fit, so that the separator is included in edge cases.
if (remainingLength == int.MinValue)
{
return false;
}
remainingLength -= member.MinimalLength;
if (remainingLength <= 0)
{
remainingLength = int.MinValue;
}
return true;
}
private void FormatException(Builder result, Exception exception)
{
result.Append("!<");
result.Append(_formatter.TypeNameFormatter.FormatTypeName(exception.GetType(), _typeNameOptions));
result.Append('>');
}
#endregion
#region Collections
private void FormatKeyValuePair(Builder result, object obj)
{
TypeInfo type = obj.GetType().GetTypeInfo();
object key = type.GetDeclaredProperty("Key").GetValue(obj, Array.Empty<object>());
object value = type.GetDeclaredProperty("Value").GetValue(obj, Array.Empty<object>());
string _;
result.AppendGroupOpening();
result.AppendCollectionItemSeparator(isFirst: true, inline: true);
FormatObjectRecursive(result, key, isRoot: false, debuggerDisplayName: out _);
result.AppendCollectionItemSeparator(isFirst: false, inline: true);
FormatObjectRecursive(result, value, isRoot: false, debuggerDisplayName: out _);
result.AppendGroupClosing(inline: true);
}
private void FormatCollectionHeader(Builder result, ICollection collection)
{
if (collection is Array array)
{
result.Append(_formatter.TypeNameFormatter.FormatArrayTypeName(array.GetType(), array, _typeNameOptions));
return;
}
result.Append(_formatter.TypeNameFormatter.FormatTypeName(collection.GetType(), _typeNameOptions));
try
{
result.Append('(');
result.Append(collection.Count.ToString());
result.Append(')');
}
catch (Exception)
{
// skip
}
}
private void FormatArray(Builder result, Array array)
{
FormatCollectionHeader(result, array);
// NB: Arrays specifically ignore MemberDisplayFormat.Hidden.
if (array.Rank > 1)
{
FormatMultidimensionalArrayElements(result, array, inline: _memberDisplayFormat != MemberDisplayFormat.SeparateLines);
}
else
{
result.Append(' ');
FormatSequenceMembers(result, array, inline: _memberDisplayFormat != MemberDisplayFormat.SeparateLines);
}
}
private void FormatDictionaryMembers(Builder result, IDictionary dict, bool inline)
{
result.AppendGroupOpening();
int i = 0;
try
{
IDictionaryEnumerator enumerator = dict.GetEnumerator();
IDisposable disposable = enumerator as IDisposable;
try
{
while (enumerator.MoveNext())
{
var entry = enumerator.Entry;
string _;
result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline);
result.AppendGroupOpening();
result.AppendCollectionItemSeparator(isFirst: true, inline: true);
FormatObjectRecursive(result, entry.Key, isRoot: false, debuggerDisplayName: out _);
result.AppendCollectionItemSeparator(isFirst: false, inline: true);
FormatObjectRecursive(result, entry.Value, isRoot: false, debuggerDisplayName: out _);
result.AppendGroupClosing(inline: true);
i++;
}
}
finally
{
if (disposable != null)
{
disposable.Dispose();
}
}
}
catch (Exception e)
{
result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline);
FormatException(result, e);
result.Append(' ');
result.Append(_builderOptions.Ellipsis);
}
result.AppendGroupClosing(inline);
}
private void FormatSequenceMembers(Builder result, IEnumerable sequence, bool inline)
{
result.AppendGroupOpening();
int i = 0;
try
{
foreach (var item in sequence)
{
string _;
result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline);
FormatObjectRecursive(result, item, isRoot: false, debuggerDisplayName: out _);
i++;
}
}
catch (Exception e)
{
result.AppendCollectionItemSeparator(isFirst: i == 0, inline: inline);
FormatException(result, e);
result.Append(" ...");
}
result.AppendGroupClosing(inline);
}
private void FormatMultidimensionalArrayElements(Builder result, Array array, bool inline)
{
Debug.Assert(array.Rank > 1);
if (array.Length == 0)
{
result.AppendCollectionItemSeparator(isFirst: true, inline: true);
result.AppendGroupOpening();
result.AppendGroupClosing(inline: true);
return;
}
int[] indices = new int[array.Rank];
for (int i = array.Rank - 1; i >= 0; i--)
{
indices[i] = array.GetLowerBound(i);
}
int nesting = 0;
int flatIndex = 0;
while (true)
{
// increment indices (lower index overflows to higher):
int i = indices.Length - 1;
while (indices[i] > array.GetUpperBound(i))
{
indices[i] = array.GetLowerBound(i);
result.AppendGroupClosing(inline: inline || nesting != 1);
nesting--;
i--;
if (i < 0)
{
return;
}
indices[i]++;
}
result.AppendCollectionItemSeparator(isFirst: flatIndex == 0, inline: inline || nesting != 1);
i = indices.Length - 1;
while (i >= 0 && indices[i] == array.GetLowerBound(i))
{
result.AppendGroupOpening();
nesting++;
// array isn't empty, so there is always an element following this separator
result.AppendCollectionItemSeparator(isFirst: true, inline: inline || nesting != 1);
i--;
}
string _;
FormatObjectRecursive(result, array.GetValue(indices), isRoot: false, debuggerDisplayName: out _);
indices[indices.Length - 1]++;
flatIndex++;
}
}
#endregion
#region Scalars
private bool IsTuple(object obj)
{
#if NETSTANDARD2_0
if (obj is null)
{
return false;
}
var type = obj.GetType();
if (!type.IsGenericType)
{
return false;
}
int backtick = type.FullName.IndexOf('`');
if (backtick < 0)
{
return false;
}
var nonGenericName = type.FullName[0..backtick];
return nonGenericName == "System.ValueTuple" || nonGenericName == "System.Tuple";
#else
return obj is ITuple;
#endif
}
private void ObjectToString(Builder result, object obj)
{
try
{
string str = obj.ToString();
if (IsTuple(obj))
{
result.Append(str);
}
else
{
result.Append('[');
result.Append(str);
result.Append(']');
}
}
catch (Exception e)
{
FormatException(result, e);
}
}
#endregion
#region DebuggerDisplay Embedded Expressions
/// <summary>
/// Evaluate a format string with possible member references enclosed in braces.
/// E.g. "goo = {GetGooString(),nq}, bar = {Bar}".
/// </summary>
/// <remarks>
/// Although in theory any expression is allowed to be embedded in the string such behavior is in practice fundamentally broken.
/// The attribute doesn't specify what language (VB, C#, F#, etc.) to use to parse these expressions. Even if it did all languages
/// would need to be able to evaluate each other language's expressions, which is not viable and the Expression Evaluator doesn't
/// work that way today. Instead it evaluates the embedded expressions in the language of the current method frame. When consuming
/// VB objects from C#, for example, the evaluation might fail due to language mismatch (evaluating VB expression using C# parser).
///
/// Therefore we limit the expressions to a simple language independent syntax: {clr-member-name} '(' ')' ',nq',
/// where parentheses and ,nq suffix (no-quotes) are optional and the name is an arbitrary CLR field, property, or method name.
/// We then resolve the member by name using case-sensitive lookup first with fallback to case insensitive and evaluate it.
/// If parentheses are present we only look for methods.
/// Only parameterless members are considered.
/// </remarks>
private string FormatWithEmbeddedExpressions(int lengthLimit, string format, object obj)
{
if (string.IsNullOrEmpty(format))
{
return null;
}
var builder = new Builder(_builderOptions.WithMaximumOutputLength(lengthLimit), suppressEllipsis: true);
return FormatWithEmbeddedExpressions(builder, format, obj).ToString();
}
private Builder FormatWithEmbeddedExpressions(Builder result, string format, object obj)
{
int i = 0;
while (i < format.Length)
{
char c = format[i++];
if (c == '{')
{
if (i >= 2 && format[i - 2] == '\\')
{
result.Append('{');
}
else
{
int expressionEnd = format.IndexOf('}', i);
bool noQuotes, callableOnly;
string memberName;
if (expressionEnd == -1 || (memberName = ParseSimpleMemberName(format, i, expressionEnd, out noQuotes, out callableOnly)) == null)
{
// the expression isn't properly formatted
result.Append(format, i - 1, format.Length - i + 1);
break;
}
MemberInfo member = ResolveMember(obj, memberName, callableOnly);
if (member == null)
{
result.AppendFormat(callableOnly ? "!<Method '{0}' not found>" : "!<Member '{0}' not found>", memberName);
}
else
{
Exception exception;
object value = GetMemberValue(member, obj, out exception);
if (exception != null)
{
FormatException(result, exception);
}
else
{
MemberDisplayFormat oldMemberDisplayFormat = _memberDisplayFormat;
CommonPrimitiveFormatterOptions oldPrimitiveOptions = _primitiveOptions;
_memberDisplayFormat = MemberDisplayFormat.Hidden;
_primitiveOptions = new CommonPrimitiveFormatterOptions(
_primitiveOptions.NumberRadix,
_primitiveOptions.IncludeCharacterCodePoints,
quoteStringsAndCharacters: !noQuotes,
escapeNonPrintableCharacters: _primitiveOptions.EscapeNonPrintableCharacters,
cultureInfo: _primitiveOptions.CultureInfo);
string _;
FormatObjectRecursive(result, value, isRoot: false, debuggerDisplayName: out _);
_primitiveOptions = oldPrimitiveOptions;
_memberDisplayFormat = oldMemberDisplayFormat;
}
}
i = expressionEnd + 1;
}
}
else
{
result.Append(c);
}
}
return result;
}
#endregion
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/CSharp/Portable/BraceCompletion/CurlyBraceCompletionService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.BraceCompletion;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Formatting;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Indentation;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.BraceCompletion
{
[Export(LanguageNames.CSharp, typeof(IBraceCompletionService)), Shared]
internal class CurlyBraceCompletionService : AbstractBraceCompletionService
{
/// <summary>
/// Annotation used to find the closing brace location after formatting changes are applied.
/// The closing brace location is then used as the caret location.
/// </summary>
private static readonly SyntaxAnnotation s_closingBraceSyntaxAnnotation = new(nameof(s_closingBraceSyntaxAnnotation));
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CurlyBraceCompletionService()
{
}
protected override char OpeningBrace => CurlyBrace.OpenCharacter;
protected override char ClosingBrace => CurlyBrace.CloseCharacter;
public override Task<bool> AllowOverTypeAsync(BraceCompletionContext context, CancellationToken cancellationToken)
=> AllowOverTypeInUserCodeWithValidClosingTokenAsync(context, cancellationToken);
public override async Task<BraceCompletionResult?> GetTextChangesAfterCompletionAsync(BraceCompletionContext braceCompletionContext, CancellationToken cancellationToken)
{
var documentOptions = await braceCompletionContext.Document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
// After the closing brace is completed we need to format the span from the opening point to the closing point.
// E.g. when the user triggers completion for an if statement ($$ is the caret location) we insert braces to get
// if (true){$$}
// We then need to format this to
// if (true) { $$}
var (formattingChanges, finalCurlyBraceEnd) = await FormatTrackingSpanAsync(
braceCompletionContext.Document,
braceCompletionContext.OpeningPoint,
braceCompletionContext.ClosingPoint,
shouldHonorAutoFormattingOnCloseBraceOption: true,
// We're not trying to format the indented block here, so no need to pass in additional rules.
braceFormattingIndentationRules: ImmutableArray<AbstractFormattingRule>.Empty,
documentOptions,
cancellationToken).ConfigureAwait(false);
if (formattingChanges.IsEmpty)
{
return null;
}
// The caret location should be at the start of the closing brace character.
var originalText = await braceCompletionContext.Document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var formattedText = originalText.WithChanges(formattingChanges);
var caretLocation = formattedText.Lines.GetLinePosition(finalCurlyBraceEnd - 1);
return new BraceCompletionResult(formattingChanges, caretLocation);
}
public override async Task<BraceCompletionResult?> GetTextChangeAfterReturnAsync(
BraceCompletionContext context,
DocumentOptionSet documentOptions,
CancellationToken cancellationToken)
{
var document = context.Document;
var closingPoint = context.ClosingPoint;
var openingPoint = context.OpeningPoint;
var originalDocumentText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
// check whether shape of the braces are what we support
// shape must be either "{|}" or "{ }". | is where caret is. otherwise, we don't do any special behavior
if (!ContainsOnlyWhitespace(originalDocumentText, openingPoint, closingPoint))
{
return null;
}
var openingPointLine = originalDocumentText.Lines.GetLineFromPosition(openingPoint).LineNumber;
var closingPointLine = originalDocumentText.Lines.GetLineFromPosition(closingPoint).LineNumber;
// If there are already multiple empty lines between the braces, don't do anything.
// We need to allow a single empty line between the braces to account for razor scenarios where they insert a line.
if (closingPointLine - openingPointLine > 2)
{
return null;
}
// If there is not already an empty line inserted between the braces, insert one.
TextChange? newLineEdit = null;
var textToFormat = originalDocumentText;
if (closingPointLine - openingPointLine == 1)
{
var newLineString = documentOptions.GetOption(FormattingOptions2.NewLine);
newLineEdit = new TextChange(new TextSpan(closingPoint - 1, 0), newLineString);
textToFormat = originalDocumentText.WithChanges(newLineEdit.Value);
// Modify the closing point location to adjust for the newly inserted line.
closingPoint += newLineString.Length;
}
// Format the text that contains the newly inserted line.
var (formattingChanges, newClosingPoint) = await FormatTrackingSpanAsync(
document.WithText(textToFormat),
openingPoint,
closingPoint,
shouldHonorAutoFormattingOnCloseBraceOption: false,
braceFormattingIndentationRules: GetBraceIndentationFormattingRules(documentOptions),
documentOptions,
cancellationToken).ConfigureAwait(false);
closingPoint = newClosingPoint;
var formattedText = textToFormat.WithChanges(formattingChanges);
// Get the empty line between the curly braces.
var desiredCaretLine = GetLineBetweenCurlys(closingPoint, formattedText);
Debug.Assert(desiredCaretLine.GetFirstNonWhitespacePosition() == null, "the line between the formatted braces is not empty");
// Set the caret position to the properly indented column in the desired line.
var newDocument = document.WithText(formattedText);
var newDocumentText = await newDocument.GetTextAsync(cancellationToken).ConfigureAwait(false);
var caretPosition = GetIndentedLinePosition(newDocument, newDocumentText, desiredCaretLine.LineNumber, cancellationToken);
// The new line edit is calculated against the original text, d0, to get text d1.
// The formatting edits are calculated against d1 to get text d2.
// Merge the formatting and new line edits into a set of whitespace only text edits that all apply to d0.
var overallChanges = newLineEdit != null ? GetMergedChanges(newLineEdit.Value, formattingChanges, formattedText) : formattingChanges;
return new BraceCompletionResult(overallChanges, caretPosition);
static TextLine GetLineBetweenCurlys(int closingPosition, SourceText text)
{
var closingBraceLineNumber = text.Lines.GetLineFromPosition(closingPosition - 1).LineNumber;
return text.Lines[closingBraceLineNumber - 1];
}
static LinePosition GetIndentedLinePosition(Document document, SourceText sourceText, int lineNumber, CancellationToken cancellationToken)
{
var indentationService = document.GetRequiredLanguageService<IIndentationService>();
var indentation = indentationService.GetIndentation(document, lineNumber, cancellationToken);
var baseLinePosition = sourceText.Lines.GetLinePosition(indentation.BasePosition);
var offsetOfBacePosition = baseLinePosition.Character;
var totalOffset = offsetOfBacePosition + indentation.Offset;
var indentedLinePosition = new LinePosition(lineNumber, totalOffset);
return indentedLinePosition;
}
static ImmutableArray<TextChange> GetMergedChanges(TextChange newLineEdit, ImmutableArray<TextChange> formattingChanges, SourceText formattedText)
{
var newRanges = TextChangeRangeExtensions.Merge(
ImmutableArray.Create(newLineEdit.ToTextChangeRange()),
formattingChanges.SelectAsArray(f => f.ToTextChangeRange()));
using var _ = ArrayBuilder<TextChange>.GetInstance(out var mergedChanges);
var amountToShift = 0;
foreach (var newRange in newRanges)
{
var newTextChangeSpan = newRange.Span;
// Get the text to put in the text change by looking at the span in the formatted text.
// As the new range start is relative to the original text, we need to adjust it assuming the previous changes were applied
// to get the correct start location in the formatted text.
// E.g. with changes
// 1. Insert "hello" at 2
// 2. Insert "goodbye" at 3
// "goodbye" is after "hello" at location 3 + 5 (length of "hello") in the new text.
var newTextChangeText = formattedText.GetSubText(new TextSpan(newRange.Span.Start + amountToShift, newRange.NewLength)).ToString();
amountToShift += (newRange.NewLength - newRange.Span.Length);
mergedChanges.Add(new TextChange(newTextChangeSpan, newTextChangeText));
}
return mergedChanges.ToImmutable();
}
}
public override async Task<bool> CanProvideBraceCompletionAsync(char brace, int openingPosition, Document document, CancellationToken cancellationToken)
{
// Only potentially valid for curly brace completion if not in an interpolation brace completion context.
if (OpeningBrace == brace && await InterpolationBraceCompletionService.IsPositionInInterpolationContextAsync(document, openingPosition, cancellationToken).ConfigureAwait(false))
{
return false;
}
return await base.CanProvideBraceCompletionAsync(brace, openingPosition, document, cancellationToken).ConfigureAwait(false);
}
protected override bool IsValidOpeningBraceToken(SyntaxToken token)
=> token.IsKind(SyntaxKind.OpenBraceToken) && !token.Parent.IsKind(SyntaxKind.Interpolation);
protected override bool IsValidClosingBraceToken(SyntaxToken token)
=> token.IsKind(SyntaxKind.CloseBraceToken);
private static bool ContainsOnlyWhitespace(SourceText text, int openingPosition, int closingBraceEndPoint)
{
// Set the start point to the character after the opening brace.
var start = openingPosition + 1;
// Set the end point to the closing brace start character position.
var end = closingBraceEndPoint - 1;
for (var i = start; i < end; i++)
{
if (!char.IsWhiteSpace(text[i]))
{
return false;
}
}
return true;
}
/// <summary>
/// Formats the span between the opening and closing points, options permitting.
/// Returns the text changes that should be applied to the input document to
/// get the formatted text and the end of the close curly brace in the formatted text.
/// </summary>
private static async Task<(ImmutableArray<TextChange> textChanges, int finalCurlyBraceEnd)> FormatTrackingSpanAsync(
Document document,
int openingPoint,
int closingPoint,
bool shouldHonorAutoFormattingOnCloseBraceOption,
ImmutableArray<AbstractFormattingRule> braceFormattingIndentationRules,
DocumentOptionSet documentOptions,
CancellationToken cancellationToken)
{
var option = document.Project.Solution.Options.GetOption(BraceCompletionOptions.AutoFormattingOnCloseBrace, document.Project.Language);
if (!option && shouldHonorAutoFormattingOnCloseBraceOption)
{
return (ImmutableArray<TextChange>.Empty, closingPoint);
}
// Annotate the original closing brace so we can find it after formatting.
document = await GetDocumentWithAnnotatedClosingBraceAsync(document, closingPoint, cancellationToken).ConfigureAwait(false);
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var startPoint = openingPoint;
var endPoint = closingPoint;
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
// Only format outside of the completed braces if they're on the same line for array/collection/object initializer expressions.
// Example: `var x = new int[]{}`:
// Correct: `var x = new int[] {}`
// Incorrect: `var x = new int[] { }`
// This is a heuristic to prevent brace completion from breaking user expectation/muscle memory in common scenarios.
// see bug Devdiv:823958
if (text.Lines.GetLineFromPosition(startPoint) == text.Lines.GetLineFromPosition(endPoint))
{
var startToken = root.FindToken(startPoint, findInsideTrivia: true);
if (startToken.IsKind(SyntaxKind.OpenBraceToken) &&
(startToken.Parent?.IsInitializerForArrayOrCollectionCreationExpression() == true ||
startToken.Parent is AnonymousObjectCreationExpressionSyntax))
{
// Since the braces are next to each other the span to format is everything up to the opening brace start.
endPoint = startToken.SpanStart;
}
}
var style = documentOptions.GetOption(FormattingOptions.SmartIndent);
if (style == FormattingOptions.IndentStyle.Smart)
{
// Set the formatting start point to be the beginning of the first word to the left
// of the opening brace location.
// skip whitespace
while (startPoint >= 0 && char.IsWhiteSpace(text[startPoint]))
{
startPoint--;
}
// skip tokens in the first word to the left.
startPoint--;
while (startPoint >= 0 && !char.IsWhiteSpace(text[startPoint]))
{
startPoint--;
}
}
var spanToFormat = TextSpan.FromBounds(Math.Max(startPoint, 0), endPoint);
var rules = document.GetFormattingRules(spanToFormat, braceFormattingIndentationRules);
var result = Formatter.GetFormattingResult(
root, SpecializedCollections.SingletonEnumerable(spanToFormat), document.Project.Solution.Workspace, documentOptions, rules, cancellationToken);
if (result == null)
{
return (ImmutableArray<TextChange>.Empty, closingPoint);
}
var newRoot = result.GetFormattedRoot(cancellationToken);
var newClosingPoint = newRoot.GetAnnotatedTokens(s_closingBraceSyntaxAnnotation).Single().SpanStart + 1;
var textChanges = result.GetTextChanges(cancellationToken).ToImmutableArray();
return (textChanges, newClosingPoint);
static async Task<Document> GetDocumentWithAnnotatedClosingBraceAsync(Document document, int closingBraceEndPoint, CancellationToken cancellationToken)
{
var originalRoot = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var closeBraceToken = originalRoot.FindToken(closingBraceEndPoint - 1);
Debug.Assert(closeBraceToken.IsKind(SyntaxKind.CloseBraceToken));
var newCloseBraceToken = closeBraceToken.WithAdditionalAnnotations(s_closingBraceSyntaxAnnotation);
var root = originalRoot.ReplaceToken(closeBraceToken, newCloseBraceToken);
return document.WithSyntaxRoot(root);
}
}
private static ImmutableArray<AbstractFormattingRule> GetBraceIndentationFormattingRules(DocumentOptionSet documentOptions)
{
var indentStyle = documentOptions.GetOption(FormattingOptions.SmartIndent);
return ImmutableArray.Create(BraceCompletionFormattingRule.ForIndentStyle(indentStyle));
}
private sealed class BraceCompletionFormattingRule : BaseFormattingRule
{
private static readonly Predicate<SuppressOperation> s_predicate = o => o == null || o.Option.IsOn(SuppressOption.NoWrapping);
private static readonly ImmutableArray<BraceCompletionFormattingRule> s_instances = ImmutableArray.Create(
new BraceCompletionFormattingRule(FormattingOptions.IndentStyle.None),
new BraceCompletionFormattingRule(FormattingOptions.IndentStyle.Block),
new BraceCompletionFormattingRule(FormattingOptions.IndentStyle.Smart));
private readonly FormattingOptions.IndentStyle _indentStyle;
private readonly CachedOptions _options;
public BraceCompletionFormattingRule(FormattingOptions.IndentStyle indentStyle)
: this(indentStyle, new CachedOptions(null))
{
}
private BraceCompletionFormattingRule(FormattingOptions.IndentStyle indentStyle, CachedOptions options)
{
_indentStyle = indentStyle;
_options = options;
}
public static AbstractFormattingRule ForIndentStyle(FormattingOptions.IndentStyle indentStyle)
{
Debug.Assert(s_instances[(int)indentStyle]._indentStyle == indentStyle);
return s_instances[(int)indentStyle];
}
public override AbstractFormattingRule WithOptions(AnalyzerConfigOptions options)
{
var cachedOptions = new CachedOptions(options);
if (cachedOptions == _options)
{
return this;
}
return new BraceCompletionFormattingRule(_indentStyle, cachedOptions);
}
public override AdjustNewLinesOperation? GetAdjustNewLinesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation)
{
// If we're inside any of the following expressions check if the option for
// braces on new lines in object / array initializers is set before we attempt
// to move the open brace location to a new line.
// new MyObject {
// new List<int> {
// int[] arr = {
// = new[] {
// = new int[] {
if (currentToken.IsKind(SyntaxKind.OpenBraceToken) && currentToken.Parent.IsKind(
SyntaxKind.ObjectInitializerExpression,
SyntaxKind.CollectionInitializerExpression,
SyntaxKind.ArrayInitializerExpression,
SyntaxKind.ImplicitArrayCreationExpression))
{
if (_options.NewLinesForBracesInObjectCollectionArrayInitializers)
{
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
else
{
return null;
}
}
return base.GetAdjustNewLinesOperation(in previousToken, in currentToken, in nextOperation);
}
public override void AddAlignTokensOperations(List<AlignTokensOperation> list, SyntaxNode node, in NextAlignTokensOperationAction nextOperation)
{
base.AddAlignTokensOperations(list, node, in nextOperation);
if (_indentStyle == FormattingOptions.IndentStyle.Block)
{
var bracePair = node.GetBracePair();
if (bracePair.IsValidBracePair())
{
// If the user has set block style indentation and we're in a valid brace pair
// then make sure we align the close brace to the open brace.
AddAlignIndentationOfTokensToBaseTokenOperation(list, node, bracePair.openBrace,
SpecializedCollections.SingletonEnumerable(bracePair.closeBrace), AlignTokensOption.AlignIndentationOfTokensToFirstTokenOfBaseTokenLine);
}
}
}
public override void AddSuppressOperations(List<SuppressOperation> list, SyntaxNode node, in NextSuppressOperationAction nextOperation)
{
base.AddSuppressOperations(list, node, in nextOperation);
// not sure exactly what is happening here, but removing the bellow causesthe indentation to be wrong.
// remove suppression rules for array and collection initializer
if (node.IsInitializerForArrayOrCollectionCreationExpression())
{
// remove any suppression operation
list.RemoveAll(s_predicate);
}
}
private readonly struct CachedOptions : IEquatable<CachedOptions>
{
public readonly bool NewLinesForBracesInObjectCollectionArrayInitializers;
public CachedOptions(AnalyzerConfigOptions? options)
{
NewLinesForBracesInObjectCollectionArrayInitializers = GetOptionOrDefault(options, CSharpFormattingOptions2.NewLinesForBracesInObjectCollectionArrayInitializers);
}
public static bool operator ==(CachedOptions left, CachedOptions right)
=> left.Equals(right);
public static bool operator !=(CachedOptions left, CachedOptions right)
=> !(left == right);
private static T GetOptionOrDefault<T>(AnalyzerConfigOptions? options, Option2<T> option)
{
if (options is null)
return option.DefaultValue;
return options.GetOption(option);
}
public override bool Equals(object? obj)
=> obj is CachedOptions options && Equals(options);
public bool Equals(CachedOptions other)
{
return NewLinesForBracesInObjectCollectionArrayInitializers == other.NewLinesForBracesInObjectCollectionArrayInitializers;
}
public override int GetHashCode()
{
var hashCode = 0;
hashCode = (hashCode << 1) + (NewLinesForBracesInObjectCollectionArrayInitializers ? 1 : 0);
return hashCode;
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.BraceCompletion;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Formatting;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Indentation;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.BraceCompletion
{
[Export(LanguageNames.CSharp, typeof(IBraceCompletionService)), Shared]
internal class CurlyBraceCompletionService : AbstractBraceCompletionService
{
/// <summary>
/// Annotation used to find the closing brace location after formatting changes are applied.
/// The closing brace location is then used as the caret location.
/// </summary>
private static readonly SyntaxAnnotation s_closingBraceSyntaxAnnotation = new(nameof(s_closingBraceSyntaxAnnotation));
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CurlyBraceCompletionService()
{
}
protected override char OpeningBrace => CurlyBrace.OpenCharacter;
protected override char ClosingBrace => CurlyBrace.CloseCharacter;
public override Task<bool> AllowOverTypeAsync(BraceCompletionContext context, CancellationToken cancellationToken)
=> AllowOverTypeInUserCodeWithValidClosingTokenAsync(context, cancellationToken);
public override async Task<BraceCompletionResult?> GetTextChangesAfterCompletionAsync(BraceCompletionContext braceCompletionContext, CancellationToken cancellationToken)
{
var documentOptions = await braceCompletionContext.Document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
// After the closing brace is completed we need to format the span from the opening point to the closing point.
// E.g. when the user triggers completion for an if statement ($$ is the caret location) we insert braces to get
// if (true){$$}
// We then need to format this to
// if (true) { $$}
var (formattingChanges, finalCurlyBraceEnd) = await FormatTrackingSpanAsync(
braceCompletionContext.Document,
braceCompletionContext.OpeningPoint,
braceCompletionContext.ClosingPoint,
shouldHonorAutoFormattingOnCloseBraceOption: true,
// We're not trying to format the indented block here, so no need to pass in additional rules.
braceFormattingIndentationRules: ImmutableArray<AbstractFormattingRule>.Empty,
documentOptions,
cancellationToken).ConfigureAwait(false);
if (formattingChanges.IsEmpty)
{
return null;
}
// The caret location should be at the start of the closing brace character.
var originalText = await braceCompletionContext.Document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var formattedText = originalText.WithChanges(formattingChanges);
var caretLocation = formattedText.Lines.GetLinePosition(finalCurlyBraceEnd - 1);
return new BraceCompletionResult(formattingChanges, caretLocation);
}
public override async Task<BraceCompletionResult?> GetTextChangeAfterReturnAsync(
BraceCompletionContext context,
DocumentOptionSet documentOptions,
CancellationToken cancellationToken)
{
var document = context.Document;
var closingPoint = context.ClosingPoint;
var openingPoint = context.OpeningPoint;
var originalDocumentText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
// check whether shape of the braces are what we support
// shape must be either "{|}" or "{ }". | is where caret is. otherwise, we don't do any special behavior
if (!ContainsOnlyWhitespace(originalDocumentText, openingPoint, closingPoint))
{
return null;
}
var openingPointLine = originalDocumentText.Lines.GetLineFromPosition(openingPoint).LineNumber;
var closingPointLine = originalDocumentText.Lines.GetLineFromPosition(closingPoint).LineNumber;
// If there are already multiple empty lines between the braces, don't do anything.
// We need to allow a single empty line between the braces to account for razor scenarios where they insert a line.
if (closingPointLine - openingPointLine > 2)
{
return null;
}
// If there is not already an empty line inserted between the braces, insert one.
TextChange? newLineEdit = null;
var textToFormat = originalDocumentText;
if (closingPointLine - openingPointLine == 1)
{
var newLineString = documentOptions.GetOption(FormattingOptions2.NewLine);
newLineEdit = new TextChange(new TextSpan(closingPoint - 1, 0), newLineString);
textToFormat = originalDocumentText.WithChanges(newLineEdit.Value);
// Modify the closing point location to adjust for the newly inserted line.
closingPoint += newLineString.Length;
}
// Format the text that contains the newly inserted line.
var (formattingChanges, newClosingPoint) = await FormatTrackingSpanAsync(
document.WithText(textToFormat),
openingPoint,
closingPoint,
shouldHonorAutoFormattingOnCloseBraceOption: false,
braceFormattingIndentationRules: GetBraceIndentationFormattingRules(documentOptions),
documentOptions,
cancellationToken).ConfigureAwait(false);
closingPoint = newClosingPoint;
var formattedText = textToFormat.WithChanges(formattingChanges);
// Get the empty line between the curly braces.
var desiredCaretLine = GetLineBetweenCurlys(closingPoint, formattedText);
Debug.Assert(desiredCaretLine.GetFirstNonWhitespacePosition() == null, "the line between the formatted braces is not empty");
// Set the caret position to the properly indented column in the desired line.
var newDocument = document.WithText(formattedText);
var newDocumentText = await newDocument.GetTextAsync(cancellationToken).ConfigureAwait(false);
var caretPosition = GetIndentedLinePosition(newDocument, newDocumentText, desiredCaretLine.LineNumber, cancellationToken);
// The new line edit is calculated against the original text, d0, to get text d1.
// The formatting edits are calculated against d1 to get text d2.
// Merge the formatting and new line edits into a set of whitespace only text edits that all apply to d0.
var overallChanges = newLineEdit != null ? GetMergedChanges(newLineEdit.Value, formattingChanges, formattedText) : formattingChanges;
return new BraceCompletionResult(overallChanges, caretPosition);
static TextLine GetLineBetweenCurlys(int closingPosition, SourceText text)
{
var closingBraceLineNumber = text.Lines.GetLineFromPosition(closingPosition - 1).LineNumber;
return text.Lines[closingBraceLineNumber - 1];
}
static LinePosition GetIndentedLinePosition(Document document, SourceText sourceText, int lineNumber, CancellationToken cancellationToken)
{
var indentationService = document.GetRequiredLanguageService<IIndentationService>();
var indentation = indentationService.GetIndentation(document, lineNumber, cancellationToken);
var baseLinePosition = sourceText.Lines.GetLinePosition(indentation.BasePosition);
var offsetOfBacePosition = baseLinePosition.Character;
var totalOffset = offsetOfBacePosition + indentation.Offset;
var indentedLinePosition = new LinePosition(lineNumber, totalOffset);
return indentedLinePosition;
}
static ImmutableArray<TextChange> GetMergedChanges(TextChange newLineEdit, ImmutableArray<TextChange> formattingChanges, SourceText formattedText)
{
var newRanges = TextChangeRangeExtensions.Merge(
ImmutableArray.Create(newLineEdit.ToTextChangeRange()),
formattingChanges.SelectAsArray(f => f.ToTextChangeRange()));
using var _ = ArrayBuilder<TextChange>.GetInstance(out var mergedChanges);
var amountToShift = 0;
foreach (var newRange in newRanges)
{
var newTextChangeSpan = newRange.Span;
// Get the text to put in the text change by looking at the span in the formatted text.
// As the new range start is relative to the original text, we need to adjust it assuming the previous changes were applied
// to get the correct start location in the formatted text.
// E.g. with changes
// 1. Insert "hello" at 2
// 2. Insert "goodbye" at 3
// "goodbye" is after "hello" at location 3 + 5 (length of "hello") in the new text.
var newTextChangeText = formattedText.GetSubText(new TextSpan(newRange.Span.Start + amountToShift, newRange.NewLength)).ToString();
amountToShift += (newRange.NewLength - newRange.Span.Length);
mergedChanges.Add(new TextChange(newTextChangeSpan, newTextChangeText));
}
return mergedChanges.ToImmutable();
}
}
public override async Task<bool> CanProvideBraceCompletionAsync(char brace, int openingPosition, Document document, CancellationToken cancellationToken)
{
// Only potentially valid for curly brace completion if not in an interpolation brace completion context.
if (OpeningBrace == brace && await InterpolationBraceCompletionService.IsPositionInInterpolationContextAsync(document, openingPosition, cancellationToken).ConfigureAwait(false))
{
return false;
}
return await base.CanProvideBraceCompletionAsync(brace, openingPosition, document, cancellationToken).ConfigureAwait(false);
}
protected override bool IsValidOpeningBraceToken(SyntaxToken token)
=> token.IsKind(SyntaxKind.OpenBraceToken) && !token.Parent.IsKind(SyntaxKind.Interpolation);
protected override bool IsValidClosingBraceToken(SyntaxToken token)
=> token.IsKind(SyntaxKind.CloseBraceToken);
private static bool ContainsOnlyWhitespace(SourceText text, int openingPosition, int closingBraceEndPoint)
{
// Set the start point to the character after the opening brace.
var start = openingPosition + 1;
// Set the end point to the closing brace start character position.
var end = closingBraceEndPoint - 1;
for (var i = start; i < end; i++)
{
if (!char.IsWhiteSpace(text[i]))
{
return false;
}
}
return true;
}
/// <summary>
/// Formats the span between the opening and closing points, options permitting.
/// Returns the text changes that should be applied to the input document to
/// get the formatted text and the end of the close curly brace in the formatted text.
/// </summary>
private static async Task<(ImmutableArray<TextChange> textChanges, int finalCurlyBraceEnd)> FormatTrackingSpanAsync(
Document document,
int openingPoint,
int closingPoint,
bool shouldHonorAutoFormattingOnCloseBraceOption,
ImmutableArray<AbstractFormattingRule> braceFormattingIndentationRules,
DocumentOptionSet documentOptions,
CancellationToken cancellationToken)
{
var option = document.Project.Solution.Options.GetOption(BraceCompletionOptions.AutoFormattingOnCloseBrace, document.Project.Language);
if (!option && shouldHonorAutoFormattingOnCloseBraceOption)
{
return (ImmutableArray<TextChange>.Empty, closingPoint);
}
// Annotate the original closing brace so we can find it after formatting.
document = await GetDocumentWithAnnotatedClosingBraceAsync(document, closingPoint, cancellationToken).ConfigureAwait(false);
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var startPoint = openingPoint;
var endPoint = closingPoint;
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
// Only format outside of the completed braces if they're on the same line for array/collection/object initializer expressions.
// Example: `var x = new int[]{}`:
// Correct: `var x = new int[] {}`
// Incorrect: `var x = new int[] { }`
// This is a heuristic to prevent brace completion from breaking user expectation/muscle memory in common scenarios.
// see bug Devdiv:823958
if (text.Lines.GetLineFromPosition(startPoint) == text.Lines.GetLineFromPosition(endPoint))
{
var startToken = root.FindToken(startPoint, findInsideTrivia: true);
if (startToken.IsKind(SyntaxKind.OpenBraceToken) &&
(startToken.Parent?.IsInitializerForArrayOrCollectionCreationExpression() == true ||
startToken.Parent is AnonymousObjectCreationExpressionSyntax))
{
// Since the braces are next to each other the span to format is everything up to the opening brace start.
endPoint = startToken.SpanStart;
}
}
var style = documentOptions.GetOption(FormattingOptions.SmartIndent);
if (style == FormattingOptions.IndentStyle.Smart)
{
// Set the formatting start point to be the beginning of the first word to the left
// of the opening brace location.
// skip whitespace
while (startPoint >= 0 && char.IsWhiteSpace(text[startPoint]))
{
startPoint--;
}
// skip tokens in the first word to the left.
startPoint--;
while (startPoint >= 0 && !char.IsWhiteSpace(text[startPoint]))
{
startPoint--;
}
}
var spanToFormat = TextSpan.FromBounds(Math.Max(startPoint, 0), endPoint);
var rules = document.GetFormattingRules(spanToFormat, braceFormattingIndentationRules);
var result = Formatter.GetFormattingResult(
root, SpecializedCollections.SingletonEnumerable(spanToFormat), document.Project.Solution.Workspace, documentOptions, rules, cancellationToken);
if (result == null)
{
return (ImmutableArray<TextChange>.Empty, closingPoint);
}
var newRoot = result.GetFormattedRoot(cancellationToken);
var newClosingPoint = newRoot.GetAnnotatedTokens(s_closingBraceSyntaxAnnotation).Single().SpanStart + 1;
var textChanges = result.GetTextChanges(cancellationToken).ToImmutableArray();
return (textChanges, newClosingPoint);
static async Task<Document> GetDocumentWithAnnotatedClosingBraceAsync(Document document, int closingBraceEndPoint, CancellationToken cancellationToken)
{
var originalRoot = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var closeBraceToken = originalRoot.FindToken(closingBraceEndPoint - 1);
Debug.Assert(closeBraceToken.IsKind(SyntaxKind.CloseBraceToken));
var newCloseBraceToken = closeBraceToken.WithAdditionalAnnotations(s_closingBraceSyntaxAnnotation);
var root = originalRoot.ReplaceToken(closeBraceToken, newCloseBraceToken);
return document.WithSyntaxRoot(root);
}
}
private static ImmutableArray<AbstractFormattingRule> GetBraceIndentationFormattingRules(DocumentOptionSet documentOptions)
{
var indentStyle = documentOptions.GetOption(FormattingOptions.SmartIndent);
return ImmutableArray.Create(BraceCompletionFormattingRule.ForIndentStyle(indentStyle));
}
private sealed class BraceCompletionFormattingRule : BaseFormattingRule
{
private static readonly Predicate<SuppressOperation> s_predicate = o => o == null || o.Option.IsOn(SuppressOption.NoWrapping);
private static readonly ImmutableArray<BraceCompletionFormattingRule> s_instances = ImmutableArray.Create(
new BraceCompletionFormattingRule(FormattingOptions.IndentStyle.None),
new BraceCompletionFormattingRule(FormattingOptions.IndentStyle.Block),
new BraceCompletionFormattingRule(FormattingOptions.IndentStyle.Smart));
private readonly FormattingOptions.IndentStyle _indentStyle;
private readonly CachedOptions _options;
public BraceCompletionFormattingRule(FormattingOptions.IndentStyle indentStyle)
: this(indentStyle, new CachedOptions(null))
{
}
private BraceCompletionFormattingRule(FormattingOptions.IndentStyle indentStyle, CachedOptions options)
{
_indentStyle = indentStyle;
_options = options;
}
public static AbstractFormattingRule ForIndentStyle(FormattingOptions.IndentStyle indentStyle)
{
Debug.Assert(s_instances[(int)indentStyle]._indentStyle == indentStyle);
return s_instances[(int)indentStyle];
}
public override AbstractFormattingRule WithOptions(AnalyzerConfigOptions options)
{
var cachedOptions = new CachedOptions(options);
if (cachedOptions == _options)
{
return this;
}
return new BraceCompletionFormattingRule(_indentStyle, cachedOptions);
}
public override AdjustNewLinesOperation? GetAdjustNewLinesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation)
{
// If we're inside any of the following expressions check if the option for
// braces on new lines in object / array initializers is set before we attempt
// to move the open brace location to a new line.
// new MyObject {
// new List<int> {
// int[] arr = {
// = new[] {
// = new int[] {
if (currentToken.IsKind(SyntaxKind.OpenBraceToken) && currentToken.Parent.IsKind(
SyntaxKind.ObjectInitializerExpression,
SyntaxKind.CollectionInitializerExpression,
SyntaxKind.ArrayInitializerExpression,
SyntaxKind.ImplicitArrayCreationExpression))
{
if (_options.NewLinesForBracesInObjectCollectionArrayInitializers)
{
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
else
{
return null;
}
}
return base.GetAdjustNewLinesOperation(in previousToken, in currentToken, in nextOperation);
}
public override void AddAlignTokensOperations(List<AlignTokensOperation> list, SyntaxNode node, in NextAlignTokensOperationAction nextOperation)
{
base.AddAlignTokensOperations(list, node, in nextOperation);
if (_indentStyle == FormattingOptions.IndentStyle.Block)
{
var bracePair = node.GetBracePair();
if (bracePair.IsValidBracePair())
{
// If the user has set block style indentation and we're in a valid brace pair
// then make sure we align the close brace to the open brace.
AddAlignIndentationOfTokensToBaseTokenOperation(list, node, bracePair.openBrace,
SpecializedCollections.SingletonEnumerable(bracePair.closeBrace), AlignTokensOption.AlignIndentationOfTokensToFirstTokenOfBaseTokenLine);
}
}
}
public override void AddSuppressOperations(List<SuppressOperation> list, SyntaxNode node, in NextSuppressOperationAction nextOperation)
{
base.AddSuppressOperations(list, node, in nextOperation);
// not sure exactly what is happening here, but removing the bellow causesthe indentation to be wrong.
// remove suppression rules for array and collection initializer
if (node.IsInitializerForArrayOrCollectionCreationExpression())
{
// remove any suppression operation
list.RemoveAll(s_predicate);
}
}
private readonly struct CachedOptions : IEquatable<CachedOptions>
{
public readonly bool NewLinesForBracesInObjectCollectionArrayInitializers;
public CachedOptions(AnalyzerConfigOptions? options)
{
NewLinesForBracesInObjectCollectionArrayInitializers = GetOptionOrDefault(options, CSharpFormattingOptions2.NewLinesForBracesInObjectCollectionArrayInitializers);
}
public static bool operator ==(CachedOptions left, CachedOptions right)
=> left.Equals(right);
public static bool operator !=(CachedOptions left, CachedOptions right)
=> !(left == right);
private static T GetOptionOrDefault<T>(AnalyzerConfigOptions? options, Option2<T> option)
{
if (options is null)
return option.DefaultValue;
return options.GetOption(option);
}
public override bool Equals(object? obj)
=> obj is CachedOptions options && Equals(options);
public bool Equals(CachedOptions other)
{
return NewLinesForBracesInObjectCollectionArrayInitializers == other.NewLinesForBracesInObjectCollectionArrayInitializers;
}
public override int GetHashCode()
{
var hashCode = 0;
hashCode = (hashCode << 1) + (NewLinesForBracesInObjectCollectionArrayInitializers ? 1 : 0);
return hashCode;
}
}
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Test/Resources/Core/SymbolsTests/MissingTypes/MissingTypesEquality1.il |
// ilasm /DLL MissingTypesEquality1.il
// Microsoft (R) .NET Framework IL Disassembler. Version 4.0.30319.1
// Metadata version: v4.0.30319
.assembly extern mscorlib
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
.ver 4:0:0:0
}
.assembly extern MDTestLib1
{
.ver 0:0:0:0
}
.assembly extern MDTestLib2
{
.ver 0:0:0:0
}
.assembly extern MDTestLib3
{
.ver 0:0:0:0
}
.assembly extern MDTestLib4
{
.ver 0:0:0:0
}
.assembly MissingTypesEquality1
{
.hash algorithm 0x00008004
.ver 0:0:0:0
}
.module MissingTypesEquality1.dll
// MVID: {E8168B7E-08FF-41C9-9993-6AD3D46B903C}
.imagebase 0x00400000
.file alignment 0x00000200
.stackreserve 0x00100000
.subsystem 0x0002 // WINDOWS_GUI
.corflags 0x00000001 // ILONLY
// Image base: 0x00450000
// =============== CLASS MEMBERS DECLARATION ===================
.class private abstract auto ansi C
extends [mscorlib]System.Object
{
.method family specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method C::.ctor
.method public newslot abstract strict virtual
instance class [MDTestLib1]MissingType1
M1() cil managed
{
}
.method public newslot abstract strict virtual
instance class [MDTestLib1]MissingType2
M2() cil managed
{
}
.method public newslot abstract strict virtual
instance class [MDTestLib2]MissingType1
M3() cil managed
{
}
.method public newslot abstract strict virtual
instance class [MDTestLib3]MissingType1
M4() cil managed
{
}
.method public newslot abstract strict virtual
instance class [MDTestLib3]MissingType2
M5() cil managed
{
}
.method public newslot abstract strict virtual
instance class [MDTestLib4]MissingType1
M6() cil managed
{
}
.method public newslot abstract strict virtual
instance class [MDTestLib1]MissingType1
M7() cil managed
{
}
.method public newslot abstract strict virtual
instance class [MDTestLib3]MissingType1
M8() cil managed
{
}
} // end of class C
// =============================================================
// *********** DISASSEMBLY COMPLETE ***********************
// WARNING: Created Win32 resource file MissingTypesEquality1.res
|
// ilasm /DLL MissingTypesEquality1.il
// Microsoft (R) .NET Framework IL Disassembler. Version 4.0.30319.1
// Metadata version: v4.0.30319
.assembly extern mscorlib
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
.ver 4:0:0:0
}
.assembly extern MDTestLib1
{
.ver 0:0:0:0
}
.assembly extern MDTestLib2
{
.ver 0:0:0:0
}
.assembly extern MDTestLib3
{
.ver 0:0:0:0
}
.assembly extern MDTestLib4
{
.ver 0:0:0:0
}
.assembly MissingTypesEquality1
{
.hash algorithm 0x00008004
.ver 0:0:0:0
}
.module MissingTypesEquality1.dll
// MVID: {E8168B7E-08FF-41C9-9993-6AD3D46B903C}
.imagebase 0x00400000
.file alignment 0x00000200
.stackreserve 0x00100000
.subsystem 0x0002 // WINDOWS_GUI
.corflags 0x00000001 // ILONLY
// Image base: 0x00450000
// =============== CLASS MEMBERS DECLARATION ===================
.class private abstract auto ansi C
extends [mscorlib]System.Object
{
.method family specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method C::.ctor
.method public newslot abstract strict virtual
instance class [MDTestLib1]MissingType1
M1() cil managed
{
}
.method public newslot abstract strict virtual
instance class [MDTestLib1]MissingType2
M2() cil managed
{
}
.method public newslot abstract strict virtual
instance class [MDTestLib2]MissingType1
M3() cil managed
{
}
.method public newslot abstract strict virtual
instance class [MDTestLib3]MissingType1
M4() cil managed
{
}
.method public newslot abstract strict virtual
instance class [MDTestLib3]MissingType2
M5() cil managed
{
}
.method public newslot abstract strict virtual
instance class [MDTestLib4]MissingType1
M6() cil managed
{
}
.method public newslot abstract strict virtual
instance class [MDTestLib1]MissingType1
M7() cil managed
{
}
.method public newslot abstract strict virtual
instance class [MDTestLib3]MissingType1
M8() cil managed
{
}
} // end of class C
// =============================================================
// *********** DISASSEMBLY COMPLETE ***********************
// WARNING: Created Win32 resource file MissingTypesEquality1.res
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordInequalityOperator.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Globalization;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// The record type includes synthesized '==' and '!=' operators equivalent to operators declared as follows:
///
/// For record class:
/// public static bool operator==(R? left, R? right)
/// => (object) left == right || ((object)left != null && left.Equals(right));
/// public static bool operator !=(R? left, R? right)
/// => !(left == right);
///
/// For record struct:
/// public static bool operator==(R left, R right)
/// => left.Equals(right);
/// public static bool operator !=(R left, R right)
/// => !(left == right);
///
///The 'Equals' method called by the '==' operator is the 'Equals(R? other)' (<see cref="SynthesizedRecordEquals"/>).
///The '!=' operator delegates to the '==' operator. It is an error if the operators are declared explicitly.
/// </summary>
internal sealed class SynthesizedRecordInequalityOperator : SynthesizedRecordEqualityOperatorBase
{
public SynthesizedRecordInequalityOperator(SourceMemberContainerTypeSymbol containingType, int memberOffset, BindingDiagnosticBag diagnostics)
: base(containingType, WellKnownMemberNames.InequalityOperatorName, memberOffset, diagnostics)
{
}
internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics)
{
var F = new SyntheticBoundNodeFactory(this, ContainingType.GetNonNullSyntaxNode(), compilationState, diagnostics);
try
{
// => !(left == right);
F.CloseMethod(F.Block(F.Return(F.Not(F.Call(receiver: null, ContainingType.GetMembers(WellKnownMemberNames.EqualityOperatorName).OfType<SynthesizedRecordEqualityOperator>().Single(),
F.Parameter(Parameters[0]), F.Parameter(Parameters[1]))))));
}
catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex)
{
diagnostics.Add(ex.Diagnostic);
F.CloseMethod(F.ThrowNull());
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// The record type includes synthesized '==' and '!=' operators equivalent to operators declared as follows:
///
/// For record class:
/// public static bool operator==(R? left, R? right)
/// => (object) left == right || ((object)left != null && left.Equals(right));
/// public static bool operator !=(R? left, R? right)
/// => !(left == right);
///
/// For record struct:
/// public static bool operator==(R left, R right)
/// => left.Equals(right);
/// public static bool operator !=(R left, R right)
/// => !(left == right);
///
///The 'Equals' method called by the '==' operator is the 'Equals(R? other)' (<see cref="SynthesizedRecordEquals"/>).
///The '!=' operator delegates to the '==' operator. It is an error if the operators are declared explicitly.
/// </summary>
internal sealed class SynthesizedRecordInequalityOperator : SynthesizedRecordEqualityOperatorBase
{
public SynthesizedRecordInequalityOperator(SourceMemberContainerTypeSymbol containingType, int memberOffset, BindingDiagnosticBag diagnostics)
: base(containingType, WellKnownMemberNames.InequalityOperatorName, memberOffset, diagnostics)
{
}
internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics)
{
var F = new SyntheticBoundNodeFactory(this, ContainingType.GetNonNullSyntaxNode(), compilationState, diagnostics);
try
{
// => !(left == right);
F.CloseMethod(F.Block(F.Return(F.Not(F.Call(receiver: null, ContainingType.GetMembers(WellKnownMemberNames.EqualityOperatorName).OfType<SynthesizedRecordEqualityOperator>().Single(),
F.Parameter(Parameters[0]), F.Parameter(Parameters[1]))))));
}
catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex)
{
diagnostics.Add(ex.Diagnostic);
F.CloseMethod(F.ThrowNull());
}
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/CSharp/Portable/Completion/KeywordRecommenders/ShortKeywordRecommender.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class ShortKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender
{
public ShortKeywordRecommender()
: base(SyntaxKind.ShortKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
var syntaxTree = context.SyntaxTree;
return
context.IsAnyExpressionContext ||
context.IsDefiniteCastTypeContext ||
context.IsStatementContext ||
context.IsGlobalStatementContext ||
context.IsObjectCreationTypeContext ||
(context.IsGenericTypeArgumentContext && !context.TargetToken.Parent.HasAncestor<XmlCrefAttributeSyntax>()) ||
context.IsFunctionPointerTypeArgumentContext ||
context.IsEnumBaseListContext ||
context.IsIsOrAsTypeContext ||
context.IsLocalVariableDeclarationContext ||
context.IsFixedVariableDeclarationContext ||
context.IsParameterTypeContext ||
context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext ||
context.IsImplicitOrExplicitOperatorTypeContext ||
context.IsPrimaryFunctionExpressionContext ||
context.IsCrefContext ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) ||
context.IsDelegateReturnTypeContext ||
syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
context.IsPossibleTupleContext ||
context.IsMemberDeclarationContext(
validModifiers: SyntaxKindSet.AllMemberModifiers,
validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations,
canBePartial: false,
cancellationToken: cancellationToken);
}
protected override SpecialType SpecialType => SpecialType.System_Int16;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class ShortKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender
{
public ShortKeywordRecommender()
: base(SyntaxKind.ShortKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
var syntaxTree = context.SyntaxTree;
return
context.IsAnyExpressionContext ||
context.IsDefiniteCastTypeContext ||
context.IsStatementContext ||
context.IsGlobalStatementContext ||
context.IsObjectCreationTypeContext ||
(context.IsGenericTypeArgumentContext && !context.TargetToken.Parent.HasAncestor<XmlCrefAttributeSyntax>()) ||
context.IsFunctionPointerTypeArgumentContext ||
context.IsEnumBaseListContext ||
context.IsIsOrAsTypeContext ||
context.IsLocalVariableDeclarationContext ||
context.IsFixedVariableDeclarationContext ||
context.IsParameterTypeContext ||
context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext ||
context.IsImplicitOrExplicitOperatorTypeContext ||
context.IsPrimaryFunctionExpressionContext ||
context.IsCrefContext ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) ||
context.IsDelegateReturnTypeContext ||
syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
context.IsPossibleTupleContext ||
context.IsMemberDeclarationContext(
validModifiers: SyntaxKindSet.AllMemberModifiers,
validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations,
canBePartial: false,
cancellationToken: cancellationToken);
}
protected override SpecialType SpecialType => SpecialType.System_Int16;
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/AddImports/AbstractAddImportsService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.AddImports
{
internal abstract class AbstractAddImportsService<TCompilationUnitSyntax, TNamespaceDeclarationSyntax, TUsingOrAliasSyntax, TExternSyntax>
: IAddImportsService
where TCompilationUnitSyntax : SyntaxNode
where TNamespaceDeclarationSyntax : SyntaxNode
where TUsingOrAliasSyntax : SyntaxNode
where TExternSyntax : SyntaxNode
{
protected AbstractAddImportsService()
{
}
protected abstract SyntaxNode? GetAlias(TUsingOrAliasSyntax usingOrAlias);
protected abstract ImmutableArray<SyntaxNode> GetGlobalImports(Compilation compilation, SyntaxGenerator generator);
protected abstract SyntaxList<TUsingOrAliasSyntax> GetUsingsAndAliases(SyntaxNode node);
protected abstract SyntaxList<TExternSyntax> GetExterns(SyntaxNode node);
protected abstract bool IsStaticUsing(TUsingOrAliasSyntax usingOrAlias);
private bool IsSimpleUsing(TUsingOrAliasSyntax usingOrAlias) => !IsAlias(usingOrAlias) && !IsStaticUsing(usingOrAlias);
private bool IsAlias(TUsingOrAliasSyntax usingOrAlias) => GetAlias(usingOrAlias) != null;
private bool HasAliases(SyntaxNode node) => GetUsingsAndAliases(node).Any(IsAlias);
private bool HasUsings(SyntaxNode node) => GetUsingsAndAliases(node).Any(IsSimpleUsing);
private bool HasStaticUsings(SyntaxNode node) => GetUsingsAndAliases(node).Any(IsStaticUsing);
private bool HasExterns(SyntaxNode node) => GetExterns(node).Any();
private bool HasAnyImports(SyntaxNode node) => GetUsingsAndAliases(node).Any() || GetExterns(node).Any();
public bool HasExistingImport(
Compilation compilation,
SyntaxNode root,
SyntaxNode? contextLocation,
SyntaxNode import,
SyntaxGenerator generator)
{
var globalImports = GetGlobalImports(compilation, generator);
var containers = GetAllContainers(root, contextLocation);
return HasExistingImport(import, containers, globalImports);
}
private static ImmutableArray<SyntaxNode> GetAllContainers(SyntaxNode root, SyntaxNode? contextLocation)
{
contextLocation ??= root;
var applicableContainer = GetFirstApplicableContainer(contextLocation);
return applicableContainer.GetAncestorsOrThis<SyntaxNode>().ToImmutableArray();
}
private bool HasExistingImport(
SyntaxNode import, ImmutableArray<SyntaxNode> containers, ImmutableArray<SyntaxNode> globalImports)
{
foreach (var node in containers)
{
if (GetUsingsAndAliases(node).Any(u => IsEquivalentImport(u, import)))
{
return true;
}
if (GetExterns(node).Any(u => IsEquivalentImport(u, import)))
{
return true;
}
}
foreach (var node in globalImports)
{
if (IsEquivalentImport(node, import))
{
return true;
}
}
return false;
}
protected abstract bool IsEquivalentImport(SyntaxNode a, SyntaxNode b);
public SyntaxNode GetImportContainer(SyntaxNode root, SyntaxNode? contextLocation, SyntaxNode import)
{
contextLocation ??= root;
GetContainers(root, contextLocation,
out var externContainer, out var usingContainer, out var staticUsingContainer, out var aliasContainer);
switch (import)
{
case TExternSyntax _:
return externContainer;
case TUsingOrAliasSyntax u:
if (IsAlias(u))
{
return aliasContainer;
}
if (IsStaticUsing(u))
{
return staticUsingContainer;
}
return usingContainer;
}
throw new InvalidOperationException();
}
public SyntaxNode AddImports(
Compilation compilation,
SyntaxNode root,
SyntaxNode? contextLocation,
IEnumerable<SyntaxNode> newImports,
SyntaxGenerator generator,
bool placeSystemNamespaceFirst,
bool allowInHiddenRegions,
CancellationToken cancellationToken)
{
contextLocation ??= root;
var globalImports = GetGlobalImports(compilation, generator);
var containers = GetAllContainers(root, contextLocation);
var filteredImports = newImports.Where(i => !HasExistingImport(i, containers, globalImports)).ToArray();
var externAliases = filteredImports.OfType<TExternSyntax>().ToArray();
var usingDirectives = filteredImports.OfType<TUsingOrAliasSyntax>().Where(IsSimpleUsing).ToArray();
var staticUsingDirectives = filteredImports.OfType<TUsingOrAliasSyntax>().Where(IsStaticUsing).ToArray();
var aliasDirectives = filteredImports.OfType<TUsingOrAliasSyntax>().Where(IsAlias).ToArray();
GetContainers(root, contextLocation,
out var externContainer, out var usingContainer, out var aliasContainer, out var staticUsingContainer);
var newRoot = Rewrite(
externAliases, usingDirectives, staticUsingDirectives, aliasDirectives,
externContainer, usingContainer, staticUsingContainer, aliasContainer,
placeSystemNamespaceFirst, allowInHiddenRegions, root, cancellationToken);
return newRoot;
}
protected abstract SyntaxNode Rewrite(
TExternSyntax[] externAliases, TUsingOrAliasSyntax[] usingDirectives, TUsingOrAliasSyntax[] staticUsingDirectives, TUsingOrAliasSyntax[] aliasDirectives,
SyntaxNode externContainer, SyntaxNode usingContainer, SyntaxNode staticUsingContainer, SyntaxNode aliasContainer,
bool placeSystemNamespaceFirst, bool allowInHiddenRegions, SyntaxNode root, CancellationToken cancellationToken);
private void GetContainers(SyntaxNode root, SyntaxNode contextLocation, out SyntaxNode externContainer, out SyntaxNode usingContainer, out SyntaxNode staticUsingContainer, out SyntaxNode aliasContainer)
{
var applicableContainer = GetFirstApplicableContainer(contextLocation);
var contextSpine = applicableContainer.GetAncestorsOrThis<SyntaxNode>().ToImmutableArray();
// The node we'll add to if we can't find a specific namespace with imports of
// the type we're trying to add. This will be the closest namespace with any
// imports in it, or the root if there are no such namespaces.
var fallbackNode = contextSpine.FirstOrDefault(HasAnyImports) ?? root;
// The specific container to add each type of import to. We look for a container
// that already has an import of the same type as the node we want to add to.
// If we can find one, we add to that container. If not, we call back to the
// innermost node with any imports.
externContainer = contextSpine.FirstOrDefault(HasExterns) ?? fallbackNode;
usingContainer = contextSpine.FirstOrDefault(HasUsings) ?? fallbackNode;
staticUsingContainer = contextSpine.FirstOrDefault(HasStaticUsings) ?? fallbackNode;
aliasContainer = contextSpine.FirstOrDefault(HasAliases) ?? fallbackNode;
}
private static SyntaxNode? GetFirstApplicableContainer(SyntaxNode contextNode)
{
var usingDirective = contextNode.GetAncestor<TUsingOrAliasSyntax>();
var node = usingDirective != null ? usingDirective.Parent! : contextNode;
return node.GetAncestor<TNamespaceDeclarationSyntax>() ??
(SyntaxNode?)node.GetAncestorOrThis<TCompilationUnitSyntax>();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.AddImports
{
internal abstract class AbstractAddImportsService<TCompilationUnitSyntax, TNamespaceDeclarationSyntax, TUsingOrAliasSyntax, TExternSyntax>
: IAddImportsService
where TCompilationUnitSyntax : SyntaxNode
where TNamespaceDeclarationSyntax : SyntaxNode
where TUsingOrAliasSyntax : SyntaxNode
where TExternSyntax : SyntaxNode
{
protected AbstractAddImportsService()
{
}
protected abstract SyntaxNode? GetAlias(TUsingOrAliasSyntax usingOrAlias);
protected abstract ImmutableArray<SyntaxNode> GetGlobalImports(Compilation compilation, SyntaxGenerator generator);
protected abstract SyntaxList<TUsingOrAliasSyntax> GetUsingsAndAliases(SyntaxNode node);
protected abstract SyntaxList<TExternSyntax> GetExterns(SyntaxNode node);
protected abstract bool IsStaticUsing(TUsingOrAliasSyntax usingOrAlias);
private bool IsSimpleUsing(TUsingOrAliasSyntax usingOrAlias) => !IsAlias(usingOrAlias) && !IsStaticUsing(usingOrAlias);
private bool IsAlias(TUsingOrAliasSyntax usingOrAlias) => GetAlias(usingOrAlias) != null;
private bool HasAliases(SyntaxNode node) => GetUsingsAndAliases(node).Any(IsAlias);
private bool HasUsings(SyntaxNode node) => GetUsingsAndAliases(node).Any(IsSimpleUsing);
private bool HasStaticUsings(SyntaxNode node) => GetUsingsAndAliases(node).Any(IsStaticUsing);
private bool HasExterns(SyntaxNode node) => GetExterns(node).Any();
private bool HasAnyImports(SyntaxNode node) => GetUsingsAndAliases(node).Any() || GetExterns(node).Any();
public bool HasExistingImport(
Compilation compilation,
SyntaxNode root,
SyntaxNode? contextLocation,
SyntaxNode import,
SyntaxGenerator generator)
{
var globalImports = GetGlobalImports(compilation, generator);
var containers = GetAllContainers(root, contextLocation);
return HasExistingImport(import, containers, globalImports);
}
private static ImmutableArray<SyntaxNode> GetAllContainers(SyntaxNode root, SyntaxNode? contextLocation)
{
contextLocation ??= root;
var applicableContainer = GetFirstApplicableContainer(contextLocation);
return applicableContainer.GetAncestorsOrThis<SyntaxNode>().ToImmutableArray();
}
private bool HasExistingImport(
SyntaxNode import, ImmutableArray<SyntaxNode> containers, ImmutableArray<SyntaxNode> globalImports)
{
foreach (var node in containers)
{
if (GetUsingsAndAliases(node).Any(u => IsEquivalentImport(u, import)))
{
return true;
}
if (GetExterns(node).Any(u => IsEquivalentImport(u, import)))
{
return true;
}
}
foreach (var node in globalImports)
{
if (IsEquivalentImport(node, import))
{
return true;
}
}
return false;
}
protected abstract bool IsEquivalentImport(SyntaxNode a, SyntaxNode b);
public SyntaxNode GetImportContainer(SyntaxNode root, SyntaxNode? contextLocation, SyntaxNode import)
{
contextLocation ??= root;
GetContainers(root, contextLocation,
out var externContainer, out var usingContainer, out var staticUsingContainer, out var aliasContainer);
switch (import)
{
case TExternSyntax _:
return externContainer;
case TUsingOrAliasSyntax u:
if (IsAlias(u))
{
return aliasContainer;
}
if (IsStaticUsing(u))
{
return staticUsingContainer;
}
return usingContainer;
}
throw new InvalidOperationException();
}
public SyntaxNode AddImports(
Compilation compilation,
SyntaxNode root,
SyntaxNode? contextLocation,
IEnumerable<SyntaxNode> newImports,
SyntaxGenerator generator,
bool placeSystemNamespaceFirst,
bool allowInHiddenRegions,
CancellationToken cancellationToken)
{
contextLocation ??= root;
var globalImports = GetGlobalImports(compilation, generator);
var containers = GetAllContainers(root, contextLocation);
var filteredImports = newImports.Where(i => !HasExistingImport(i, containers, globalImports)).ToArray();
var externAliases = filteredImports.OfType<TExternSyntax>().ToArray();
var usingDirectives = filteredImports.OfType<TUsingOrAliasSyntax>().Where(IsSimpleUsing).ToArray();
var staticUsingDirectives = filteredImports.OfType<TUsingOrAliasSyntax>().Where(IsStaticUsing).ToArray();
var aliasDirectives = filteredImports.OfType<TUsingOrAliasSyntax>().Where(IsAlias).ToArray();
GetContainers(root, contextLocation,
out var externContainer, out var usingContainer, out var aliasContainer, out var staticUsingContainer);
var newRoot = Rewrite(
externAliases, usingDirectives, staticUsingDirectives, aliasDirectives,
externContainer, usingContainer, staticUsingContainer, aliasContainer,
placeSystemNamespaceFirst, allowInHiddenRegions, root, cancellationToken);
return newRoot;
}
protected abstract SyntaxNode Rewrite(
TExternSyntax[] externAliases, TUsingOrAliasSyntax[] usingDirectives, TUsingOrAliasSyntax[] staticUsingDirectives, TUsingOrAliasSyntax[] aliasDirectives,
SyntaxNode externContainer, SyntaxNode usingContainer, SyntaxNode staticUsingContainer, SyntaxNode aliasContainer,
bool placeSystemNamespaceFirst, bool allowInHiddenRegions, SyntaxNode root, CancellationToken cancellationToken);
private void GetContainers(SyntaxNode root, SyntaxNode contextLocation, out SyntaxNode externContainer, out SyntaxNode usingContainer, out SyntaxNode staticUsingContainer, out SyntaxNode aliasContainer)
{
var applicableContainer = GetFirstApplicableContainer(contextLocation);
var contextSpine = applicableContainer.GetAncestorsOrThis<SyntaxNode>().ToImmutableArray();
// The node we'll add to if we can't find a specific namespace with imports of
// the type we're trying to add. This will be the closest namespace with any
// imports in it, or the root if there are no such namespaces.
var fallbackNode = contextSpine.FirstOrDefault(HasAnyImports) ?? root;
// The specific container to add each type of import to. We look for a container
// that already has an import of the same type as the node we want to add to.
// If we can find one, we add to that container. If not, we call back to the
// innermost node with any imports.
externContainer = contextSpine.FirstOrDefault(HasExterns) ?? fallbackNode;
usingContainer = contextSpine.FirstOrDefault(HasUsings) ?? fallbackNode;
staticUsingContainer = contextSpine.FirstOrDefault(HasStaticUsings) ?? fallbackNode;
aliasContainer = contextSpine.FirstOrDefault(HasAliases) ?? fallbackNode;
}
private static SyntaxNode? GetFirstApplicableContainer(SyntaxNode contextNode)
{
var usingDirective = contextNode.GetAncestor<TUsingOrAliasSyntax>();
var node = usingDirective != null ? usingDirective.Parent! : contextNode;
return node.GetAncestor<TNamespaceDeclarationSyntax>() ??
(SyntaxNode?)node.GetAncestorOrThis<TCompilationUnitSyntax>();
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/VisualBasic/Test/Syntax/Scanner/ScannerTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.CompilerServices
Imports System.Threading.Thread
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Syntax.InternalSyntax
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
<CLSCompliant(False)>
Public Class ScannerTests
Inherits BasicTestBase
Private Function ScanOnce(str As String, Optional startStatement As Boolean = False) As SyntaxToken
Return SyntaxFactory.ParseToken(str, startStatement:=startStatement)
End Function
Private Function ScanOnce(str As String, languageVersion As VisualBasic.LanguageVersion) As SyntaxToken
Return SyntaxFactory.ParseTokens(str, options:=New VisualBasicParseOptions(languageVersion:=languageVersion)).First()
End Function
Private Function AsString(tokens As IEnumerable(Of SyntaxToken)) As String
Dim str = String.Concat(From t In tokens Select t.ToFullString())
Return str
End Function
Private Function MakeDwString(str As String) As String
Return (From c In str Select If(c < ChrW(&H21S) OrElse c > ChrW(&H7ES), c, ChrW(AscW(c) + &HFF00US - &H20US))).ToArray
End Function
Private Function ScanAllCheckDw(str As String) As IEnumerable(Of SyntaxToken)
Dim tokens = SyntaxFactory.ParseTokens(str)
' test that token have the same text as it was.
Assert.Equal(str, AsString(tokens))
' test that we get same with doublewidth string
Dim doubleWidthStr = MakeDwString(str)
Dim doubleWidthTokens = ScanAllNoDwCheck(doubleWidthStr)
Assert.Equal(tokens.Count, doubleWidthTokens.Count)
For Each t In tokens.Zip(doubleWidthTokens, Function(t1, t2) Tuple.Create(t1, t2))
Assert.Equal(t.Item1.Kind, t.Item2.Kind)
Assert.Equal(t.Item1.Span, t.Item2.Span)
Assert.Equal(t.Item1.FullSpan, t.Item2.FullSpan)
Assert.Equal(MakeDwString(t.Item1.ToFullString()), t.Item2.ToFullString())
Next
Return tokens
End Function
Private Function ScanAllNoDwCheck(str As String) As IEnumerable(Of SyntaxToken)
Dim tokens = SyntaxFactory.ParseTokens(str)
' test that token have the same text as it was.
Assert.Equal(str, AsString(tokens))
Return tokens
End Function
<Fact>
Public Sub TestLessThanConflictMarker1()
' Needs to be followed by a space.
Dim token = SyntaxFactory.ParseTokens("<<<<<<<").First()
Assert.Equal(SyntaxKind.LessThanLessThanToken, token.Kind())
' Has to be the start of a line.
token = SyntaxFactory.ParseTokens(" <<<<<<<").First()
Assert.Equal(SyntaxKind.LessThanLessThanToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Assert.True(token.LeadingTrivia.Single().Kind() = SyntaxKind.WhitespaceTrivia)
' Has to have at least seven characters.
token = SyntaxFactory.ParseTokens("<<<<<< ").First()
Assert.Equal(SyntaxKind.LessThanLessThanToken, token.Kind())
' Start of line, seven characters, ends with space.
token = SyntaxFactory.ParseTokens("<<<<<<< ").First()
Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Dim trivia = token.LeadingTrivia.Single()
Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia)
Assert.True(trivia.ContainsDiagnostics)
Dim err = trivia.Errors().First
Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code)
End Sub
<Fact>
Public Sub TestLessThanConflictMarker2()
Dim token = SyntaxFactory.ParseTokens("{" & vbCrLf & "<<<<<<<").Skip(2).First()
Assert.Equal(SyntaxKind.LessThanLessThanToken, token.Kind())
token = SyntaxFactory.ParseTokens("{" & vbCrLf & " <<<<<<<").Skip(2).First()
Assert.Equal(SyntaxKind.LessThanLessThanToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Assert.True(token.LeadingTrivia.Single().Kind() = SyntaxKind.WhitespaceTrivia)
token = SyntaxFactory.ParseTokens("{" & vbCrLf & "<<<<<< ").Skip(2).First()
Assert.Equal(SyntaxKind.LessThanLessThanToken, token.Kind())
token = SyntaxFactory.ParseTokens("{" & vbCrLf & "<<<<<<< ").Skip(2).First()
Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Dim trivia = token.LeadingTrivia.Single()
Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia)
Assert.True(trivia.SpanStart = 3)
Assert.True(trivia.Span.Length = 8)
Assert.True(trivia.ContainsDiagnostics)
Dim err = trivia.Errors().First
Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code)
End Sub
<Fact>
Public Sub TestGreaterThanConflictMarker1()
' Needs to be followed by a space.
Dim token = SyntaxFactory.ParseTokens(">>>>>>>").First()
Assert.Equal(SyntaxKind.GreaterThanGreaterThanToken, token.Kind())
' Has to be the start of a line.
token = SyntaxFactory.ParseTokens(" >>>>>>>").First()
Assert.Equal(SyntaxKind.GreaterThanGreaterThanToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Assert.True(token.LeadingTrivia.Single().Kind() = SyntaxKind.WhitespaceTrivia)
' Has to have at least seven characters.
token = SyntaxFactory.ParseTokens(">>>>>> ").First()
Assert.Equal(SyntaxKind.GreaterThanGreaterThanToken, token.Kind())
' Start of line, seven characters, ends with space.
token = SyntaxFactory.ParseTokens(">>>>>>> ").First()
Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Dim trivia = token.LeadingTrivia.Single()
Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia)
Assert.True(trivia.ContainsDiagnostics)
Dim err = trivia.Errors().First
Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code)
End Sub
<Fact>
Public Sub TestGreaterThanConflictMarker2()
Dim token = SyntaxFactory.ParseTokens("{" & vbCrLf & ">>>>>>>").Skip(2).First()
Assert.Equal(SyntaxKind.GreaterThanGreaterThanToken, token.Kind())
token = SyntaxFactory.ParseTokens("{" & vbCrLf & " >>>>>>>").Skip(2).First()
Assert.Equal(SyntaxKind.GreaterThanGreaterThanToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Assert.True(token.LeadingTrivia.Single().Kind() = SyntaxKind.WhitespaceTrivia)
token = SyntaxFactory.ParseTokens("{" & vbCrLf & ">>>>>> ").Skip(2).First()
Assert.Equal(SyntaxKind.GreaterThanGreaterThanToken, token.Kind())
token = SyntaxFactory.ParseTokens("{" & vbCrLf & ">>>>>>> ").Skip(2).First()
Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Dim trivia = token.LeadingTrivia.Single()
Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia)
Assert.True(trivia.SpanStart = 3)
Assert.True(trivia.Span.Length = 8)
Assert.True(trivia.ContainsDiagnostics)
Dim err = trivia.Errors().First
Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code)
End Sub
<Fact>
Public Sub TestEqualsConflictMarker1()
' Has to be the start of a line.
Dim token = SyntaxFactory.ParseTokens(" =======").First()
Assert.Equal(SyntaxKind.EqualsToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Assert.True(token.LeadingTrivia.Single().Kind() = SyntaxKind.WhitespaceTrivia)
' Has to have at least seven characters.
token = SyntaxFactory.ParseTokens("====== ").First()
Assert.Equal(SyntaxKind.EqualsToken, token.Kind())
' Start of line, seven characters
token = SyntaxFactory.ParseTokens("=======").First()
Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Assert.True(token.LeadingTrivia.Single().Kind() = SyntaxKind.ConflictMarkerTrivia)
' Start of line, seven characters
token = SyntaxFactory.ParseTokens("======= trailing chars").First()
Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Dim trivia = token.LeadingTrivia.Single()
Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia)
Assert.Equal(trivia.Span.Length, 22)
Assert.True(trivia.ContainsDiagnostics)
Dim err = trivia.Errors().First
Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code)
token = SyntaxFactory.ParseTokens("======= Trailing" & vbCrLf & "disabled text").First()
Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Assert.Equal(3, token.LeadingTrivia.Count)
trivia = token.LeadingTrivia(0)
Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia)
Assert.Equal(trivia.Span.Length, 16)
Assert.True(trivia.ContainsDiagnostics)
err = trivia.Errors().First
Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code)
trivia = token.LeadingTrivia(1)
Assert.True(trivia.Kind() = SyntaxKind.EndOfLineTrivia)
Assert.Equal(trivia.Span.Start, 16)
Assert.Equal(trivia.Span.Length, 2)
trivia = token.LeadingTrivia(2)
Assert.True(trivia.Kind() = SyntaxKind.DisabledTextTrivia)
Assert.Equal(trivia.Span.Start, 18)
Assert.Equal(trivia.Span.Length, 13)
token = SyntaxFactory.ParseTokens("======= Trailing" & vbCrLf & "disabled text" & vbCrLf & ">>>> still disabled").First()
Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Assert.Equal(3, token.LeadingTrivia.Count)
trivia = token.LeadingTrivia(0)
Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia)
Assert.Equal(trivia.Span.Length, 16)
Assert.True(trivia.ContainsDiagnostics)
err = trivia.Errors().First
Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code)
trivia = token.LeadingTrivia(1)
Assert.True(trivia.Kind() = SyntaxKind.EndOfLineTrivia)
Assert.Equal(trivia.Span.Length, 2)
trivia = token.LeadingTrivia(2)
Assert.True(trivia.Kind() = SyntaxKind.DisabledTextTrivia)
Assert.Equal(trivia.Span.Length, 34)
token = SyntaxFactory.ParseTokens("======= Trailing" & vbCrLf & "disabled text" & vbCrLf & ">>>>>>> Actually the end").First()
Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Assert.Equal(token.LeadingTrivia.Count, 4)
Dim trivia1 = token.LeadingTrivia(0)
Assert.True(trivia1.Kind() = SyntaxKind.ConflictMarkerTrivia)
Assert.Equal(trivia1.Span.Length, 16)
Assert.True(trivia1.ContainsDiagnostics)
err = trivia1.Errors().First
Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code)
Dim trivia2 = token.LeadingTrivia(1)
Assert.True(trivia2.Kind() = SyntaxKind.EndOfLineTrivia)
Assert.Equal(trivia2.Span.Start, 16)
Assert.Equal(trivia2.Span.Length, 2)
Dim trivia3 = token.LeadingTrivia(2)
Assert.True(trivia3.Kind() = SyntaxKind.DisabledTextTrivia)
Assert.Equal(trivia3.Span.Start, 18)
Assert.Equal(trivia3.Span.Length, 15)
Dim trivia4 = token.LeadingTrivia(3)
Assert.True(trivia4.Kind() = SyntaxKind.ConflictMarkerTrivia)
Assert.Equal(trivia4.Span.Start, 33)
Assert.Equal(trivia4.Span.Length, 24)
Assert.True(trivia4.ContainsDiagnostics)
err = trivia4.Errors().First
Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code)
End Sub
<Fact>
Public Sub TestEqualsConflictMarker2()
' Has to be the start of a line.
Dim token = SyntaxFactory.ParseTokens("{" & vbCrLf & " =======").Skip(2).First()
Assert.Equal(SyntaxKind.EqualsToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Assert.True(token.LeadingTrivia.Single().Kind() = SyntaxKind.WhitespaceTrivia)
' Has to have at least seven characters.
token = SyntaxFactory.ParseTokens("{" & vbCrLf & "====== ").Skip(2).First()
Assert.Equal(SyntaxKind.EqualsToken, token.Kind())
' Start of line, seven characters
token = SyntaxFactory.ParseTokens("{" & vbCrLf & "=======").Skip(2).First()
Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Dim trivia = token.LeadingTrivia.Single()
Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia)
Assert.True(trivia.ContainsDiagnostics)
Dim err = trivia.Errors().First
Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code)
' Start of line, seven characters
token = SyntaxFactory.ParseTokens("{" & vbCrLf & "======= trailing chars").Skip(2).First()
Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
trivia = token.LeadingTrivia.Single()
Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia)
Assert.Equal(trivia.Span.Length, 22)
Assert.True(trivia.ContainsDiagnostics)
err = trivia.Errors().First
Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code)
token = SyntaxFactory.ParseTokens("{" & vbCrLf & "======= Trailing" & vbCrLf & "disabled text").Skip(2).First()
Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Assert.Equal(3, token.LeadingTrivia.Count)
trivia = token.LeadingTrivia(0)
Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia)
Assert.Equal(trivia.Span.Length, 16)
Assert.True(trivia.ContainsDiagnostics)
err = trivia.Errors().First
Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code)
trivia = token.LeadingTrivia(1)
Assert.True(trivia.Kind() = SyntaxKind.EndOfLineTrivia)
Assert.Equal(trivia.Span.Start, 19)
Assert.Equal(trivia.Span.Length, 2)
trivia = token.LeadingTrivia(2)
Assert.True(trivia.Kind() = SyntaxKind.DisabledTextTrivia)
Assert.Equal(trivia.Span.Start, 21)
Assert.Equal(trivia.Span.Length, 13)
token = SyntaxFactory.ParseTokens("{" & vbCrLf & "======= Trailing" & vbCrLf & "disabled text" & vbCrLf & ">>>> still disabled").Skip(2).First()
Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Assert.Equal(3, token.LeadingTrivia.Count)
trivia = token.LeadingTrivia(0)
Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia)
Assert.Equal(trivia.Span.Length, 16)
Assert.True(trivia.ContainsDiagnostics)
err = trivia.Errors().First
Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code)
trivia = token.LeadingTrivia(1)
Assert.True(trivia.Kind() = SyntaxKind.EndOfLineTrivia)
Assert.Equal(trivia.Span.Length, 2)
trivia = token.LeadingTrivia(2)
Assert.True(trivia.Kind() = SyntaxKind.DisabledTextTrivia)
Assert.Equal(trivia.Span.Length, 34)
token = SyntaxFactory.ParseTokens("{" & vbCrLf & "======= Trailing" & vbCrLf & "disabled text" & vbCrLf & ">>>>>>> Actually the end").Skip(2).First()
Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Assert.Equal(token.LeadingTrivia.Count, 4)
Dim trivia1 = token.LeadingTrivia(0)
Assert.True(trivia1.Kind() = SyntaxKind.ConflictMarkerTrivia)
Assert.Equal(trivia1.Span.Length, 16)
Assert.True(trivia1.ContainsDiagnostics)
err = trivia1.Errors().First
Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code)
Dim trivia2 = token.LeadingTrivia(1)
Assert.True(trivia2.Kind() = SyntaxKind.EndOfLineTrivia)
Assert.Equal(trivia2.Span.Start, 19)
Assert.Equal(trivia2.Span.Length, 2)
Dim trivia3 = token.LeadingTrivia(2)
Assert.True(trivia3.Kind() = SyntaxKind.DisabledTextTrivia)
Assert.Equal(trivia3.Span.Start, 21)
Assert.Equal(trivia3.Span.Length, 15)
Dim trivia4 = token.LeadingTrivia(3)
Assert.True(trivia4.Kind() = SyntaxKind.ConflictMarkerTrivia)
Assert.Equal(trivia4.Span.Start, 36)
Assert.Equal(trivia4.Span.Length, 24)
Assert.True(trivia4.ContainsDiagnostics)
err = trivia4.Errors().First
Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code)
End Sub
<Fact>
Public Sub Scanner_EndOfText()
Dim tk = ScanOnce("")
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal("", tk.ToFullString())
tk = ScanOnce(" ")
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(" ", tk.ToFullString())
tk = ScanOnce(" ")
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(" ", tk.ToFullString())
tk = ScanOnce("'")
Assert.Equal(SyntaxKind.EmptyToken, tk.Kind)
Assert.Equal(SyntaxKind.CommentTrivia, tk.TrailingTrivia(0).Kind)
Assert.Equal("'", tk.ToFullString())
tk = ScanOnce("'", startStatement:=True)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(SyntaxKind.CommentTrivia, tk.LeadingTrivia(0).Kind)
Assert.Equal("'", tk.ToFullString())
tk = ScanOnce(" ' ")
Assert.Equal(SyntaxKind.EmptyToken, tk.Kind)
Assert.Equal(SyntaxKind.WhitespaceTrivia, tk.LeadingTrivia(0).Kind)
Assert.Equal(SyntaxKind.CommentTrivia, tk.TrailingTrivia(0).Kind)
Assert.Equal(" ", tk.LeadingTrivia(0).ToString())
Assert.Equal("' ", tk.TrailingTrivia(0).ToString())
Assert.Equal(" ' ", tk.ToFullString())
tk = ScanOnce(" ' ", startStatement:=True)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(SyntaxKind.WhitespaceTrivia, tk.LeadingTrivia(0).Kind)
Assert.Equal(SyntaxKind.CommentTrivia, tk.LeadingTrivia(1).Kind)
Assert.Equal(" ", tk.LeadingTrivia(0).ToString())
Assert.Equal("' ", tk.LeadingTrivia(1).ToString())
Assert.Equal(" ' ", tk.ToFullString())
End Sub
<Fact>
Public Sub Scanner_StatementTerminator()
Dim tk = ScanOnce(vbCr)
Assert.Equal(SyntaxKind.EmptyToken, tk.Kind)
Assert.Equal(vbCr, tk.ToFullString())
tk = ScanOnce(vbCr, startStatement:=True)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(vbCr, tk.ToFullString())
Dim tks = ScanAllCheckDw(vbCr)
Assert.Equal(1, tks.Count)
Assert.Equal(SyntaxKind.EndOfFileToken, tks(0).Kind)
Assert.Equal(vbCr, tks(0).ToFullString())
tks = ScanAllCheckDw(" " & vbLf)
Assert.Equal(1, tks.Count)
Assert.Equal(SyntaxKind.EndOfFileToken, tks(0).Kind)
Assert.Equal(" " & vbLf, tks(0).ToFullString())
tks = ScanAllCheckDw(" A" & vbCrLf & " ")
Assert.Equal(3, tks.Count)
Assert.Equal(SyntaxKind.IdentifierToken, tks(0).Kind)
Assert.Equal(" A" & vbCrLf, tks(0).ToFullString())
Assert.Equal(SyntaxKind.StatementTerminatorToken, tks(1).Kind)
Assert.Equal("", tks(1).ToFullString())
Assert.Equal(SyntaxKind.EndOfFileToken, tks(2).Kind)
Assert.Equal(" ", tks(2).ToFullString())
End Sub
<Fact>
Public Sub Scanner_StartStatement()
Dim tk = ScanOnce(vbCr, startStatement:=True)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(vbCr, tk.ToFullString())
tk = ScanOnce(" " & vbLf, startStatement:=True)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(" " & vbLf, tk.ToFullString())
Dim str = " " & vbCrLf & " " & vbCr & "'2 " & vbLf & " ("
tk = ScanOnce(str, startStatement:=True)
Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind)
Assert.Equal(str, tk.ToFullString())
str = "'("
tk = ScanOnce(str, startStatement:=True)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(str, tk.ToFullString())
str = "'" & vbCrLf & "("
tk = ScanOnce(str, startStatement:=False)
Assert.Equal(SyntaxKind.EmptyToken, tk.Kind)
Assert.Equal("'" & vbCrLf, tk.ToFullString())
str = "'" & vbCrLf & "("
tk = ScanOnce(str, startStatement:=True)
Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind)
Assert.Equal(str, tk.ToFullString())
str = "' " & vbCrLf & " '(" & vbCrLf & "("
tk = ScanOnce(str, startStatement:=True)
Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind)
Assert.Equal(str, tk.ToFullString())
End Sub
<Fact>
Public Sub Scanner_LineContWhenExpectingNewStatement()
Dim tk = ScanOnce("_", startStatement:=True)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal("_", tk.ToFullString())
tk = ScanOnce(" _", startStatement:=True)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(" _", tk.ToFullString())
tk = ScanOnce(" _ ", startStatement:=True)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(" _ ", tk.ToFullString())
tk = ScanOnce(" _'", startStatement:=True)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(" _'", tk.ToFullString())
Assert.Equal(3, tk.LeadingTrivia.Count)
Assert.Equal(SyntaxKind.WhitespaceTrivia, tk.LeadingTrivia(0).Kind)
Assert.Equal(SyntaxKind.LineContinuationTrivia, tk.LeadingTrivia(1).Kind)
Assert.Equal(SyntaxKind.CommentTrivia, tk.LeadingTrivia(2).Kind)
Assert.Equal(0, tk.Errors.Count)
tk = ScanOnce(" _'", LanguageVersion.VisualBasic16)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(" _'", tk.ToFullString())
Assert.Equal(3, tk.LeadingTrivia.Count)
Assert.Equal(SyntaxKind.WhitespaceTrivia, tk.LeadingTrivia(0).Kind)
Assert.Equal(SyntaxKind.LineContinuationTrivia, tk.LeadingTrivia(1).Kind)
Assert.Equal(SyntaxKind.CommentTrivia, tk.LeadingTrivia(2).Kind)
Assert.Equal(0, tk.Errors.Count)
tk = ScanOnce(" _' Comment", LanguageVersion.VisualBasic15_3)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(" _' Comment", tk.ToFullString())
Assert.Equal(3, tk.LeadingTrivia.Count)
Assert.Equal(SyntaxKind.WhitespaceTrivia, tk.LeadingTrivia(0).Kind)
Assert.False(tk.LeadingTrivia(0).ContainsDiagnostics)
Assert.Equal(SyntaxKind.LineContinuationTrivia, tk.LeadingTrivia(1).Kind)
Assert.False(tk.LeadingTrivia(1).ContainsDiagnostics)
Assert.Equal(SyntaxKind.CommentTrivia, tk.LeadingTrivia(2).Kind)
Assert.True(tk.LeadingTrivia(2).ContainsDiagnostics)
Assert.Equal(1, tk.Errors.Count)
Assert.Equal(ERRID.ERR_CommentsAfterLineContinuationNotAvailable1, tk.Errors.First().Code)
tk = ScanOnce(" _' Comment", LanguageVersion.VisualBasic16)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(" _' Comment", tk.ToFullString())
Assert.Equal(3, tk.LeadingTrivia.Count)
Assert.Equal(SyntaxKind.WhitespaceTrivia, tk.LeadingTrivia(0).Kind)
Assert.Equal(SyntaxKind.LineContinuationTrivia, tk.LeadingTrivia(1).Kind)
Assert.Equal(SyntaxKind.CommentTrivia, tk.LeadingTrivia(2).Kind)
Assert.Equal(0, tk.Errors.Count)
tk = ScanOnce(" _ ' Comment" & vbCrLf, LanguageVersion.VisualBasic16)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(" _ ' Comment" & vbCrLf, tk.ToFullString())
Assert.Equal(5, tk.LeadingTrivia.Count)
Assert.Equal(SyntaxKind.WhitespaceTrivia, tk.LeadingTrivia(0).Kind)
Assert.Equal(SyntaxKind.LineContinuationTrivia, tk.LeadingTrivia(1).Kind)
Assert.Equal(SyntaxKind.WhitespaceTrivia, tk.LeadingTrivia(2).Kind)
Assert.Equal(SyntaxKind.CommentTrivia, tk.LeadingTrivia(3).Kind)
Assert.Equal(SyntaxKind.EndOfLineTrivia, tk.LeadingTrivia(4).Kind)
Assert.Equal(0, tk.Errors.Count)
tk = ScanOnce(" _ rem", startStatement:=True)
Assert.Equal(SyntaxKind.BadToken, tk.Kind)
Assert.Equal(" _ rem", tk.ToFullString())
Assert.Equal(30999, tk.Errors.First().Code)
tk = ScanOnce(" _ abc", startStatement:=True)
Assert.Equal(SyntaxKind.BadToken, tk.Kind)
Assert.Equal(" _ ", tk.ToFullString())
Assert.Equal(30203, tk.Errors.First().Code)
Dim tks = ScanAllCheckDw(" _ rem")
Assert.Equal(SyntaxKind.BadToken, tks(0).Kind)
Assert.Equal(" _ rem", tks(0).ToFullString())
Assert.Equal(30999, tks(0).Errors.First().Code)
tk = ScanOnce("_" & vbLf, startStatement:=True)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal("_" & vbLf, tk.ToFullString())
tk = ScanOnce(" _" & vbLf, startStatement:=True)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(" _" & vbLf, tk.ToFullString())
Dim str = " _" & vbCrLf & " _" & vbCr & "'2 " & vbLf & " ("
tk = ScanOnce(str, startStatement:=True)
Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind)
Assert.Equal(str, tk.ToFullString())
str = " _" & vbCrLf & " _" & vbCrLf & "("
tk = ScanOnce(str, startStatement:=True)
Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind)
Assert.Equal(str, tk.ToFullString())
End Sub
<Fact>
Public Sub Scanner_LineContInsideStatement()
' this would be a case of )_
' valid _ would have been consumed by )
Dim tk = ScanOnce("_" & vbLf, False)
Assert.Equal(SyntaxKind.BadToken, tk.Kind)
Assert.Equal("_" + vbLf, tk.ToFullString)
Dim Str = "'_" & vbCrLf & "("
tk = ScanOnce(Str, False)
Assert.Equal(SyntaxKind.EmptyToken, tk.Kind)
Assert.Equal("'_" & vbCrLf, tk.ToFullString())
Str = " _" & vbCrLf & "("
tk = ScanOnce(Str, False)
Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind)
Assert.Equal(Str, tk.ToFullString())
' _ is invalid here, should not be consumed by (
Str = " _" & vbCrLf & "(" & "_" & vbCrLf & "'qq"
tk = ScanOnce(Str, False)
Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind)
Assert.Equal(" _" & vbCrLf & "(", tk.ToFullString())
' _ is valid here, but we should not go past the Eol
Str = " _" & vbCrLf & "(" & " _" & vbCrLf & "'qq"
tk = ScanOnce(Str, False)
Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind)
Assert.Equal(" _" & vbCrLf & "(" & " _" & vbCrLf, tk.ToFullString())
End Sub
<Fact>
Public Sub Scanner_RemComment()
Dim str = " " & vbCrLf & " " & vbCr & "REM " & vbLf & " ("
Dim tk = ScanOnce(str, True)
Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind)
Assert.Equal(str, tk.ToFullString())
str = "A REM Hello "
tk = ScanOnce(str, True)
Assert.Equal(SyntaxKind.IdentifierToken, tk.Kind)
Assert.Equal(str, tk.ToFullString())
str = "A A REM Hello " & vbCrLf & "A Rem Hello "
Dim tks = ScanAllCheckDw(str)
Assert.Equal(SyntaxKind.IdentifierToken, tks(0).Kind)
Assert.Equal("A ", tks(0).ToFullString)
Assert.Equal(SyntaxKind.IdentifierToken, tks(1).Kind)
Assert.NotEqual("A ", tks(1).ToFullString)
Assert.Equal(SyntaxKind.StatementTerminatorToken, tks(2).Kind)
Assert.Equal(SyntaxKind.IdentifierToken, tks(3).Kind)
Assert.NotEqual("A ", tks(1).ToFullString)
Assert.Equal(SyntaxKind.EndOfFileToken, tks(4).Kind)
Assert.Equal(5, tks.Count)
REM(
str = "REM("
tk = ScanOnce(str, True)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(str, tk.ToFullString())
str = "ReM" & vbCrLf & "("
tk = ScanOnce(str, False)
Assert.Equal(SyntaxKind.EmptyToken, tk.Kind)
Assert.Equal("ReM" & vbCrLf, tk.ToFullString())
str = "rEM" & vbCrLf & "("
tk = ScanOnce(str, True)
Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind)
Assert.Equal(str, tk.ToFullString())
str = "rem " & vbCrLf & " REM(" & vbCrLf & "("
tk = ScanOnce(str, True)
Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind)
Assert.Equal(str, tk.ToFullString())
End Sub
''' <summary>
''' EmptyToken is generated by the Scanner in a single-line
''' If or lambda with an empty statement to avoid generating
''' a statement terminator with leading or trailing trivia.
''' </summary>
<Fact>
Public Sub Scanner_EmptyToken()
' No EmptyToken required because no trivia before EOF.
ParseTokensAndVerify("If True Then Else Return :",
SyntaxKind.IfKeyword,
SyntaxKind.TrueKeyword,
SyntaxKind.ThenKeyword,
SyntaxKind.ElseKeyword,
SyntaxKind.ReturnKeyword,
SyntaxKind.ColonToken,
SyntaxKind.EndOfFileToken)
' No EmptyToken required because no trailing trivia before EOF.
' (The space after the colon is leading trivia on EOF.)
ParseTokensAndVerify("If True Then Else : ",
SyntaxKind.IfKeyword,
SyntaxKind.TrueKeyword,
SyntaxKind.ThenKeyword,
SyntaxKind.ElseKeyword,
SyntaxKind.ColonToken,
SyntaxKind.EndOfFileToken)
' EmptyToken required because comment is trailing
' trivia between the colon and EOL.
ParseTokensAndVerify(<![CDATA[If True Then Else :'Comment
Return]]>.Value,
SyntaxKind.IfKeyword,
SyntaxKind.TrueKeyword,
SyntaxKind.ThenKeyword,
SyntaxKind.ElseKeyword,
SyntaxKind.ColonToken,
SyntaxKind.EmptyToken,
SyntaxKind.StatementTerminatorToken,
SyntaxKind.ReturnKeyword,
SyntaxKind.EndOfFileToken)
' EmptyToken required because comment is trailing
' trivia between the colon and EOF.
ParseTokensAndVerify("Sub() If True Then Return : REM",
SyntaxKind.SubKeyword,
SyntaxKind.OpenParenToken,
SyntaxKind.CloseParenToken,
SyntaxKind.IfKeyword,
SyntaxKind.TrueKeyword,
SyntaxKind.ThenKeyword,
SyntaxKind.ReturnKeyword,
SyntaxKind.ColonToken,
SyntaxKind.EmptyToken,
SyntaxKind.EndOfFileToken)
' No EmptyToken required because colon, space, comment
' and EOL are all treated as multi-line leading trivia on EndKeyword.
ParseTokensAndVerify(<![CDATA[If True Then
: 'Comment
End If]]>.Value,
SyntaxKind.IfKeyword,
SyntaxKind.TrueKeyword,
SyntaxKind.ThenKeyword,
SyntaxKind.StatementTerminatorToken,
SyntaxKind.EndKeyword,
SyntaxKind.IfKeyword,
SyntaxKind.EndOfFileToken)
End Sub
Private Sub ParseTokensAndVerify(str As String, ParamArray kinds As SyntaxKind())
Dim tokens = SyntaxFactory.ParseTokens(str).ToArray()
Dim result = String.Join("", tokens.Select(Function(t) t.ToFullString()))
Assert.Equal(str, result)
Assert.Equal(tokens.Length, kinds.Length)
For i = 0 To tokens.Length - 1
Assert.Equal(tokens(i).Kind, kinds(i))
Next
End Sub
<Fact>
Public Sub Scanner_DimKeyword()
Dim Str = " " & vbCrLf & " " & vbCr & "DIM " & vbLf & " ("
Dim tk = ScanOnce(Str, True)
Assert.Equal(SyntaxKind.DimKeyword, tk.Kind)
Assert.Equal(" " & vbCrLf & " " & vbCr & "DIM " + vbLf, tk.ToFullString)
Str = "Dim("
tk = ScanOnce(Str, True)
Assert.Equal(SyntaxKind.DimKeyword, tk.Kind)
Assert.Equal("Dim", tk.ToFullString())
Str = "DiM" & vbCrLf & "("
tk = ScanOnce(Str, False)
Assert.Equal(SyntaxKind.DimKeyword, tk.Kind)
Assert.Equal("DiM" + vbCrLf, tk.ToFullString)
Str = "dIM" & " _" & vbCrLf & "("
tk = ScanOnce(Str, True)
Assert.Equal(SyntaxKind.DimKeyword, tk.Kind)
Assert.Equal("dIM" & " _" & vbCrLf, tk.ToFullString())
Str = "dim " & vbCrLf & " DIMM" & vbCrLf & "("
Dim tks = ScanAllNoDwCheck(Str)
Assert.Equal(SyntaxKind.DimKeyword, tks(0).Kind)
Assert.Equal(SyntaxKind.StatementTerminatorToken, tks(1).Kind)
Assert.Equal(SyntaxKind.IdentifierToken, tks(2).Kind)
Assert.Equal(SyntaxKind.StatementTerminatorToken, tks(3).Kind)
Assert.Equal(SyntaxKind.OpenParenToken, tks(4).Kind)
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact>
Public Sub StaticKeyword()
Dim Str = " " & vbCrLf & " " & vbCr & "STATIC " & vbLf & " ("
Dim tk = ScanOnce(Str, True)
Assert.Equal(SyntaxKind.StaticKeyword, tk.Kind)
Assert.Equal(" " & vbCrLf & " " & vbCr & "STATIC " & vbLf, tk.ToFullString())
Str = "Static("
tk = ScanOnce(Str, True)
Assert.Equal(SyntaxKind.StaticKeyword, tk.Kind)
Assert.Equal("Static", tk.ToFullString())
Str = "StatiC" & vbCrLf & "("
tk = ScanOnce(Str, False)
Assert.Equal(SyntaxKind.StaticKeyword, tk.Kind)
Assert.Equal("StatiC" & vbCrLf, tk.ToFullString())
Str = "sTATIC" & " _" & vbCrLf & "("
tk = ScanOnce(Str, True)
Assert.Equal(SyntaxKind.StaticKeyword, tk.Kind)
Assert.Equal("sTATIC" & " _" & vbCrLf, tk.ToFullString())
Str = "static " & vbCrLf & " STATICC" & vbCrLf & "("
Dim tks = ScanAllNoDwCheck(Str)
Assert.Equal(SyntaxKind.StaticKeyword, tks(0).Kind)
Assert.Equal(SyntaxKind.StatementTerminatorToken, tks(1).Kind)
Assert.Equal(SyntaxKind.IdentifierToken, tks(2).Kind)
Assert.Equal(SyntaxKind.StatementTerminatorToken, tks(3).Kind)
Assert.Equal(SyntaxKind.OpenParenToken, tks(4).Kind)
End Sub
<Fact>
Public Sub Scanner_FrequentKeywords()
Dim Str = "End "
Dim tk = ScanOnce(Str, True)
Assert.Equal(SyntaxKind.EndKeyword, tk.Kind)
Assert.Equal(3, tk.Span.Length)
Assert.Equal(4, tk.FullSpan.Length)
Assert.Equal("End ", tk.ToFullString())
Str = "As "
tk = ScanOnce(Str, False)
Assert.Equal(SyntaxKind.AsKeyword, tk.Kind)
Assert.Equal(2, tk.Span.Length)
Assert.Equal(3, tk.FullSpan.Length)
Assert.Equal("As ", tk.ToFullString())
Str = "If "
tk = ScanOnce(Str, False)
Assert.Equal(SyntaxKind.IfKeyword, tk.Kind)
Assert.Equal(2, tk.Span.Length)
Assert.Equal(3, tk.FullSpan.Length)
Assert.Equal("If ", tk.ToFullString())
End Sub
<Fact>
Public Sub Scanner_PlusToken()
Dim Str = "+"
Dim tk = ScanOnce(Str, True)
Assert.Equal(SyntaxKind.PlusToken, tk.Kind)
Assert.Equal(Str, tk.ToFullString())
Str = "+ ="
tk = ScanOnce(Str, True)
Assert.Equal(SyntaxKind.PlusEqualsToken, tk.Kind)
Assert.Equal(Str, tk.ToFullString())
End Sub
<Fact>
Public Sub Scanner_PowerToken()
Dim Str = "^"
Dim tk = ScanOnce(Str, False)
Assert.Equal(SyntaxKind.CaretToken, tk.Kind)
Assert.Equal(Str, tk.ToFullString())
Str = "^ =^"
Dim tks = ScanAllCheckDw(Str)
Assert.Equal(SyntaxKind.CaretEqualsToken, tks(0).Kind)
Assert.Equal(SyntaxKind.CaretToken, tks(1).Kind)
End Sub
<Fact>
Public Sub Scanner_GreaterThanToken()
Dim Str = "> "
Dim tk = ScanOnce(Str, False)
Assert.Equal(SyntaxKind.GreaterThanToken, tk.Kind)
Assert.Equal(Str, tk.ToFullString())
Str = " >= 'qqqq"
tk = ScanOnce(Str, True)
Assert.Equal(SyntaxKind.GreaterThanEqualsToken, tk.Kind)
Assert.Equal(Str, tk.ToFullString())
Str = " > ="
tk = ScanOnce(Str, True)
Assert.Equal(SyntaxKind.GreaterThanEqualsToken, tk.Kind)
Assert.Equal(Str, tk.ToFullString())
'Str = " >" & vbCrLf & "="
'tk = ScanOnce(Str, True)
'Assert.Equal(NodeKind.GreaterToken, tk.Kind)
'Assert.Equal(" >" & vbCrLf, tk.ToFullString())
'Str = ">" & " _" & vbCrLf & "="
'tk = ScanOnce(Str, True)
'Assert.Equal(NodeKind.GreaterToken, tk.Kind)
'Assert.Equal(">" & " _" & vbCrLf, tk.ToFullString())
End Sub
<Fact>
Public Sub Scanner_LessThanToken()
Dim Str = "> <"
Dim tks = ScanAllCheckDw(Str)
Assert.Equal(SyntaxKind.GreaterThanToken, tks(0).Kind)
Assert.Equal(SyntaxKind.LessThanToken, tks(1).Kind)
Str = "<<<<%"
tks = ScanAllCheckDw(Str)
Assert.Equal(SyntaxKind.LessThanLessThanToken, tks(0).Kind)
Assert.Equal(SyntaxKind.LessThanToken, tks(1).Kind)
Assert.Equal(SyntaxKind.LessThanToken, tks(2).Kind)
Assert.Equal(SyntaxKind.BadToken, tks(3).Kind)
Assert.Equal(SyntaxKind.EndOfFileToken, tks(4).Kind)
Str = " < << <% "
tks = ScanAllCheckDw(Str)
Assert.Equal(SyntaxKind.LessThanLessThanToken, tks(0).Kind)
Assert.Equal(SyntaxKind.LessThanToken, tks(1).Kind)
Assert.Equal(SyntaxKind.LessThanToken, tks(2).Kind)
Assert.Equal(SyntaxKind.BadToken, tks(3).Kind)
Assert.Equal(SyntaxKind.EndOfFileToken, tks(4).Kind)
End Sub
<Fact>
Public Sub Scanner_ShiftLeftToken()
Dim Str = "<<<<="
Dim tks = ScanAllCheckDw(Str)
Assert.Equal(SyntaxKind.LessThanLessThanToken, tks(0).Kind)
Assert.Equal(SyntaxKind.LessThanLessThanEqualsToken, tks(1).Kind)
Assert.Equal(SyntaxKind.EndOfFileToken, tks(2).Kind)
'Str = "<" & vbLf & " < < = "
'tks = ScanAllCheckDw(Str)
'Assert.Equal(NodeKind.LessToken, tks(0).Kind)
'Assert.Equal(NodeKind.LeftShiftEqualsToken, tks(1).Kind)
'Assert.Equal(NodeKind.EndOfTextToken, tks(2).Kind)
'' left shift does not allow implicit line continuation
'Str = "<<" & vbLf & "<<="
'tks = ScanAllCheckDw(Str)
'Assert.Equal(NodeKind.LeftShiftToken, tks(0).Kind)
'Assert.Equal(NodeKind.StatementTerminatorToken, tks(1).Kind)
'Assert.Equal(NodeKind.LeftShiftEqualsToken, tks(2).Kind)
'Assert.Equal(NodeKind.EndOfTextToken, tks(3).Kind)
End Sub
<Fact>
Public Sub Scanner_NotEqualsToken()
Dim Str = "<>"
Dim tks = ScanAllCheckDw(Str)
Assert.Equal(SyntaxKind.LessThanGreaterThanToken, tks(0).Kind)
Assert.Equal(SyntaxKind.EndOfFileToken, tks(1).Kind)
Str = "<>="
tks = ScanAllCheckDw(Str)
Assert.Equal(SyntaxKind.LessThanGreaterThanToken, tks(0).Kind)
Assert.Equal(SyntaxKind.EqualsToken, tks(1).Kind)
Assert.Equal(SyntaxKind.EndOfFileToken, tks(2).Kind)
'Str = "<" & vbLf & " > "
'tks = ScanAllCheckDw(Str)
'Assert.Equal(NodeKind.LessToken, tks(0).Kind)
'Assert.Equal(NodeKind.GreaterToken, tks(1).Kind)
'Assert.Equal(NodeKind.EndOfTextToken, tks(2).Kind)
'' left shift does not allow implicit line continuation
'Str = "< > <" & " _" & vbLf & ">"
'tks = ScanAllCheckDw(Str)
'Assert.Equal(NodeKind.NotEqualToken, tks(0).Kind)
'Assert.Equal(NodeKind.LessToken, tks(1).Kind)
'Assert.Equal(NodeKind.GreaterToken, tks(2).Kind)
'Assert.Equal(NodeKind.EndOfTextToken, tks(3).Kind)
End Sub
Private Sub CheckCharTkValue(tk As SyntaxToken, expected As Char)
Dim val = DirectCast(tk.Value, Char)
Assert.Equal(expected, val)
End Sub
<Fact>
Public Sub Scanner_CharLiteralToken()
Dim Str = <text>"Q"c</text>.Value
Dim tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.CharacterLiteralToken, tk.Kind)
Assert.Equal(Str, tk.ToFullString())
CheckCharTkValue(tk, "Q"c)
Str = <text>""""c</text>.Value
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.CharacterLiteralToken, tk.Kind)
Assert.Equal(Str, tk.ToFullString())
CheckCharTkValue(tk, """"c)
Str = <text>""c</text>.Value
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.BadToken, tk.Kind)
Assert.Equal(30004, tk.GetSyntaxErrorsNoTree()(0).Code)
Assert.Equal(Str, tk.ToFullString())
Str = <text>"""c</text>.Value
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.StringLiteralToken, tk.Kind)
Assert.Equal(30648, tk.GetSyntaxErrorsNoTree()(0).Code)
Assert.Equal(Str, tk.ToFullString())
CheckStrTkValue(tk, """c")
Str = <text>"QQ"c</text>.Value
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.BadToken, tk.Kind)
Assert.Equal(30004, tk.GetSyntaxErrorsNoTree()(0).Code)
Assert.Equal(Str, tk.ToFullString())
Str = <text>"Q"c "Q"c"Q"c "Q"c _
"Q"c
""""c</text>.Value
Dim doubleWidthStr = MakeDwString(Str)
Dim tks = ScanAllNoDwCheck(doubleWidthStr)
Assert.Equal(10, tks.Count)
Assert.Equal(True, tks.Any(Function(t) t.ContainsDiagnostics))
End Sub
Private Sub CheckStrTkValue(tk As SyntaxToken, expected As String)
Dim str = DirectCast(tk.Value, String)
Assert.Equal(expected, str)
End Sub
<Fact>
Public Sub Scanner_StringLiteralToken()
Dim Str = <text>""</text>.Value
Dim tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.StringLiteralToken, tk.Kind)
Assert.Equal(Str, tk.ToFullString())
CheckStrTkValue(tk, "")
Str = <text>"Q"</text>.Value
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.StringLiteralToken, tk.Kind)
Assert.Equal(Str, tk.ToFullString())
CheckStrTkValue(tk, "Q")
Str = <text>""""</text>.Value
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.StringLiteralToken, tk.Kind)
Assert.Equal(Str, tk.ToFullString())
CheckStrTkValue(tk, """")
Str = <text>""""""""</text>.Value
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.StringLiteralToken, tk.Kind)
Assert.Equal(Str, tk.ToFullString())
CheckStrTkValue(tk, """""""")
Str = <text>"""" """"</text>.Value
Dim tks = ScanAllCheckDw(Str)
Assert.Equal(SyntaxKind.StringLiteralToken, tks(0).Kind)
Assert.Equal(SyntaxKind.StringLiteralToken, tks(1).Kind)
Str = <text>"AA"
"BB"</text>.Value
tks = ScanAllCheckDw(Str)
Assert.Equal(SyntaxKind.StringLiteralToken, tks(0).Kind)
Assert.Equal(SyntaxKind.StatementTerminatorToken, tks(1).Kind)
Assert.Equal(SyntaxKind.StringLiteralToken, tks(2).Kind)
End Sub
<Fact>
Public Sub Scanner_IntegerLiteralToken()
Dim Str = "42"
Dim tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(LiteralBase.Decimal, tk.GetBase())
Assert.Equal(42, tk.Value)
Str = " 42 "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(LiteralBase.Decimal, tk.GetBase())
Assert.Equal(42, tk.Value)
Assert.Equal(" 42 ", tk.ToFullString())
Str = " 4_2 "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(LiteralBase.Decimal, tk.GetBase())
Assert.Equal(42, tk.Value)
Assert.Equal(" 4_2 ", tk.ToFullString())
Assert.Equal(0, tk.Errors().Count)
Str = " &H42L "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(LiteralBase.Hexadecimal, tk.GetBase())
Assert.Equal(&H42L, tk.Value)
Assert.Equal(" &H42L ", tk.ToFullString())
Str = " &H4_2L "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(LiteralBase.Hexadecimal, tk.GetBase())
Assert.Equal(&H42L, tk.Value)
Assert.Equal(" &H4_2L ", tk.ToFullString())
Str = " &H_1 "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(LiteralBase.Hexadecimal, tk.GetBase())
Assert.Equal(&H1, tk.Value)
Assert.Equal(" &H_1 ", tk.ToFullString())
Str = " &B_1 "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(LiteralBase.Binary, tk.GetBase())
Assert.Equal(&B1, tk.Value)
Assert.Equal(" &B_1 ", tk.ToFullString())
Str = " &O_1 "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(LiteralBase.Octal, tk.GetBase())
Assert.Equal(&O1, tk.Value)
Assert.Equal(" &O_1 ", tk.ToFullString())
Str = " &H__1_1L "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(LiteralBase.Hexadecimal, tk.GetBase())
Assert.Equal(&H11L, tk.Value)
Assert.Equal(" &H__1_1L ", tk.ToFullString())
Str = " &B__1_1L "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(LiteralBase.Binary, tk.GetBase())
Assert.Equal(&B11L, tk.Value)
Assert.Equal(" &B__1_1L ", tk.ToFullString())
Str = " &O__1_1L "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(LiteralBase.Octal, tk.GetBase())
Assert.Equal(&O11L, tk.Value)
Assert.Equal(" &O__1_1L ", tk.ToFullString())
Str = " &H42L &H42& "
Dim tks = ScanAllCheckDw(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tks(0).Kind)
Assert.Equal(LiteralBase.Hexadecimal, tks(1).GetBase())
Assert.Equal(&H42L, tks(1).Value)
Assert.Equal(TypeCharacter.Long, tks(1).GetTypeCharacter())
Str = " &B1010L "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(LiteralBase.Binary, tk.GetBase())
Assert.Equal(&HAL, tk.Value)
Assert.Equal(" &B1010L ", tk.ToFullString())
Assert.Equal(0, tk.Errors().Count)
Str = " &B1_0_1_0L "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(LiteralBase.Binary, tk.GetBase())
Assert.Equal(&HAL, tk.Value)
Assert.Equal(" &B1_0_1_0L ", tk.ToFullString())
Assert.Equal(0, tk.Errors().Count)
End Sub
<Fact>
Public Sub Scanner_FloatingLiteralToken()
Dim Str = "4.2"
Dim tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind)
Assert.Equal(4.2, tk.Value)
Str = " 0.42 "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind)
Assert.Equal(0.42, tk.Value)
Assert.IsType(Of Double)(tk.Value)
Assert.Equal(" 0.42 ", tk.ToFullString())
Str = " 0_0.4_2 "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind)
Assert.Equal(0.42, tk.Value)
Assert.IsType(Of Double)(tk.Value)
Assert.Equal(" 0_0.4_2 ", tk.ToFullString())
Str = " 0.42# "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind)
Assert.Equal(0.42, tk.Value)
Assert.IsType(Of Double)(tk.Value)
Assert.Equal(" 0.42# ", tk.ToFullString())
Str = " 0.42R "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind)
Assert.Equal(0.42, tk.Value)
Assert.IsType(Of Double)(tk.Value)
Assert.Equal(" 0.42R ", tk.ToFullString())
Str = " 0.42! "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind)
Assert.Equal(0.42!, tk.Value)
Assert.IsType(Of Single)(tk.Value)
Assert.Equal(" 0.42! ", tk.ToFullString())
Str = " 0.42F "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind)
Assert.Equal(0.42F, tk.Value)
Assert.IsType(Of Single)(tk.Value)
Assert.Equal(" 0.42F ", tk.ToFullString())
Str = " .42 42# "
Dim tks = ScanAllCheckDw(Str)
Assert.Equal(SyntaxKind.FloatingLiteralToken, tks(1).Kind)
Assert.Equal(42.0#, tks(1).Value)
Assert.Equal(0.42, tks(0).Value)
Assert.IsType(Of Double)(tks(1).Value)
Assert.Equal(TypeCharacter.Double, tks(1).GetTypeCharacter())
End Sub
<Fact>
Public Sub Scanner_DecimalLiteralToken()
Dim Str = "4.2D"
Dim tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.DecimalLiteralToken, tk.Kind)
Assert.Equal(TypeCharacter.DecimalLiteral, tk.GetTypeCharacter())
Assert.Equal(4.2D, tk.Value)
Str = " 0.42@ "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.DecimalLiteralToken, tk.Kind)
Assert.Equal(0.42@, tk.Value)
Assert.Equal(" 0.42@ ", tk.ToFullString())
Str = " .42D 4242424242424242424242424242@ "
Dim tks = ScanAllCheckDw(Str)
Assert.Equal(SyntaxKind.DecimalLiteralToken, tks(1).Kind)
Assert.Equal(4242424242424242424242424242D, tks(1).Value)
Assert.Equal(0.42D, tks(0).Value)
Assert.Equal(TypeCharacter.Decimal, tks(1).GetTypeCharacter())
End Sub
<WorkItem(538543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538543")>
<Fact>
Public Sub Scanner_DecimalLiteralExpToken()
Dim Str = "1E1D"
Dim tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.DecimalLiteralToken, tk.Kind)
Assert.Equal(TypeCharacter.DecimalLiteral, tk.GetTypeCharacter())
Assert.Equal(10D, tk.Value)
End Sub
<Fact>
Public Sub Scanner_Overflow()
Dim Str = "2147483647I"
Dim tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(2147483647I, CInt(tk.Value))
Str = "2147483648I"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(30036, tk.GetSyntaxErrorsNoTree()(0).Code)
Assert.Equal(0, CInt(tk.Value))
Str = "&H7FFFFFFFI"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(&H7FFFFFFFI, CInt(tk.Value))
Str = "&HFFFFFFFFI"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(&HFFFFFFFFI, tk.Value)
Str = "&HFFFFFFFFS"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(30036, tk.GetSyntaxErrorsNoTree()(0).Code)
Assert.Equal(0, CInt(tk.Value))
Str = "&B111111111111111111111111111111111I"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(30036, tk.GetSyntaxErrorsNoTree()(0).Code)
Assert.Equal(0, CInt(tk.Value))
Str = "&B11111111111111111111111111111111UI"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(&HFFFFFFFFUI, CUInt(tk.Value))
Str = "&B1111111111111111111111111111111I"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(&H7FFFFFFFI, CInt(tk.Value))
Str = "1.7976931348623157E+308d"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.DecimalLiteralToken, tk.Kind)
Assert.Equal(30036, tk.GetSyntaxErrorsNoTree()(0).Code)
Assert.Equal(0D, tk.Value)
Str = "1.797693134862315456489789797987987897897987987E+308F"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind)
Assert.Equal(30036, tk.GetSyntaxErrorsNoTree()(0).Code)
Assert.Equal(0.0F, tk.Value)
End Sub
<Fact>
Public Sub Scanner_UnderscoreWrongLocation()
Dim Str = "_1"
Dim tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IdentifierToken, tk.Kind)
Assert.Equal(0, tk.GetSyntaxErrorsNoTree().Count())
Str = "1_"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(30035, tk.GetSyntaxErrorsNoTree()(0).Code)
Assert.Equal(0, CInt(tk.Value))
Str = "&H1_"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(30035, tk.GetSyntaxErrorsNoTree()(0).Code)
Assert.Equal(0, CInt(tk.Value))
Str = "1_.1"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind)
Assert.Equal(30035, tk.GetSyntaxErrorsNoTree()(0).Code)
Assert.Equal(0, CInt(tk.Value))
Str = "1.1_"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind)
Assert.Equal(30035, tk.GetSyntaxErrorsNoTree()(0).Code)
Assert.Equal(0, CInt(tk.Value))
Str = "&H_"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Dim errors = tk.Errors()
Assert.Equal(1, errors.Count)
Assert.Equal(30035, errors.First().Code)
Assert.Equal(0, CInt(tk.Value))
Str = "&H_2_"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
errors = tk.Errors()
Assert.Equal(1, errors.Count)
Assert.Equal(30035, errors.First().Code)
Assert.Equal(0, CInt(tk.Value))
End Sub
<Fact>
Public Sub Scanner_UnderscoreFeatureFlag()
Dim Str = "&H_1"
Dim tk = ScanOnce(Str, LanguageVersion.VisualBasic14)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Dim errors = tk.Errors()
Assert.Equal(1, errors.Count)
Assert.Equal(36716, errors.First().Code)
Assert.Equal(1, CInt(tk.Value))
Str = "&H_123_456_789_ABC_DEF_123"
tk = ScanOnce(Str, LanguageVersion.VisualBasic14)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
errors = tk.Errors()
Assert.Equal(2, errors.Count)
Assert.Equal(30036, errors.ElementAt(0).Code)
Assert.Equal(36716, errors.ElementAt(1).Code)
Assert.Equal(0, CInt(tk.Value))
End Sub
<Fact>
Public Sub Scanner_DateLiteralToken()
Dim Str = "#10/10/2010#"
Dim tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.DateLiteralToken, tk.Kind)
Assert.Equal(#10/10/2010#, tk.Value)
Str = "#10/10/1#"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.DateLiteralToken, tk.Kind)
Assert.Equal(#10/10/0001#, tk.Value)
Str = "#10/10/101#"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.DateLiteralToken, tk.Kind)
Assert.Equal(#10/10/0101#, tk.Value)
Str = "#10/10/0#"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.BadToken, tk.Kind)
Assert.Equal(31085, tk.GetSyntaxErrorsNoTree()(0).Code)
Assert.Equal("#10/10/0#", tk.ToFullString())
Str = " #10/10/2010 10:10:00 PM# "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.DateLiteralToken, tk.Kind)
Assert.Equal(#10/10/2010 10:10:00 PM#, tk.Value)
Str = "x = #10/10/2010##10/10/2010 10:10:00 PM# "
Dim tks = ScanAllCheckDw(Str)
Assert.Equal(#10/10/2010#, tks(2).Value)
Assert.Equal(#10/10/2010 10:10:00 PM#, tks(3).Value)
End Sub
<Fact>
Public Sub Scanner_DateLiteralTokenWithYearFirst()
Dim text = "#1984-10-12#"
Dim token = ScanOnce(text)
Assert.Equal(SyntaxKind.DateLiteralToken, token.Kind)
Assert.Equal(#10/12/1984#, token.Value)
' May use slash as separator in dates.
text = "#1984/10/12#"
token = ScanOnce(text)
Assert.Equal(SyntaxKind.DateLiteralToken, token.Kind)
Assert.Equal(#10/12/1984#, token.Value)
' Years must be four digits.
text = "#84-10-12#"
token = ScanOnce(text)
Assert.Equal(SyntaxKind.BadToken, token.Kind)
Assert.Equal(31085, token.GetSyntaxErrorsNoTree()(0).Code)
text = "#84/10/12#"
token = ScanOnce(text)
Assert.Equal(SyntaxKind.BadToken, token.Kind)
Assert.Equal(31085, token.GetSyntaxErrorsNoTree()(0).Code)
' Months may be one digit.
text = "#2010-4-12#"
token = ScanOnce(text)
Assert.Equal(SyntaxKind.DateLiteralToken, token.Kind)
Assert.Equal(#4/12/2010#, token.Value)
' Days may be one digit.
text = "#1955/11/5#"
token = ScanOnce(text)
Assert.Equal(SyntaxKind.DateLiteralToken, token.Kind)
Assert.Equal(#11/5/1955#, token.Value)
' Time only.
text = " #09:45:01# "
token = ScanOnce(text)
Assert.Equal(SyntaxKind.DateLiteralToken, token.Kind)
Assert.Equal(#1/1/1 9:45:01 AM#, token.Value)
' Date and time.
text = " # 2010-04-12 9:00 # "
token = ScanOnce(text)
Assert.Equal(SyntaxKind.DateLiteralToken, token.Kind)
Assert.Equal(#4/12/2010 9:00:00 AM#, token.Value)
text = " #2010/04/12 9:00# "
token = ScanOnce(text)
Assert.Equal(SyntaxKind.DateLiteralToken, token.Kind)
Assert.Equal(#4/12/2010 9:00:00 AM#, token.Value)
text = "x = #2010-04-12##2010-04-12 09:00:00 # "
Dim tokens = ScanAllCheckDw(text)
Assert.Equal(#4/12/2010#, tokens(2).Value)
Assert.Equal(#4/12/2010 9:00:00 AM#, tokens(3).Value)
text = "#01984/10/12#"
token = ScanOnce(text)
Assert.Equal(SyntaxKind.BadToken, token.Kind)
Assert.Equal(31085, token.GetSyntaxErrorsNoTree()(0).Code)
text = "#984/10/12#"
token = ScanOnce(text)
Assert.Equal(SyntaxKind.BadToken, token.Kind)
Assert.Equal(31085, token.GetSyntaxErrorsNoTree()(0).Code)
text = "#1984/10/#"
token = ScanOnce(text)
Assert.Equal(SyntaxKind.BadToken, token.Kind)
Assert.Equal(31085, token.GetSyntaxErrorsNoTree()(0).Code)
text = "#1984//12#"
token = ScanOnce(text)
Assert.Equal(SyntaxKind.BadToken, token.Kind)
Assert.Equal(31085, token.GetSyntaxErrorsNoTree()(0).Code)
text = "#1984/10-12#"
token = ScanOnce(text)
Assert.Equal(SyntaxKind.BadToken, token.Kind)
Assert.Equal(31085, token.GetSyntaxErrorsNoTree()(0).Code)
text = "#1984-10/12#"
token = ScanOnce(text)
Assert.Equal(SyntaxKind.BadToken, token.Kind)
Assert.Equal(31085, token.GetSyntaxErrorsNoTree()(0).Code)
End Sub
<Fact, WorkItem(529782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529782")>
Public Sub DateAndDecimalCultureIndependentTokens()
Dim SavedCultureInfo = CurrentThread.CurrentCulture
Try
CurrentThread.CurrentCulture = New System.Globalization.CultureInfo("de-DE", False)
Dim Str = "4.2"
Dim tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind)
Assert.Equal(4.2, tk.Value)
Str = "4.2F"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind)
Assert.Equal(4.2F, tk.Value)
Assert.IsType(Of Single)(tk.Value)
Str = "4.2R"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind)
Assert.Equal(4.2R, tk.Value)
Assert.IsType(Of Double)(tk.Value)
Str = "4.2D"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.DecimalLiteralToken, tk.Kind)
Assert.Equal(4.2D, tk.Value)
Assert.IsType(Of Decimal)(tk.Value)
Str = "#8/23/1970 3:35:39AM#"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.DateLiteralToken, tk.Kind)
Assert.Equal(#8/23/1970 3:35:39 AM#, tk.Value)
Finally
CurrentThread.CurrentCulture = SavedCultureInfo
End Try
End Sub
<Fact>
Public Sub Scanner_BracketedIdentToken()
Dim Str = "[Goo123]"
Dim tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IdentifierToken, tk.Kind)
Assert.True(tk.IsBracketed)
Assert.Equal("Goo123", tk.ValueText)
Assert.Equal("Goo123", tk.Value)
Assert.Equal("[Goo123]", tk.ToFullString())
Str = "[__]"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IdentifierToken, tk.Kind)
Assert.True(tk.IsBracketed)
Assert.Equal("__", tk.ValueText)
Assert.Equal("[__]", tk.ToFullString())
Str = "[Goo ]"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.BadToken, tk.Kind)
Assert.Equal(30034, tk.GetSyntaxErrorsNoTree()(0).Code)
Assert.Equal("[Goo ", tk.ToFullString())
Str = "[]"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.BadToken, tk.Kind)
Assert.Equal(30203, tk.GetSyntaxErrorsNoTree()(0).Code)
Assert.Equal("[]", tk.ToFullString())
Str = "[_]"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.BadToken, tk.Kind)
Assert.Equal(30203, tk.GetSyntaxErrorsNoTree()(0).Code)
Assert.Equal("[_]", tk.ToFullString())
End Sub
<Fact>
Public Sub Scanner_StringLiteralValueText()
Dim str = """Hello, World!"""
Dim tk = ScanOnce(str)
Assert.Equal(SyntaxKind.StringLiteralToken, tk.Kind)
Assert.Equal("Hello, World!", tk.ValueText)
Assert.Equal("""Hello, World!""", tk.ToFullString())
End Sub
<Fact>
Public Sub Scanner_MultiLineStringLiteral()
Dim text =
<text>"Hello,
World!"</text>.Value
Dim token = ScanOnce(text)
Assert.Equal(SyntaxKind.StringLiteralToken, token.Kind)
Assert.Equal("Hello," & vbLf & "World!", token.ValueText)
Assert.Equal("""Hello," & vbLf & "World!""", token.ToString())
End Sub
Private Function Repeat(str As String, num As Integer) As String
Dim arr(num - 1) As String
For i As Integer = 0 To num - 1
arr(i) = str
Next
Return String.Join("", arr)
End Function
<Fact>
Public Sub Scanner_BufferTest()
For i As Integer = 0 To 12
Dim TokenStr = New String("+"c, i)
Dim tks = ScanAllCheckDw(TokenStr)
Assert.Equal(i + 1, tks.Count)
TokenStr = Repeat(" SomeIdentifier ", i)
tks = ScanAllCheckDw(TokenStr)
Assert.Equal(i + 1, tks.Count)
' trying to place space after "someIdent" on ^2 boundary
Dim identLen = Math.Max(1, CInt(2 ^ i) - 11)
TokenStr = Repeat("X", identLen) & " someIdent " & Repeat("X", identLen + 11)
tks = ScanAllNoDwCheck(TokenStr)
Assert.Equal(4, tks.Count)
Next
For i As Integer = 100 To 5000 Step 250
Dim TokenStr = New String("+"c, i)
Dim tks = ScanAllCheckDw(TokenStr)
Assert.Equal(i + 1, tks.Count)
TokenStr = Repeat(" SomeIdentifier ", i)
tks = ScanAllCheckDw(TokenStr)
Assert.Equal(i + 1, tks.Count)
Next
End Sub
<Fact>
Public Sub Scanner_Bug866445()
Dim x = &HFF00110001020408L
Dim Str = "&HFF00110001020408L"
Dim tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
End Sub
<Fact>
Public Sub Bug869260()
Dim tk = ScanOnce(ChrW(0))
Assert.Equal(SyntaxKind.BadToken, tk.Kind)
Assert.Equal(CInt(ERRID.ERR_IllegalChar), tk.GetSyntaxErrorsNoTree(0).Code)
End Sub
<Fact>
Public Sub Bug869081()
ParseAndVerify(<![CDATA[
<Obsolete()> _
_
_
_
_
<CLSCompliant(False)> Class Class1
End Class
]]>)
End Sub
<Fact>
Public Sub Bug658441()
ParseAndVerify(<![CDATA[
#If False Then
#If False Then
# _
#End If
# _
End If
#End If
]]>)
End Sub
<WorkItem(538747, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538747")>
<Fact>
Public Sub OghamSpacemark()
ParseAndVerify(<![CDATA[
Module M
End Module
]]>)
End Sub
<WorkItem(531175, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531175")>
<Fact>
Public Sub Bug17703()
ParseAndVerify(<![CDATA[
Dim x = <
”'
]]>,
<errors>
<error id="31151" message="Element is missing an end tag." start="9" end="23"/>
<error id="31146" message="XML name expected." start="10" end="10"/>
<error id="31146" message="XML name expected." start="10" end="10"/>
<error id="30249" message="'=' expected." start="10" end="10"/>
<error id="31164" message="Expected matching closing double quote for XML attribute value." start="23" end="23"/>
<error id="31165" message="Expected beginning < for an XML tag." start="23" end="23"/>
<error id="30636" message="'>' expected." start="23" end="23"/>
</errors>)
End Sub
<WorkItem(530916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530916")>
<Fact>
Public Sub Bug17189()
ParseAndVerify(<![CDATA[
a<
-'
-
]]>,
<errors>
<error id="30689" message="Statement cannot appear outside of a method body." start="1" end="17"/>
<error id="30800" message="Method arguments must be enclosed in parentheses." start="2" end="17"/>
<error id="31151" message="Element is missing an end tag." start="2" end="17"/>
<error id="31177" message="White space cannot appear here." start="3" end="4"/>
<error id="31169" message="Character '-' (&H2D) is not allowed at the beginning of an XML name." start="4" end="5"/>
<error id="31146" message="XML name expected." start="5" end="5"/>
<error id="30249" message="'=' expected." start="5" end="5"/>
<error id="31163" message="Expected matching closing single quote for XML attribute value." start="17" end="17"/>
<error id="31165" message="Expected beginning '<' for an XML tag." start="17" end="17"/>
<error id="30636" message="'>' expected." start="17" end="17"/>
</errors>)
End Sub
<WorkItem(530682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530682")>
<Fact>
Public Sub Bug16698()
ParseAndVerify(<![CDATA[#Const x = <!--
]]>,
Diagnostic(ERRID.ERR_BadCCExpression, "<!--"))
End Sub
<WorkItem(865832, "DevDiv/Personal")>
<Fact>
Public Sub ParseSpecialKeywords()
ParseAndVerify(<![CDATA[
Module M1
Dim x As Integer
Sub Main
If True
End If
End Sub
End Module
]]>).
VerifyNoWhitespaceInKeywords()
End Sub
<WorkItem(547317, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547317")>
<Fact>
Public Sub ParseHugeNumber()
ParseAndVerify(<![CDATA[
Module M
Sub Main
Dim x = CompareDouble(-7.92281625142643E337593543950335D)
End Sub
EndModule
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'." start="1" end="9"/>
<error id="30036" message="Overflow." start="52" end="85"/>
<error id="30188" message="Declaration expected." start="100" end="109"/>
</errors>).
VerifyNoWhitespaceInKeywords()
End Sub
<WorkItem(547317, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547317")>
<Fact>
Public Sub ParseHugeNumberLabel()
ParseAndVerify(<![CDATA[
Module M
Sub Main
678901234567890123456789012345678901234567456789012345678901234567890123456789012345
End Sub
EndModule
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'." start="1" end="9"/>
<error id="30801" message="Labels that are numbers must be followed by colons." start="30" end="114"/>
<error id="30036" message="Overflow." start="30" end="114"/>
<error id="30188" message="Declaration expected." start="128" end="137"/>
</errors>).
VerifyNoWhitespaceInKeywords()
End Sub
<WorkItem(926612, "DevDiv/Personal")>
<Fact>
Public Sub ScanMultilinesTriviaWithCRLFs()
ParseAndVerify(<![CDATA[Option Compare Text
Public Class Assembly001bDll
Sub main()
Dim Asb As System.Reflection.Assembly
Asb = System.Reflection.Assembly.GetExecutingAssembly()
apcompare(Left(CurDir(), 1) & ":\School\assembly001bdll.dll", Asb.Location, "location")
End Sub
End Class]]>)
End Sub
<Fact>
Public Sub IsWhiteSpace()
Assert.False(SyntaxFacts.IsWhitespace("A"c))
Assert.True(SyntaxFacts.IsWhitespace(" "c))
Assert.True(SyntaxFacts.IsWhitespace(ChrW(9)))
Assert.False(SyntaxFacts.IsWhitespace(ChrW(0)))
Assert.False(SyntaxFacts.IsWhitespace(ChrW(128)))
Assert.False(SyntaxFacts.IsWhitespace(ChrW(129)))
Assert.False(SyntaxFacts.IsWhitespace(ChrW(127)))
Assert.True(SyntaxFacts.IsWhitespace(ChrW(160)))
Assert.True(SyntaxFacts.IsWhitespace(ChrW(12288)))
Assert.True(SyntaxFacts.IsWhitespace(ChrW(8192)))
Assert.True(SyntaxFacts.IsWhitespace(ChrW(8203)))
End Sub
<Fact>
Public Sub IsNewline()
Assert.True(SyntaxFacts.IsNewLine(ChrW(13)))
Assert.True(SyntaxFacts.IsNewLine(ChrW(10)))
Assert.True(SyntaxFacts.IsNewLine(ChrW(133)))
Assert.True(SyntaxFacts.IsNewLine(ChrW(8232)))
Assert.True(SyntaxFacts.IsNewLine(ChrW(8233)))
Assert.False(SyntaxFacts.IsNewLine(ChrW(132)))
Assert.False(SyntaxFacts.IsNewLine(ChrW(160)))
Assert.False(SyntaxFacts.IsNewLine(" "c))
Assert.Equal(String.Empty, SyntaxFacts.MakeHalfWidthIdentifier(String.Empty))
Assert.Null(SyntaxFacts.MakeHalfWidthIdentifier(Nothing))
Assert.Equal("ABC", SyntaxFacts.MakeHalfWidthIdentifier("ABC"))
Assert.Equal(ChrW(65280), SyntaxFacts.MakeHalfWidthIdentifier(ChrW(65280)))
Assert.NotEqual(ChrW(65281), SyntaxFacts.MakeHalfWidthIdentifier(ChrW(65281)))
Assert.Equal(1, SyntaxFacts.MakeHalfWidthIdentifier(ChrW(65281)).Length)
End Sub
<Fact>
Public Sub MakeHalfWidthIdentifier()
Assert.Equal(String.Empty, SyntaxFacts.MakeHalfWidthIdentifier(String.Empty))
Assert.Equal(Nothing, SyntaxFacts.MakeHalfWidthIdentifier(Nothing))
Assert.Equal("ABC", SyntaxFacts.MakeHalfWidthIdentifier("ABC"))
Assert.Equal(ChrW(65280), SyntaxFacts.MakeHalfWidthIdentifier(ChrW(65280)))
Assert.NotEqual(ChrW(65281), SyntaxFacts.MakeHalfWidthIdentifier(ChrW(65281)))
Assert.Equal(1, SyntaxFacts.MakeHalfWidthIdentifier(ChrW(65281)).Length)
End Sub
End Class
Module SyntaxDiagnosticInfoListExtensions
<Extension>
Public Function Count(list As SyntaxDiagnosticInfoList) As Integer
Dim result = 0
For Each v In list
result += 1
Next
Return result
End Function
<Extension>
Public Function First(list As SyntaxDiagnosticInfoList) As DiagnosticInfo
For Each v In list
Return v
Next
Throw New InvalidOperationException()
End Function
<Extension>
Public Function ElementAt(list As SyntaxDiagnosticInfoList, index As Integer) As DiagnosticInfo
Dim i = 0
For Each v In list
If i = index Then
Return v
End If
i += 1
Next
Throw New IndexOutOfRangeException()
End Function
End Module
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.CompilerServices
Imports System.Threading.Thread
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Syntax.InternalSyntax
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
<CLSCompliant(False)>
Public Class ScannerTests
Inherits BasicTestBase
Private Function ScanOnce(str As String, Optional startStatement As Boolean = False) As SyntaxToken
Return SyntaxFactory.ParseToken(str, startStatement:=startStatement)
End Function
Private Function ScanOnce(str As String, languageVersion As VisualBasic.LanguageVersion) As SyntaxToken
Return SyntaxFactory.ParseTokens(str, options:=New VisualBasicParseOptions(languageVersion:=languageVersion)).First()
End Function
Private Function AsString(tokens As IEnumerable(Of SyntaxToken)) As String
Dim str = String.Concat(From t In tokens Select t.ToFullString())
Return str
End Function
Private Function MakeDwString(str As String) As String
Return (From c In str Select If(c < ChrW(&H21S) OrElse c > ChrW(&H7ES), c, ChrW(AscW(c) + &HFF00US - &H20US))).ToArray
End Function
Private Function ScanAllCheckDw(str As String) As IEnumerable(Of SyntaxToken)
Dim tokens = SyntaxFactory.ParseTokens(str)
' test that token have the same text as it was.
Assert.Equal(str, AsString(tokens))
' test that we get same with doublewidth string
Dim doubleWidthStr = MakeDwString(str)
Dim doubleWidthTokens = ScanAllNoDwCheck(doubleWidthStr)
Assert.Equal(tokens.Count, doubleWidthTokens.Count)
For Each t In tokens.Zip(doubleWidthTokens, Function(t1, t2) Tuple.Create(t1, t2))
Assert.Equal(t.Item1.Kind, t.Item2.Kind)
Assert.Equal(t.Item1.Span, t.Item2.Span)
Assert.Equal(t.Item1.FullSpan, t.Item2.FullSpan)
Assert.Equal(MakeDwString(t.Item1.ToFullString()), t.Item2.ToFullString())
Next
Return tokens
End Function
Private Function ScanAllNoDwCheck(str As String) As IEnumerable(Of SyntaxToken)
Dim tokens = SyntaxFactory.ParseTokens(str)
' test that token have the same text as it was.
Assert.Equal(str, AsString(tokens))
Return tokens
End Function
<Fact>
Public Sub TestLessThanConflictMarker1()
' Needs to be followed by a space.
Dim token = SyntaxFactory.ParseTokens("<<<<<<<").First()
Assert.Equal(SyntaxKind.LessThanLessThanToken, token.Kind())
' Has to be the start of a line.
token = SyntaxFactory.ParseTokens(" <<<<<<<").First()
Assert.Equal(SyntaxKind.LessThanLessThanToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Assert.True(token.LeadingTrivia.Single().Kind() = SyntaxKind.WhitespaceTrivia)
' Has to have at least seven characters.
token = SyntaxFactory.ParseTokens("<<<<<< ").First()
Assert.Equal(SyntaxKind.LessThanLessThanToken, token.Kind())
' Start of line, seven characters, ends with space.
token = SyntaxFactory.ParseTokens("<<<<<<< ").First()
Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Dim trivia = token.LeadingTrivia.Single()
Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia)
Assert.True(trivia.ContainsDiagnostics)
Dim err = trivia.Errors().First
Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code)
End Sub
<Fact>
Public Sub TestLessThanConflictMarker2()
Dim token = SyntaxFactory.ParseTokens("{" & vbCrLf & "<<<<<<<").Skip(2).First()
Assert.Equal(SyntaxKind.LessThanLessThanToken, token.Kind())
token = SyntaxFactory.ParseTokens("{" & vbCrLf & " <<<<<<<").Skip(2).First()
Assert.Equal(SyntaxKind.LessThanLessThanToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Assert.True(token.LeadingTrivia.Single().Kind() = SyntaxKind.WhitespaceTrivia)
token = SyntaxFactory.ParseTokens("{" & vbCrLf & "<<<<<< ").Skip(2).First()
Assert.Equal(SyntaxKind.LessThanLessThanToken, token.Kind())
token = SyntaxFactory.ParseTokens("{" & vbCrLf & "<<<<<<< ").Skip(2).First()
Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Dim trivia = token.LeadingTrivia.Single()
Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia)
Assert.True(trivia.SpanStart = 3)
Assert.True(trivia.Span.Length = 8)
Assert.True(trivia.ContainsDiagnostics)
Dim err = trivia.Errors().First
Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code)
End Sub
<Fact>
Public Sub TestGreaterThanConflictMarker1()
' Needs to be followed by a space.
Dim token = SyntaxFactory.ParseTokens(">>>>>>>").First()
Assert.Equal(SyntaxKind.GreaterThanGreaterThanToken, token.Kind())
' Has to be the start of a line.
token = SyntaxFactory.ParseTokens(" >>>>>>>").First()
Assert.Equal(SyntaxKind.GreaterThanGreaterThanToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Assert.True(token.LeadingTrivia.Single().Kind() = SyntaxKind.WhitespaceTrivia)
' Has to have at least seven characters.
token = SyntaxFactory.ParseTokens(">>>>>> ").First()
Assert.Equal(SyntaxKind.GreaterThanGreaterThanToken, token.Kind())
' Start of line, seven characters, ends with space.
token = SyntaxFactory.ParseTokens(">>>>>>> ").First()
Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Dim trivia = token.LeadingTrivia.Single()
Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia)
Assert.True(trivia.ContainsDiagnostics)
Dim err = trivia.Errors().First
Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code)
End Sub
<Fact>
Public Sub TestGreaterThanConflictMarker2()
Dim token = SyntaxFactory.ParseTokens("{" & vbCrLf & ">>>>>>>").Skip(2).First()
Assert.Equal(SyntaxKind.GreaterThanGreaterThanToken, token.Kind())
token = SyntaxFactory.ParseTokens("{" & vbCrLf & " >>>>>>>").Skip(2).First()
Assert.Equal(SyntaxKind.GreaterThanGreaterThanToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Assert.True(token.LeadingTrivia.Single().Kind() = SyntaxKind.WhitespaceTrivia)
token = SyntaxFactory.ParseTokens("{" & vbCrLf & ">>>>>> ").Skip(2).First()
Assert.Equal(SyntaxKind.GreaterThanGreaterThanToken, token.Kind())
token = SyntaxFactory.ParseTokens("{" & vbCrLf & ">>>>>>> ").Skip(2).First()
Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Dim trivia = token.LeadingTrivia.Single()
Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia)
Assert.True(trivia.SpanStart = 3)
Assert.True(trivia.Span.Length = 8)
Assert.True(trivia.ContainsDiagnostics)
Dim err = trivia.Errors().First
Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code)
End Sub
<Fact>
Public Sub TestEqualsConflictMarker1()
' Has to be the start of a line.
Dim token = SyntaxFactory.ParseTokens(" =======").First()
Assert.Equal(SyntaxKind.EqualsToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Assert.True(token.LeadingTrivia.Single().Kind() = SyntaxKind.WhitespaceTrivia)
' Has to have at least seven characters.
token = SyntaxFactory.ParseTokens("====== ").First()
Assert.Equal(SyntaxKind.EqualsToken, token.Kind())
' Start of line, seven characters
token = SyntaxFactory.ParseTokens("=======").First()
Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Assert.True(token.LeadingTrivia.Single().Kind() = SyntaxKind.ConflictMarkerTrivia)
' Start of line, seven characters
token = SyntaxFactory.ParseTokens("======= trailing chars").First()
Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Dim trivia = token.LeadingTrivia.Single()
Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia)
Assert.Equal(trivia.Span.Length, 22)
Assert.True(trivia.ContainsDiagnostics)
Dim err = trivia.Errors().First
Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code)
token = SyntaxFactory.ParseTokens("======= Trailing" & vbCrLf & "disabled text").First()
Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Assert.Equal(3, token.LeadingTrivia.Count)
trivia = token.LeadingTrivia(0)
Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia)
Assert.Equal(trivia.Span.Length, 16)
Assert.True(trivia.ContainsDiagnostics)
err = trivia.Errors().First
Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code)
trivia = token.LeadingTrivia(1)
Assert.True(trivia.Kind() = SyntaxKind.EndOfLineTrivia)
Assert.Equal(trivia.Span.Start, 16)
Assert.Equal(trivia.Span.Length, 2)
trivia = token.LeadingTrivia(2)
Assert.True(trivia.Kind() = SyntaxKind.DisabledTextTrivia)
Assert.Equal(trivia.Span.Start, 18)
Assert.Equal(trivia.Span.Length, 13)
token = SyntaxFactory.ParseTokens("======= Trailing" & vbCrLf & "disabled text" & vbCrLf & ">>>> still disabled").First()
Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Assert.Equal(3, token.LeadingTrivia.Count)
trivia = token.LeadingTrivia(0)
Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia)
Assert.Equal(trivia.Span.Length, 16)
Assert.True(trivia.ContainsDiagnostics)
err = trivia.Errors().First
Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code)
trivia = token.LeadingTrivia(1)
Assert.True(trivia.Kind() = SyntaxKind.EndOfLineTrivia)
Assert.Equal(trivia.Span.Length, 2)
trivia = token.LeadingTrivia(2)
Assert.True(trivia.Kind() = SyntaxKind.DisabledTextTrivia)
Assert.Equal(trivia.Span.Length, 34)
token = SyntaxFactory.ParseTokens("======= Trailing" & vbCrLf & "disabled text" & vbCrLf & ">>>>>>> Actually the end").First()
Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Assert.Equal(token.LeadingTrivia.Count, 4)
Dim trivia1 = token.LeadingTrivia(0)
Assert.True(trivia1.Kind() = SyntaxKind.ConflictMarkerTrivia)
Assert.Equal(trivia1.Span.Length, 16)
Assert.True(trivia1.ContainsDiagnostics)
err = trivia1.Errors().First
Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code)
Dim trivia2 = token.LeadingTrivia(1)
Assert.True(trivia2.Kind() = SyntaxKind.EndOfLineTrivia)
Assert.Equal(trivia2.Span.Start, 16)
Assert.Equal(trivia2.Span.Length, 2)
Dim trivia3 = token.LeadingTrivia(2)
Assert.True(trivia3.Kind() = SyntaxKind.DisabledTextTrivia)
Assert.Equal(trivia3.Span.Start, 18)
Assert.Equal(trivia3.Span.Length, 15)
Dim trivia4 = token.LeadingTrivia(3)
Assert.True(trivia4.Kind() = SyntaxKind.ConflictMarkerTrivia)
Assert.Equal(trivia4.Span.Start, 33)
Assert.Equal(trivia4.Span.Length, 24)
Assert.True(trivia4.ContainsDiagnostics)
err = trivia4.Errors().First
Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code)
End Sub
<Fact>
Public Sub TestEqualsConflictMarker2()
' Has to be the start of a line.
Dim token = SyntaxFactory.ParseTokens("{" & vbCrLf & " =======").Skip(2).First()
Assert.Equal(SyntaxKind.EqualsToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Assert.True(token.LeadingTrivia.Single().Kind() = SyntaxKind.WhitespaceTrivia)
' Has to have at least seven characters.
token = SyntaxFactory.ParseTokens("{" & vbCrLf & "====== ").Skip(2).First()
Assert.Equal(SyntaxKind.EqualsToken, token.Kind())
' Start of line, seven characters
token = SyntaxFactory.ParseTokens("{" & vbCrLf & "=======").Skip(2).First()
Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Dim trivia = token.LeadingTrivia.Single()
Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia)
Assert.True(trivia.ContainsDiagnostics)
Dim err = trivia.Errors().First
Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code)
' Start of line, seven characters
token = SyntaxFactory.ParseTokens("{" & vbCrLf & "======= trailing chars").Skip(2).First()
Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
trivia = token.LeadingTrivia.Single()
Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia)
Assert.Equal(trivia.Span.Length, 22)
Assert.True(trivia.ContainsDiagnostics)
err = trivia.Errors().First
Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code)
token = SyntaxFactory.ParseTokens("{" & vbCrLf & "======= Trailing" & vbCrLf & "disabled text").Skip(2).First()
Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Assert.Equal(3, token.LeadingTrivia.Count)
trivia = token.LeadingTrivia(0)
Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia)
Assert.Equal(trivia.Span.Length, 16)
Assert.True(trivia.ContainsDiagnostics)
err = trivia.Errors().First
Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code)
trivia = token.LeadingTrivia(1)
Assert.True(trivia.Kind() = SyntaxKind.EndOfLineTrivia)
Assert.Equal(trivia.Span.Start, 19)
Assert.Equal(trivia.Span.Length, 2)
trivia = token.LeadingTrivia(2)
Assert.True(trivia.Kind() = SyntaxKind.DisabledTextTrivia)
Assert.Equal(trivia.Span.Start, 21)
Assert.Equal(trivia.Span.Length, 13)
token = SyntaxFactory.ParseTokens("{" & vbCrLf & "======= Trailing" & vbCrLf & "disabled text" & vbCrLf & ">>>> still disabled").Skip(2).First()
Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Assert.Equal(3, token.LeadingTrivia.Count)
trivia = token.LeadingTrivia(0)
Assert.True(trivia.Kind() = SyntaxKind.ConflictMarkerTrivia)
Assert.Equal(trivia.Span.Length, 16)
Assert.True(trivia.ContainsDiagnostics)
err = trivia.Errors().First
Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code)
trivia = token.LeadingTrivia(1)
Assert.True(trivia.Kind() = SyntaxKind.EndOfLineTrivia)
Assert.Equal(trivia.Span.Length, 2)
trivia = token.LeadingTrivia(2)
Assert.True(trivia.Kind() = SyntaxKind.DisabledTextTrivia)
Assert.Equal(trivia.Span.Length, 34)
token = SyntaxFactory.ParseTokens("{" & vbCrLf & "======= Trailing" & vbCrLf & "disabled text" & vbCrLf & ">>>>>>> Actually the end").Skip(2).First()
Assert.Equal(SyntaxKind.EndOfFileToken, token.Kind())
Assert.True(token.HasLeadingTrivia)
Assert.Equal(token.LeadingTrivia.Count, 4)
Dim trivia1 = token.LeadingTrivia(0)
Assert.True(trivia1.Kind() = SyntaxKind.ConflictMarkerTrivia)
Assert.Equal(trivia1.Span.Length, 16)
Assert.True(trivia1.ContainsDiagnostics)
err = trivia1.Errors().First
Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code)
Dim trivia2 = token.LeadingTrivia(1)
Assert.True(trivia2.Kind() = SyntaxKind.EndOfLineTrivia)
Assert.Equal(trivia2.Span.Start, 19)
Assert.Equal(trivia2.Span.Length, 2)
Dim trivia3 = token.LeadingTrivia(2)
Assert.True(trivia3.Kind() = SyntaxKind.DisabledTextTrivia)
Assert.Equal(trivia3.Span.Start, 21)
Assert.Equal(trivia3.Span.Length, 15)
Dim trivia4 = token.LeadingTrivia(3)
Assert.True(trivia4.Kind() = SyntaxKind.ConflictMarkerTrivia)
Assert.Equal(trivia4.Span.Start, 36)
Assert.Equal(trivia4.Span.Length, 24)
Assert.True(trivia4.ContainsDiagnostics)
err = trivia4.Errors().First
Assert.Equal(ERRID.ERR_Merge_conflict_marker_encountered, err.Code)
End Sub
<Fact>
Public Sub Scanner_EndOfText()
Dim tk = ScanOnce("")
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal("", tk.ToFullString())
tk = ScanOnce(" ")
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(" ", tk.ToFullString())
tk = ScanOnce(" ")
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(" ", tk.ToFullString())
tk = ScanOnce("'")
Assert.Equal(SyntaxKind.EmptyToken, tk.Kind)
Assert.Equal(SyntaxKind.CommentTrivia, tk.TrailingTrivia(0).Kind)
Assert.Equal("'", tk.ToFullString())
tk = ScanOnce("'", startStatement:=True)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(SyntaxKind.CommentTrivia, tk.LeadingTrivia(0).Kind)
Assert.Equal("'", tk.ToFullString())
tk = ScanOnce(" ' ")
Assert.Equal(SyntaxKind.EmptyToken, tk.Kind)
Assert.Equal(SyntaxKind.WhitespaceTrivia, tk.LeadingTrivia(0).Kind)
Assert.Equal(SyntaxKind.CommentTrivia, tk.TrailingTrivia(0).Kind)
Assert.Equal(" ", tk.LeadingTrivia(0).ToString())
Assert.Equal("' ", tk.TrailingTrivia(0).ToString())
Assert.Equal(" ' ", tk.ToFullString())
tk = ScanOnce(" ' ", startStatement:=True)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(SyntaxKind.WhitespaceTrivia, tk.LeadingTrivia(0).Kind)
Assert.Equal(SyntaxKind.CommentTrivia, tk.LeadingTrivia(1).Kind)
Assert.Equal(" ", tk.LeadingTrivia(0).ToString())
Assert.Equal("' ", tk.LeadingTrivia(1).ToString())
Assert.Equal(" ' ", tk.ToFullString())
End Sub
<Fact>
Public Sub Scanner_StatementTerminator()
Dim tk = ScanOnce(vbCr)
Assert.Equal(SyntaxKind.EmptyToken, tk.Kind)
Assert.Equal(vbCr, tk.ToFullString())
tk = ScanOnce(vbCr, startStatement:=True)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(vbCr, tk.ToFullString())
Dim tks = ScanAllCheckDw(vbCr)
Assert.Equal(1, tks.Count)
Assert.Equal(SyntaxKind.EndOfFileToken, tks(0).Kind)
Assert.Equal(vbCr, tks(0).ToFullString())
tks = ScanAllCheckDw(" " & vbLf)
Assert.Equal(1, tks.Count)
Assert.Equal(SyntaxKind.EndOfFileToken, tks(0).Kind)
Assert.Equal(" " & vbLf, tks(0).ToFullString())
tks = ScanAllCheckDw(" A" & vbCrLf & " ")
Assert.Equal(3, tks.Count)
Assert.Equal(SyntaxKind.IdentifierToken, tks(0).Kind)
Assert.Equal(" A" & vbCrLf, tks(0).ToFullString())
Assert.Equal(SyntaxKind.StatementTerminatorToken, tks(1).Kind)
Assert.Equal("", tks(1).ToFullString())
Assert.Equal(SyntaxKind.EndOfFileToken, tks(2).Kind)
Assert.Equal(" ", tks(2).ToFullString())
End Sub
<Fact>
Public Sub Scanner_StartStatement()
Dim tk = ScanOnce(vbCr, startStatement:=True)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(vbCr, tk.ToFullString())
tk = ScanOnce(" " & vbLf, startStatement:=True)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(" " & vbLf, tk.ToFullString())
Dim str = " " & vbCrLf & " " & vbCr & "'2 " & vbLf & " ("
tk = ScanOnce(str, startStatement:=True)
Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind)
Assert.Equal(str, tk.ToFullString())
str = "'("
tk = ScanOnce(str, startStatement:=True)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(str, tk.ToFullString())
str = "'" & vbCrLf & "("
tk = ScanOnce(str, startStatement:=False)
Assert.Equal(SyntaxKind.EmptyToken, tk.Kind)
Assert.Equal("'" & vbCrLf, tk.ToFullString())
str = "'" & vbCrLf & "("
tk = ScanOnce(str, startStatement:=True)
Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind)
Assert.Equal(str, tk.ToFullString())
str = "' " & vbCrLf & " '(" & vbCrLf & "("
tk = ScanOnce(str, startStatement:=True)
Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind)
Assert.Equal(str, tk.ToFullString())
End Sub
<Fact>
Public Sub Scanner_LineContWhenExpectingNewStatement()
Dim tk = ScanOnce("_", startStatement:=True)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal("_", tk.ToFullString())
tk = ScanOnce(" _", startStatement:=True)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(" _", tk.ToFullString())
tk = ScanOnce(" _ ", startStatement:=True)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(" _ ", tk.ToFullString())
tk = ScanOnce(" _'", startStatement:=True)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(" _'", tk.ToFullString())
Assert.Equal(3, tk.LeadingTrivia.Count)
Assert.Equal(SyntaxKind.WhitespaceTrivia, tk.LeadingTrivia(0).Kind)
Assert.Equal(SyntaxKind.LineContinuationTrivia, tk.LeadingTrivia(1).Kind)
Assert.Equal(SyntaxKind.CommentTrivia, tk.LeadingTrivia(2).Kind)
Assert.Equal(0, tk.Errors.Count)
tk = ScanOnce(" _'", LanguageVersion.VisualBasic16)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(" _'", tk.ToFullString())
Assert.Equal(3, tk.LeadingTrivia.Count)
Assert.Equal(SyntaxKind.WhitespaceTrivia, tk.LeadingTrivia(0).Kind)
Assert.Equal(SyntaxKind.LineContinuationTrivia, tk.LeadingTrivia(1).Kind)
Assert.Equal(SyntaxKind.CommentTrivia, tk.LeadingTrivia(2).Kind)
Assert.Equal(0, tk.Errors.Count)
tk = ScanOnce(" _' Comment", LanguageVersion.VisualBasic15_3)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(" _' Comment", tk.ToFullString())
Assert.Equal(3, tk.LeadingTrivia.Count)
Assert.Equal(SyntaxKind.WhitespaceTrivia, tk.LeadingTrivia(0).Kind)
Assert.False(tk.LeadingTrivia(0).ContainsDiagnostics)
Assert.Equal(SyntaxKind.LineContinuationTrivia, tk.LeadingTrivia(1).Kind)
Assert.False(tk.LeadingTrivia(1).ContainsDiagnostics)
Assert.Equal(SyntaxKind.CommentTrivia, tk.LeadingTrivia(2).Kind)
Assert.True(tk.LeadingTrivia(2).ContainsDiagnostics)
Assert.Equal(1, tk.Errors.Count)
Assert.Equal(ERRID.ERR_CommentsAfterLineContinuationNotAvailable1, tk.Errors.First().Code)
tk = ScanOnce(" _' Comment", LanguageVersion.VisualBasic16)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(" _' Comment", tk.ToFullString())
Assert.Equal(3, tk.LeadingTrivia.Count)
Assert.Equal(SyntaxKind.WhitespaceTrivia, tk.LeadingTrivia(0).Kind)
Assert.Equal(SyntaxKind.LineContinuationTrivia, tk.LeadingTrivia(1).Kind)
Assert.Equal(SyntaxKind.CommentTrivia, tk.LeadingTrivia(2).Kind)
Assert.Equal(0, tk.Errors.Count)
tk = ScanOnce(" _ ' Comment" & vbCrLf, LanguageVersion.VisualBasic16)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(" _ ' Comment" & vbCrLf, tk.ToFullString())
Assert.Equal(5, tk.LeadingTrivia.Count)
Assert.Equal(SyntaxKind.WhitespaceTrivia, tk.LeadingTrivia(0).Kind)
Assert.Equal(SyntaxKind.LineContinuationTrivia, tk.LeadingTrivia(1).Kind)
Assert.Equal(SyntaxKind.WhitespaceTrivia, tk.LeadingTrivia(2).Kind)
Assert.Equal(SyntaxKind.CommentTrivia, tk.LeadingTrivia(3).Kind)
Assert.Equal(SyntaxKind.EndOfLineTrivia, tk.LeadingTrivia(4).Kind)
Assert.Equal(0, tk.Errors.Count)
tk = ScanOnce(" _ rem", startStatement:=True)
Assert.Equal(SyntaxKind.BadToken, tk.Kind)
Assert.Equal(" _ rem", tk.ToFullString())
Assert.Equal(30999, tk.Errors.First().Code)
tk = ScanOnce(" _ abc", startStatement:=True)
Assert.Equal(SyntaxKind.BadToken, tk.Kind)
Assert.Equal(" _ ", tk.ToFullString())
Assert.Equal(30203, tk.Errors.First().Code)
Dim tks = ScanAllCheckDw(" _ rem")
Assert.Equal(SyntaxKind.BadToken, tks(0).Kind)
Assert.Equal(" _ rem", tks(0).ToFullString())
Assert.Equal(30999, tks(0).Errors.First().Code)
tk = ScanOnce("_" & vbLf, startStatement:=True)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal("_" & vbLf, tk.ToFullString())
tk = ScanOnce(" _" & vbLf, startStatement:=True)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(" _" & vbLf, tk.ToFullString())
Dim str = " _" & vbCrLf & " _" & vbCr & "'2 " & vbLf & " ("
tk = ScanOnce(str, startStatement:=True)
Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind)
Assert.Equal(str, tk.ToFullString())
str = " _" & vbCrLf & " _" & vbCrLf & "("
tk = ScanOnce(str, startStatement:=True)
Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind)
Assert.Equal(str, tk.ToFullString())
End Sub
<Fact>
Public Sub Scanner_LineContInsideStatement()
' this would be a case of )_
' valid _ would have been consumed by )
Dim tk = ScanOnce("_" & vbLf, False)
Assert.Equal(SyntaxKind.BadToken, tk.Kind)
Assert.Equal("_" + vbLf, tk.ToFullString)
Dim Str = "'_" & vbCrLf & "("
tk = ScanOnce(Str, False)
Assert.Equal(SyntaxKind.EmptyToken, tk.Kind)
Assert.Equal("'_" & vbCrLf, tk.ToFullString())
Str = " _" & vbCrLf & "("
tk = ScanOnce(Str, False)
Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind)
Assert.Equal(Str, tk.ToFullString())
' _ is invalid here, should not be consumed by (
Str = " _" & vbCrLf & "(" & "_" & vbCrLf & "'qq"
tk = ScanOnce(Str, False)
Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind)
Assert.Equal(" _" & vbCrLf & "(", tk.ToFullString())
' _ is valid here, but we should not go past the Eol
Str = " _" & vbCrLf & "(" & " _" & vbCrLf & "'qq"
tk = ScanOnce(Str, False)
Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind)
Assert.Equal(" _" & vbCrLf & "(" & " _" & vbCrLf, tk.ToFullString())
End Sub
<Fact>
Public Sub Scanner_RemComment()
Dim str = " " & vbCrLf & " " & vbCr & "REM " & vbLf & " ("
Dim tk = ScanOnce(str, True)
Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind)
Assert.Equal(str, tk.ToFullString())
str = "A REM Hello "
tk = ScanOnce(str, True)
Assert.Equal(SyntaxKind.IdentifierToken, tk.Kind)
Assert.Equal(str, tk.ToFullString())
str = "A A REM Hello " & vbCrLf & "A Rem Hello "
Dim tks = ScanAllCheckDw(str)
Assert.Equal(SyntaxKind.IdentifierToken, tks(0).Kind)
Assert.Equal("A ", tks(0).ToFullString)
Assert.Equal(SyntaxKind.IdentifierToken, tks(1).Kind)
Assert.NotEqual("A ", tks(1).ToFullString)
Assert.Equal(SyntaxKind.StatementTerminatorToken, tks(2).Kind)
Assert.Equal(SyntaxKind.IdentifierToken, tks(3).Kind)
Assert.NotEqual("A ", tks(1).ToFullString)
Assert.Equal(SyntaxKind.EndOfFileToken, tks(4).Kind)
Assert.Equal(5, tks.Count)
REM(
str = "REM("
tk = ScanOnce(str, True)
Assert.Equal(SyntaxKind.EndOfFileToken, tk.Kind)
Assert.Equal(str, tk.ToFullString())
str = "ReM" & vbCrLf & "("
tk = ScanOnce(str, False)
Assert.Equal(SyntaxKind.EmptyToken, tk.Kind)
Assert.Equal("ReM" & vbCrLf, tk.ToFullString())
str = "rEM" & vbCrLf & "("
tk = ScanOnce(str, True)
Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind)
Assert.Equal(str, tk.ToFullString())
str = "rem " & vbCrLf & " REM(" & vbCrLf & "("
tk = ScanOnce(str, True)
Assert.Equal(SyntaxKind.OpenParenToken, tk.Kind)
Assert.Equal(str, tk.ToFullString())
End Sub
''' <summary>
''' EmptyToken is generated by the Scanner in a single-line
''' If or lambda with an empty statement to avoid generating
''' a statement terminator with leading or trailing trivia.
''' </summary>
<Fact>
Public Sub Scanner_EmptyToken()
' No EmptyToken required because no trivia before EOF.
ParseTokensAndVerify("If True Then Else Return :",
SyntaxKind.IfKeyword,
SyntaxKind.TrueKeyword,
SyntaxKind.ThenKeyword,
SyntaxKind.ElseKeyword,
SyntaxKind.ReturnKeyword,
SyntaxKind.ColonToken,
SyntaxKind.EndOfFileToken)
' No EmptyToken required because no trailing trivia before EOF.
' (The space after the colon is leading trivia on EOF.)
ParseTokensAndVerify("If True Then Else : ",
SyntaxKind.IfKeyword,
SyntaxKind.TrueKeyword,
SyntaxKind.ThenKeyword,
SyntaxKind.ElseKeyword,
SyntaxKind.ColonToken,
SyntaxKind.EndOfFileToken)
' EmptyToken required because comment is trailing
' trivia between the colon and EOL.
ParseTokensAndVerify(<![CDATA[If True Then Else :'Comment
Return]]>.Value,
SyntaxKind.IfKeyword,
SyntaxKind.TrueKeyword,
SyntaxKind.ThenKeyword,
SyntaxKind.ElseKeyword,
SyntaxKind.ColonToken,
SyntaxKind.EmptyToken,
SyntaxKind.StatementTerminatorToken,
SyntaxKind.ReturnKeyword,
SyntaxKind.EndOfFileToken)
' EmptyToken required because comment is trailing
' trivia between the colon and EOF.
ParseTokensAndVerify("Sub() If True Then Return : REM",
SyntaxKind.SubKeyword,
SyntaxKind.OpenParenToken,
SyntaxKind.CloseParenToken,
SyntaxKind.IfKeyword,
SyntaxKind.TrueKeyword,
SyntaxKind.ThenKeyword,
SyntaxKind.ReturnKeyword,
SyntaxKind.ColonToken,
SyntaxKind.EmptyToken,
SyntaxKind.EndOfFileToken)
' No EmptyToken required because colon, space, comment
' and EOL are all treated as multi-line leading trivia on EndKeyword.
ParseTokensAndVerify(<![CDATA[If True Then
: 'Comment
End If]]>.Value,
SyntaxKind.IfKeyword,
SyntaxKind.TrueKeyword,
SyntaxKind.ThenKeyword,
SyntaxKind.StatementTerminatorToken,
SyntaxKind.EndKeyword,
SyntaxKind.IfKeyword,
SyntaxKind.EndOfFileToken)
End Sub
Private Sub ParseTokensAndVerify(str As String, ParamArray kinds As SyntaxKind())
Dim tokens = SyntaxFactory.ParseTokens(str).ToArray()
Dim result = String.Join("", tokens.Select(Function(t) t.ToFullString()))
Assert.Equal(str, result)
Assert.Equal(tokens.Length, kinds.Length)
For i = 0 To tokens.Length - 1
Assert.Equal(tokens(i).Kind, kinds(i))
Next
End Sub
<Fact>
Public Sub Scanner_DimKeyword()
Dim Str = " " & vbCrLf & " " & vbCr & "DIM " & vbLf & " ("
Dim tk = ScanOnce(Str, True)
Assert.Equal(SyntaxKind.DimKeyword, tk.Kind)
Assert.Equal(" " & vbCrLf & " " & vbCr & "DIM " + vbLf, tk.ToFullString)
Str = "Dim("
tk = ScanOnce(Str, True)
Assert.Equal(SyntaxKind.DimKeyword, tk.Kind)
Assert.Equal("Dim", tk.ToFullString())
Str = "DiM" & vbCrLf & "("
tk = ScanOnce(Str, False)
Assert.Equal(SyntaxKind.DimKeyword, tk.Kind)
Assert.Equal("DiM" + vbCrLf, tk.ToFullString)
Str = "dIM" & " _" & vbCrLf & "("
tk = ScanOnce(Str, True)
Assert.Equal(SyntaxKind.DimKeyword, tk.Kind)
Assert.Equal("dIM" & " _" & vbCrLf, tk.ToFullString())
Str = "dim " & vbCrLf & " DIMM" & vbCrLf & "("
Dim tks = ScanAllNoDwCheck(Str)
Assert.Equal(SyntaxKind.DimKeyword, tks(0).Kind)
Assert.Equal(SyntaxKind.StatementTerminatorToken, tks(1).Kind)
Assert.Equal(SyntaxKind.IdentifierToken, tks(2).Kind)
Assert.Equal(SyntaxKind.StatementTerminatorToken, tks(3).Kind)
Assert.Equal(SyntaxKind.OpenParenToken, tks(4).Kind)
End Sub
<WorkItem(15925, "DevDiv_Projects/Roslyn")>
<Fact>
Public Sub StaticKeyword()
Dim Str = " " & vbCrLf & " " & vbCr & "STATIC " & vbLf & " ("
Dim tk = ScanOnce(Str, True)
Assert.Equal(SyntaxKind.StaticKeyword, tk.Kind)
Assert.Equal(" " & vbCrLf & " " & vbCr & "STATIC " & vbLf, tk.ToFullString())
Str = "Static("
tk = ScanOnce(Str, True)
Assert.Equal(SyntaxKind.StaticKeyword, tk.Kind)
Assert.Equal("Static", tk.ToFullString())
Str = "StatiC" & vbCrLf & "("
tk = ScanOnce(Str, False)
Assert.Equal(SyntaxKind.StaticKeyword, tk.Kind)
Assert.Equal("StatiC" & vbCrLf, tk.ToFullString())
Str = "sTATIC" & " _" & vbCrLf & "("
tk = ScanOnce(Str, True)
Assert.Equal(SyntaxKind.StaticKeyword, tk.Kind)
Assert.Equal("sTATIC" & " _" & vbCrLf, tk.ToFullString())
Str = "static " & vbCrLf & " STATICC" & vbCrLf & "("
Dim tks = ScanAllNoDwCheck(Str)
Assert.Equal(SyntaxKind.StaticKeyword, tks(0).Kind)
Assert.Equal(SyntaxKind.StatementTerminatorToken, tks(1).Kind)
Assert.Equal(SyntaxKind.IdentifierToken, tks(2).Kind)
Assert.Equal(SyntaxKind.StatementTerminatorToken, tks(3).Kind)
Assert.Equal(SyntaxKind.OpenParenToken, tks(4).Kind)
End Sub
<Fact>
Public Sub Scanner_FrequentKeywords()
Dim Str = "End "
Dim tk = ScanOnce(Str, True)
Assert.Equal(SyntaxKind.EndKeyword, tk.Kind)
Assert.Equal(3, tk.Span.Length)
Assert.Equal(4, tk.FullSpan.Length)
Assert.Equal("End ", tk.ToFullString())
Str = "As "
tk = ScanOnce(Str, False)
Assert.Equal(SyntaxKind.AsKeyword, tk.Kind)
Assert.Equal(2, tk.Span.Length)
Assert.Equal(3, tk.FullSpan.Length)
Assert.Equal("As ", tk.ToFullString())
Str = "If "
tk = ScanOnce(Str, False)
Assert.Equal(SyntaxKind.IfKeyword, tk.Kind)
Assert.Equal(2, tk.Span.Length)
Assert.Equal(3, tk.FullSpan.Length)
Assert.Equal("If ", tk.ToFullString())
End Sub
<Fact>
Public Sub Scanner_PlusToken()
Dim Str = "+"
Dim tk = ScanOnce(Str, True)
Assert.Equal(SyntaxKind.PlusToken, tk.Kind)
Assert.Equal(Str, tk.ToFullString())
Str = "+ ="
tk = ScanOnce(Str, True)
Assert.Equal(SyntaxKind.PlusEqualsToken, tk.Kind)
Assert.Equal(Str, tk.ToFullString())
End Sub
<Fact>
Public Sub Scanner_PowerToken()
Dim Str = "^"
Dim tk = ScanOnce(Str, False)
Assert.Equal(SyntaxKind.CaretToken, tk.Kind)
Assert.Equal(Str, tk.ToFullString())
Str = "^ =^"
Dim tks = ScanAllCheckDw(Str)
Assert.Equal(SyntaxKind.CaretEqualsToken, tks(0).Kind)
Assert.Equal(SyntaxKind.CaretToken, tks(1).Kind)
End Sub
<Fact>
Public Sub Scanner_GreaterThanToken()
Dim Str = "> "
Dim tk = ScanOnce(Str, False)
Assert.Equal(SyntaxKind.GreaterThanToken, tk.Kind)
Assert.Equal(Str, tk.ToFullString())
Str = " >= 'qqqq"
tk = ScanOnce(Str, True)
Assert.Equal(SyntaxKind.GreaterThanEqualsToken, tk.Kind)
Assert.Equal(Str, tk.ToFullString())
Str = " > ="
tk = ScanOnce(Str, True)
Assert.Equal(SyntaxKind.GreaterThanEqualsToken, tk.Kind)
Assert.Equal(Str, tk.ToFullString())
'Str = " >" & vbCrLf & "="
'tk = ScanOnce(Str, True)
'Assert.Equal(NodeKind.GreaterToken, tk.Kind)
'Assert.Equal(" >" & vbCrLf, tk.ToFullString())
'Str = ">" & " _" & vbCrLf & "="
'tk = ScanOnce(Str, True)
'Assert.Equal(NodeKind.GreaterToken, tk.Kind)
'Assert.Equal(">" & " _" & vbCrLf, tk.ToFullString())
End Sub
<Fact>
Public Sub Scanner_LessThanToken()
Dim Str = "> <"
Dim tks = ScanAllCheckDw(Str)
Assert.Equal(SyntaxKind.GreaterThanToken, tks(0).Kind)
Assert.Equal(SyntaxKind.LessThanToken, tks(1).Kind)
Str = "<<<<%"
tks = ScanAllCheckDw(Str)
Assert.Equal(SyntaxKind.LessThanLessThanToken, tks(0).Kind)
Assert.Equal(SyntaxKind.LessThanToken, tks(1).Kind)
Assert.Equal(SyntaxKind.LessThanToken, tks(2).Kind)
Assert.Equal(SyntaxKind.BadToken, tks(3).Kind)
Assert.Equal(SyntaxKind.EndOfFileToken, tks(4).Kind)
Str = " < << <% "
tks = ScanAllCheckDw(Str)
Assert.Equal(SyntaxKind.LessThanLessThanToken, tks(0).Kind)
Assert.Equal(SyntaxKind.LessThanToken, tks(1).Kind)
Assert.Equal(SyntaxKind.LessThanToken, tks(2).Kind)
Assert.Equal(SyntaxKind.BadToken, tks(3).Kind)
Assert.Equal(SyntaxKind.EndOfFileToken, tks(4).Kind)
End Sub
<Fact>
Public Sub Scanner_ShiftLeftToken()
Dim Str = "<<<<="
Dim tks = ScanAllCheckDw(Str)
Assert.Equal(SyntaxKind.LessThanLessThanToken, tks(0).Kind)
Assert.Equal(SyntaxKind.LessThanLessThanEqualsToken, tks(1).Kind)
Assert.Equal(SyntaxKind.EndOfFileToken, tks(2).Kind)
'Str = "<" & vbLf & " < < = "
'tks = ScanAllCheckDw(Str)
'Assert.Equal(NodeKind.LessToken, tks(0).Kind)
'Assert.Equal(NodeKind.LeftShiftEqualsToken, tks(1).Kind)
'Assert.Equal(NodeKind.EndOfTextToken, tks(2).Kind)
'' left shift does not allow implicit line continuation
'Str = "<<" & vbLf & "<<="
'tks = ScanAllCheckDw(Str)
'Assert.Equal(NodeKind.LeftShiftToken, tks(0).Kind)
'Assert.Equal(NodeKind.StatementTerminatorToken, tks(1).Kind)
'Assert.Equal(NodeKind.LeftShiftEqualsToken, tks(2).Kind)
'Assert.Equal(NodeKind.EndOfTextToken, tks(3).Kind)
End Sub
<Fact>
Public Sub Scanner_NotEqualsToken()
Dim Str = "<>"
Dim tks = ScanAllCheckDw(Str)
Assert.Equal(SyntaxKind.LessThanGreaterThanToken, tks(0).Kind)
Assert.Equal(SyntaxKind.EndOfFileToken, tks(1).Kind)
Str = "<>="
tks = ScanAllCheckDw(Str)
Assert.Equal(SyntaxKind.LessThanGreaterThanToken, tks(0).Kind)
Assert.Equal(SyntaxKind.EqualsToken, tks(1).Kind)
Assert.Equal(SyntaxKind.EndOfFileToken, tks(2).Kind)
'Str = "<" & vbLf & " > "
'tks = ScanAllCheckDw(Str)
'Assert.Equal(NodeKind.LessToken, tks(0).Kind)
'Assert.Equal(NodeKind.GreaterToken, tks(1).Kind)
'Assert.Equal(NodeKind.EndOfTextToken, tks(2).Kind)
'' left shift does not allow implicit line continuation
'Str = "< > <" & " _" & vbLf & ">"
'tks = ScanAllCheckDw(Str)
'Assert.Equal(NodeKind.NotEqualToken, tks(0).Kind)
'Assert.Equal(NodeKind.LessToken, tks(1).Kind)
'Assert.Equal(NodeKind.GreaterToken, tks(2).Kind)
'Assert.Equal(NodeKind.EndOfTextToken, tks(3).Kind)
End Sub
Private Sub CheckCharTkValue(tk As SyntaxToken, expected As Char)
Dim val = DirectCast(tk.Value, Char)
Assert.Equal(expected, val)
End Sub
<Fact>
Public Sub Scanner_CharLiteralToken()
Dim Str = <text>"Q"c</text>.Value
Dim tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.CharacterLiteralToken, tk.Kind)
Assert.Equal(Str, tk.ToFullString())
CheckCharTkValue(tk, "Q"c)
Str = <text>""""c</text>.Value
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.CharacterLiteralToken, tk.Kind)
Assert.Equal(Str, tk.ToFullString())
CheckCharTkValue(tk, """"c)
Str = <text>""c</text>.Value
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.BadToken, tk.Kind)
Assert.Equal(30004, tk.GetSyntaxErrorsNoTree()(0).Code)
Assert.Equal(Str, tk.ToFullString())
Str = <text>"""c</text>.Value
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.StringLiteralToken, tk.Kind)
Assert.Equal(30648, tk.GetSyntaxErrorsNoTree()(0).Code)
Assert.Equal(Str, tk.ToFullString())
CheckStrTkValue(tk, """c")
Str = <text>"QQ"c</text>.Value
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.BadToken, tk.Kind)
Assert.Equal(30004, tk.GetSyntaxErrorsNoTree()(0).Code)
Assert.Equal(Str, tk.ToFullString())
Str = <text>"Q"c "Q"c"Q"c "Q"c _
"Q"c
""""c</text>.Value
Dim doubleWidthStr = MakeDwString(Str)
Dim tks = ScanAllNoDwCheck(doubleWidthStr)
Assert.Equal(10, tks.Count)
Assert.Equal(True, tks.Any(Function(t) t.ContainsDiagnostics))
End Sub
Private Sub CheckStrTkValue(tk As SyntaxToken, expected As String)
Dim str = DirectCast(tk.Value, String)
Assert.Equal(expected, str)
End Sub
<Fact>
Public Sub Scanner_StringLiteralToken()
Dim Str = <text>""</text>.Value
Dim tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.StringLiteralToken, tk.Kind)
Assert.Equal(Str, tk.ToFullString())
CheckStrTkValue(tk, "")
Str = <text>"Q"</text>.Value
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.StringLiteralToken, tk.Kind)
Assert.Equal(Str, tk.ToFullString())
CheckStrTkValue(tk, "Q")
Str = <text>""""</text>.Value
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.StringLiteralToken, tk.Kind)
Assert.Equal(Str, tk.ToFullString())
CheckStrTkValue(tk, """")
Str = <text>""""""""</text>.Value
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.StringLiteralToken, tk.Kind)
Assert.Equal(Str, tk.ToFullString())
CheckStrTkValue(tk, """""""")
Str = <text>"""" """"</text>.Value
Dim tks = ScanAllCheckDw(Str)
Assert.Equal(SyntaxKind.StringLiteralToken, tks(0).Kind)
Assert.Equal(SyntaxKind.StringLiteralToken, tks(1).Kind)
Str = <text>"AA"
"BB"</text>.Value
tks = ScanAllCheckDw(Str)
Assert.Equal(SyntaxKind.StringLiteralToken, tks(0).Kind)
Assert.Equal(SyntaxKind.StatementTerminatorToken, tks(1).Kind)
Assert.Equal(SyntaxKind.StringLiteralToken, tks(2).Kind)
End Sub
<Fact>
Public Sub Scanner_IntegerLiteralToken()
Dim Str = "42"
Dim tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(LiteralBase.Decimal, tk.GetBase())
Assert.Equal(42, tk.Value)
Str = " 42 "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(LiteralBase.Decimal, tk.GetBase())
Assert.Equal(42, tk.Value)
Assert.Equal(" 42 ", tk.ToFullString())
Str = " 4_2 "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(LiteralBase.Decimal, tk.GetBase())
Assert.Equal(42, tk.Value)
Assert.Equal(" 4_2 ", tk.ToFullString())
Assert.Equal(0, tk.Errors().Count)
Str = " &H42L "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(LiteralBase.Hexadecimal, tk.GetBase())
Assert.Equal(&H42L, tk.Value)
Assert.Equal(" &H42L ", tk.ToFullString())
Str = " &H4_2L "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(LiteralBase.Hexadecimal, tk.GetBase())
Assert.Equal(&H42L, tk.Value)
Assert.Equal(" &H4_2L ", tk.ToFullString())
Str = " &H_1 "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(LiteralBase.Hexadecimal, tk.GetBase())
Assert.Equal(&H1, tk.Value)
Assert.Equal(" &H_1 ", tk.ToFullString())
Str = " &B_1 "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(LiteralBase.Binary, tk.GetBase())
Assert.Equal(&B1, tk.Value)
Assert.Equal(" &B_1 ", tk.ToFullString())
Str = " &O_1 "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(LiteralBase.Octal, tk.GetBase())
Assert.Equal(&O1, tk.Value)
Assert.Equal(" &O_1 ", tk.ToFullString())
Str = " &H__1_1L "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(LiteralBase.Hexadecimal, tk.GetBase())
Assert.Equal(&H11L, tk.Value)
Assert.Equal(" &H__1_1L ", tk.ToFullString())
Str = " &B__1_1L "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(LiteralBase.Binary, tk.GetBase())
Assert.Equal(&B11L, tk.Value)
Assert.Equal(" &B__1_1L ", tk.ToFullString())
Str = " &O__1_1L "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(LiteralBase.Octal, tk.GetBase())
Assert.Equal(&O11L, tk.Value)
Assert.Equal(" &O__1_1L ", tk.ToFullString())
Str = " &H42L &H42& "
Dim tks = ScanAllCheckDw(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tks(0).Kind)
Assert.Equal(LiteralBase.Hexadecimal, tks(1).GetBase())
Assert.Equal(&H42L, tks(1).Value)
Assert.Equal(TypeCharacter.Long, tks(1).GetTypeCharacter())
Str = " &B1010L "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(LiteralBase.Binary, tk.GetBase())
Assert.Equal(&HAL, tk.Value)
Assert.Equal(" &B1010L ", tk.ToFullString())
Assert.Equal(0, tk.Errors().Count)
Str = " &B1_0_1_0L "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(LiteralBase.Binary, tk.GetBase())
Assert.Equal(&HAL, tk.Value)
Assert.Equal(" &B1_0_1_0L ", tk.ToFullString())
Assert.Equal(0, tk.Errors().Count)
End Sub
<Fact>
Public Sub Scanner_FloatingLiteralToken()
Dim Str = "4.2"
Dim tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind)
Assert.Equal(4.2, tk.Value)
Str = " 0.42 "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind)
Assert.Equal(0.42, tk.Value)
Assert.IsType(Of Double)(tk.Value)
Assert.Equal(" 0.42 ", tk.ToFullString())
Str = " 0_0.4_2 "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind)
Assert.Equal(0.42, tk.Value)
Assert.IsType(Of Double)(tk.Value)
Assert.Equal(" 0_0.4_2 ", tk.ToFullString())
Str = " 0.42# "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind)
Assert.Equal(0.42, tk.Value)
Assert.IsType(Of Double)(tk.Value)
Assert.Equal(" 0.42# ", tk.ToFullString())
Str = " 0.42R "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind)
Assert.Equal(0.42, tk.Value)
Assert.IsType(Of Double)(tk.Value)
Assert.Equal(" 0.42R ", tk.ToFullString())
Str = " 0.42! "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind)
Assert.Equal(0.42!, tk.Value)
Assert.IsType(Of Single)(tk.Value)
Assert.Equal(" 0.42! ", tk.ToFullString())
Str = " 0.42F "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind)
Assert.Equal(0.42F, tk.Value)
Assert.IsType(Of Single)(tk.Value)
Assert.Equal(" 0.42F ", tk.ToFullString())
Str = " .42 42# "
Dim tks = ScanAllCheckDw(Str)
Assert.Equal(SyntaxKind.FloatingLiteralToken, tks(1).Kind)
Assert.Equal(42.0#, tks(1).Value)
Assert.Equal(0.42, tks(0).Value)
Assert.IsType(Of Double)(tks(1).Value)
Assert.Equal(TypeCharacter.Double, tks(1).GetTypeCharacter())
End Sub
<Fact>
Public Sub Scanner_DecimalLiteralToken()
Dim Str = "4.2D"
Dim tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.DecimalLiteralToken, tk.Kind)
Assert.Equal(TypeCharacter.DecimalLiteral, tk.GetTypeCharacter())
Assert.Equal(4.2D, tk.Value)
Str = " 0.42@ "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.DecimalLiteralToken, tk.Kind)
Assert.Equal(0.42@, tk.Value)
Assert.Equal(" 0.42@ ", tk.ToFullString())
Str = " .42D 4242424242424242424242424242@ "
Dim tks = ScanAllCheckDw(Str)
Assert.Equal(SyntaxKind.DecimalLiteralToken, tks(1).Kind)
Assert.Equal(4242424242424242424242424242D, tks(1).Value)
Assert.Equal(0.42D, tks(0).Value)
Assert.Equal(TypeCharacter.Decimal, tks(1).GetTypeCharacter())
End Sub
<WorkItem(538543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538543")>
<Fact>
Public Sub Scanner_DecimalLiteralExpToken()
Dim Str = "1E1D"
Dim tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.DecimalLiteralToken, tk.Kind)
Assert.Equal(TypeCharacter.DecimalLiteral, tk.GetTypeCharacter())
Assert.Equal(10D, tk.Value)
End Sub
<Fact>
Public Sub Scanner_Overflow()
Dim Str = "2147483647I"
Dim tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(2147483647I, CInt(tk.Value))
Str = "2147483648I"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(30036, tk.GetSyntaxErrorsNoTree()(0).Code)
Assert.Equal(0, CInt(tk.Value))
Str = "&H7FFFFFFFI"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(&H7FFFFFFFI, CInt(tk.Value))
Str = "&HFFFFFFFFI"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(&HFFFFFFFFI, tk.Value)
Str = "&HFFFFFFFFS"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(30036, tk.GetSyntaxErrorsNoTree()(0).Code)
Assert.Equal(0, CInt(tk.Value))
Str = "&B111111111111111111111111111111111I"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(30036, tk.GetSyntaxErrorsNoTree()(0).Code)
Assert.Equal(0, CInt(tk.Value))
Str = "&B11111111111111111111111111111111UI"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(&HFFFFFFFFUI, CUInt(tk.Value))
Str = "&B1111111111111111111111111111111I"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(&H7FFFFFFFI, CInt(tk.Value))
Str = "1.7976931348623157E+308d"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.DecimalLiteralToken, tk.Kind)
Assert.Equal(30036, tk.GetSyntaxErrorsNoTree()(0).Code)
Assert.Equal(0D, tk.Value)
Str = "1.797693134862315456489789797987987897897987987E+308F"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind)
Assert.Equal(30036, tk.GetSyntaxErrorsNoTree()(0).Code)
Assert.Equal(0.0F, tk.Value)
End Sub
<Fact>
Public Sub Scanner_UnderscoreWrongLocation()
Dim Str = "_1"
Dim tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IdentifierToken, tk.Kind)
Assert.Equal(0, tk.GetSyntaxErrorsNoTree().Count())
Str = "1_"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(30035, tk.GetSyntaxErrorsNoTree()(0).Code)
Assert.Equal(0, CInt(tk.Value))
Str = "&H1_"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Assert.Equal(30035, tk.GetSyntaxErrorsNoTree()(0).Code)
Assert.Equal(0, CInt(tk.Value))
Str = "1_.1"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind)
Assert.Equal(30035, tk.GetSyntaxErrorsNoTree()(0).Code)
Assert.Equal(0, CInt(tk.Value))
Str = "1.1_"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind)
Assert.Equal(30035, tk.GetSyntaxErrorsNoTree()(0).Code)
Assert.Equal(0, CInt(tk.Value))
Str = "&H_"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Dim errors = tk.Errors()
Assert.Equal(1, errors.Count)
Assert.Equal(30035, errors.First().Code)
Assert.Equal(0, CInt(tk.Value))
Str = "&H_2_"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
errors = tk.Errors()
Assert.Equal(1, errors.Count)
Assert.Equal(30035, errors.First().Code)
Assert.Equal(0, CInt(tk.Value))
End Sub
<Fact>
Public Sub Scanner_UnderscoreFeatureFlag()
Dim Str = "&H_1"
Dim tk = ScanOnce(Str, LanguageVersion.VisualBasic14)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
Dim errors = tk.Errors()
Assert.Equal(1, errors.Count)
Assert.Equal(36716, errors.First().Code)
Assert.Equal(1, CInt(tk.Value))
Str = "&H_123_456_789_ABC_DEF_123"
tk = ScanOnce(Str, LanguageVersion.VisualBasic14)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
errors = tk.Errors()
Assert.Equal(2, errors.Count)
Assert.Equal(30036, errors.ElementAt(0).Code)
Assert.Equal(36716, errors.ElementAt(1).Code)
Assert.Equal(0, CInt(tk.Value))
End Sub
<Fact>
Public Sub Scanner_DateLiteralToken()
Dim Str = "#10/10/2010#"
Dim tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.DateLiteralToken, tk.Kind)
Assert.Equal(#10/10/2010#, tk.Value)
Str = "#10/10/1#"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.DateLiteralToken, tk.Kind)
Assert.Equal(#10/10/0001#, tk.Value)
Str = "#10/10/101#"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.DateLiteralToken, tk.Kind)
Assert.Equal(#10/10/0101#, tk.Value)
Str = "#10/10/0#"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.BadToken, tk.Kind)
Assert.Equal(31085, tk.GetSyntaxErrorsNoTree()(0).Code)
Assert.Equal("#10/10/0#", tk.ToFullString())
Str = " #10/10/2010 10:10:00 PM# "
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.DateLiteralToken, tk.Kind)
Assert.Equal(#10/10/2010 10:10:00 PM#, tk.Value)
Str = "x = #10/10/2010##10/10/2010 10:10:00 PM# "
Dim tks = ScanAllCheckDw(Str)
Assert.Equal(#10/10/2010#, tks(2).Value)
Assert.Equal(#10/10/2010 10:10:00 PM#, tks(3).Value)
End Sub
<Fact>
Public Sub Scanner_DateLiteralTokenWithYearFirst()
Dim text = "#1984-10-12#"
Dim token = ScanOnce(text)
Assert.Equal(SyntaxKind.DateLiteralToken, token.Kind)
Assert.Equal(#10/12/1984#, token.Value)
' May use slash as separator in dates.
text = "#1984/10/12#"
token = ScanOnce(text)
Assert.Equal(SyntaxKind.DateLiteralToken, token.Kind)
Assert.Equal(#10/12/1984#, token.Value)
' Years must be four digits.
text = "#84-10-12#"
token = ScanOnce(text)
Assert.Equal(SyntaxKind.BadToken, token.Kind)
Assert.Equal(31085, token.GetSyntaxErrorsNoTree()(0).Code)
text = "#84/10/12#"
token = ScanOnce(text)
Assert.Equal(SyntaxKind.BadToken, token.Kind)
Assert.Equal(31085, token.GetSyntaxErrorsNoTree()(0).Code)
' Months may be one digit.
text = "#2010-4-12#"
token = ScanOnce(text)
Assert.Equal(SyntaxKind.DateLiteralToken, token.Kind)
Assert.Equal(#4/12/2010#, token.Value)
' Days may be one digit.
text = "#1955/11/5#"
token = ScanOnce(text)
Assert.Equal(SyntaxKind.DateLiteralToken, token.Kind)
Assert.Equal(#11/5/1955#, token.Value)
' Time only.
text = " #09:45:01# "
token = ScanOnce(text)
Assert.Equal(SyntaxKind.DateLiteralToken, token.Kind)
Assert.Equal(#1/1/1 9:45:01 AM#, token.Value)
' Date and time.
text = " # 2010-04-12 9:00 # "
token = ScanOnce(text)
Assert.Equal(SyntaxKind.DateLiteralToken, token.Kind)
Assert.Equal(#4/12/2010 9:00:00 AM#, token.Value)
text = " #2010/04/12 9:00# "
token = ScanOnce(text)
Assert.Equal(SyntaxKind.DateLiteralToken, token.Kind)
Assert.Equal(#4/12/2010 9:00:00 AM#, token.Value)
text = "x = #2010-04-12##2010-04-12 09:00:00 # "
Dim tokens = ScanAllCheckDw(text)
Assert.Equal(#4/12/2010#, tokens(2).Value)
Assert.Equal(#4/12/2010 9:00:00 AM#, tokens(3).Value)
text = "#01984/10/12#"
token = ScanOnce(text)
Assert.Equal(SyntaxKind.BadToken, token.Kind)
Assert.Equal(31085, token.GetSyntaxErrorsNoTree()(0).Code)
text = "#984/10/12#"
token = ScanOnce(text)
Assert.Equal(SyntaxKind.BadToken, token.Kind)
Assert.Equal(31085, token.GetSyntaxErrorsNoTree()(0).Code)
text = "#1984/10/#"
token = ScanOnce(text)
Assert.Equal(SyntaxKind.BadToken, token.Kind)
Assert.Equal(31085, token.GetSyntaxErrorsNoTree()(0).Code)
text = "#1984//12#"
token = ScanOnce(text)
Assert.Equal(SyntaxKind.BadToken, token.Kind)
Assert.Equal(31085, token.GetSyntaxErrorsNoTree()(0).Code)
text = "#1984/10-12#"
token = ScanOnce(text)
Assert.Equal(SyntaxKind.BadToken, token.Kind)
Assert.Equal(31085, token.GetSyntaxErrorsNoTree()(0).Code)
text = "#1984-10/12#"
token = ScanOnce(text)
Assert.Equal(SyntaxKind.BadToken, token.Kind)
Assert.Equal(31085, token.GetSyntaxErrorsNoTree()(0).Code)
End Sub
<Fact, WorkItem(529782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529782")>
Public Sub DateAndDecimalCultureIndependentTokens()
Dim SavedCultureInfo = CurrentThread.CurrentCulture
Try
CurrentThread.CurrentCulture = New System.Globalization.CultureInfo("de-DE", False)
Dim Str = "4.2"
Dim tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind)
Assert.Equal(4.2, tk.Value)
Str = "4.2F"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind)
Assert.Equal(4.2F, tk.Value)
Assert.IsType(Of Single)(tk.Value)
Str = "4.2R"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.FloatingLiteralToken, tk.Kind)
Assert.Equal(4.2R, tk.Value)
Assert.IsType(Of Double)(tk.Value)
Str = "4.2D"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.DecimalLiteralToken, tk.Kind)
Assert.Equal(4.2D, tk.Value)
Assert.IsType(Of Decimal)(tk.Value)
Str = "#8/23/1970 3:35:39AM#"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.DateLiteralToken, tk.Kind)
Assert.Equal(#8/23/1970 3:35:39 AM#, tk.Value)
Finally
CurrentThread.CurrentCulture = SavedCultureInfo
End Try
End Sub
<Fact>
Public Sub Scanner_BracketedIdentToken()
Dim Str = "[Goo123]"
Dim tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IdentifierToken, tk.Kind)
Assert.True(tk.IsBracketed)
Assert.Equal("Goo123", tk.ValueText)
Assert.Equal("Goo123", tk.Value)
Assert.Equal("[Goo123]", tk.ToFullString())
Str = "[__]"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IdentifierToken, tk.Kind)
Assert.True(tk.IsBracketed)
Assert.Equal("__", tk.ValueText)
Assert.Equal("[__]", tk.ToFullString())
Str = "[Goo ]"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.BadToken, tk.Kind)
Assert.Equal(30034, tk.GetSyntaxErrorsNoTree()(0).Code)
Assert.Equal("[Goo ", tk.ToFullString())
Str = "[]"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.BadToken, tk.Kind)
Assert.Equal(30203, tk.GetSyntaxErrorsNoTree()(0).Code)
Assert.Equal("[]", tk.ToFullString())
Str = "[_]"
tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.BadToken, tk.Kind)
Assert.Equal(30203, tk.GetSyntaxErrorsNoTree()(0).Code)
Assert.Equal("[_]", tk.ToFullString())
End Sub
<Fact>
Public Sub Scanner_StringLiteralValueText()
Dim str = """Hello, World!"""
Dim tk = ScanOnce(str)
Assert.Equal(SyntaxKind.StringLiteralToken, tk.Kind)
Assert.Equal("Hello, World!", tk.ValueText)
Assert.Equal("""Hello, World!""", tk.ToFullString())
End Sub
<Fact>
Public Sub Scanner_MultiLineStringLiteral()
Dim text =
<text>"Hello,
World!"</text>.Value
Dim token = ScanOnce(text)
Assert.Equal(SyntaxKind.StringLiteralToken, token.Kind)
Assert.Equal("Hello," & vbLf & "World!", token.ValueText)
Assert.Equal("""Hello," & vbLf & "World!""", token.ToString())
End Sub
Private Function Repeat(str As String, num As Integer) As String
Dim arr(num - 1) As String
For i As Integer = 0 To num - 1
arr(i) = str
Next
Return String.Join("", arr)
End Function
<Fact>
Public Sub Scanner_BufferTest()
For i As Integer = 0 To 12
Dim TokenStr = New String("+"c, i)
Dim tks = ScanAllCheckDw(TokenStr)
Assert.Equal(i + 1, tks.Count)
TokenStr = Repeat(" SomeIdentifier ", i)
tks = ScanAllCheckDw(TokenStr)
Assert.Equal(i + 1, tks.Count)
' trying to place space after "someIdent" on ^2 boundary
Dim identLen = Math.Max(1, CInt(2 ^ i) - 11)
TokenStr = Repeat("X", identLen) & " someIdent " & Repeat("X", identLen + 11)
tks = ScanAllNoDwCheck(TokenStr)
Assert.Equal(4, tks.Count)
Next
For i As Integer = 100 To 5000 Step 250
Dim TokenStr = New String("+"c, i)
Dim tks = ScanAllCheckDw(TokenStr)
Assert.Equal(i + 1, tks.Count)
TokenStr = Repeat(" SomeIdentifier ", i)
tks = ScanAllCheckDw(TokenStr)
Assert.Equal(i + 1, tks.Count)
Next
End Sub
<Fact>
Public Sub Scanner_Bug866445()
Dim x = &HFF00110001020408L
Dim Str = "&HFF00110001020408L"
Dim tk = ScanOnce(Str)
Assert.Equal(SyntaxKind.IntegerLiteralToken, tk.Kind)
End Sub
<Fact>
Public Sub Bug869260()
Dim tk = ScanOnce(ChrW(0))
Assert.Equal(SyntaxKind.BadToken, tk.Kind)
Assert.Equal(CInt(ERRID.ERR_IllegalChar), tk.GetSyntaxErrorsNoTree(0).Code)
End Sub
<Fact>
Public Sub Bug869081()
ParseAndVerify(<![CDATA[
<Obsolete()> _
_
_
_
_
<CLSCompliant(False)> Class Class1
End Class
]]>)
End Sub
<Fact>
Public Sub Bug658441()
ParseAndVerify(<![CDATA[
#If False Then
#If False Then
# _
#End If
# _
End If
#End If
]]>)
End Sub
<WorkItem(538747, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538747")>
<Fact>
Public Sub OghamSpacemark()
ParseAndVerify(<![CDATA[
Module M
End Module
]]>)
End Sub
<WorkItem(531175, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531175")>
<Fact>
Public Sub Bug17703()
ParseAndVerify(<![CDATA[
Dim x = <
”'
]]>,
<errors>
<error id="31151" message="Element is missing an end tag." start="9" end="23"/>
<error id="31146" message="XML name expected." start="10" end="10"/>
<error id="31146" message="XML name expected." start="10" end="10"/>
<error id="30249" message="'=' expected." start="10" end="10"/>
<error id="31164" message="Expected matching closing double quote for XML attribute value." start="23" end="23"/>
<error id="31165" message="Expected beginning < for an XML tag." start="23" end="23"/>
<error id="30636" message="'>' expected." start="23" end="23"/>
</errors>)
End Sub
<WorkItem(530916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530916")>
<Fact>
Public Sub Bug17189()
ParseAndVerify(<![CDATA[
a<
-'
-
]]>,
<errors>
<error id="30689" message="Statement cannot appear outside of a method body." start="1" end="17"/>
<error id="30800" message="Method arguments must be enclosed in parentheses." start="2" end="17"/>
<error id="31151" message="Element is missing an end tag." start="2" end="17"/>
<error id="31177" message="White space cannot appear here." start="3" end="4"/>
<error id="31169" message="Character '-' (&H2D) is not allowed at the beginning of an XML name." start="4" end="5"/>
<error id="31146" message="XML name expected." start="5" end="5"/>
<error id="30249" message="'=' expected." start="5" end="5"/>
<error id="31163" message="Expected matching closing single quote for XML attribute value." start="17" end="17"/>
<error id="31165" message="Expected beginning '<' for an XML tag." start="17" end="17"/>
<error id="30636" message="'>' expected." start="17" end="17"/>
</errors>)
End Sub
<WorkItem(530682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530682")>
<Fact>
Public Sub Bug16698()
ParseAndVerify(<![CDATA[#Const x = <!--
]]>,
Diagnostic(ERRID.ERR_BadCCExpression, "<!--"))
End Sub
<WorkItem(865832, "DevDiv/Personal")>
<Fact>
Public Sub ParseSpecialKeywords()
ParseAndVerify(<![CDATA[
Module M1
Dim x As Integer
Sub Main
If True
End If
End Sub
End Module
]]>).
VerifyNoWhitespaceInKeywords()
End Sub
<WorkItem(547317, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547317")>
<Fact>
Public Sub ParseHugeNumber()
ParseAndVerify(<![CDATA[
Module M
Sub Main
Dim x = CompareDouble(-7.92281625142643E337593543950335D)
End Sub
EndModule
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'." start="1" end="9"/>
<error id="30036" message="Overflow." start="52" end="85"/>
<error id="30188" message="Declaration expected." start="100" end="109"/>
</errors>).
VerifyNoWhitespaceInKeywords()
End Sub
<WorkItem(547317, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547317")>
<Fact>
Public Sub ParseHugeNumberLabel()
ParseAndVerify(<![CDATA[
Module M
Sub Main
678901234567890123456789012345678901234567456789012345678901234567890123456789012345
End Sub
EndModule
]]>,
<errors>
<error id="30625" message="'Module' statement must end with a matching 'End Module'." start="1" end="9"/>
<error id="30801" message="Labels that are numbers must be followed by colons." start="30" end="114"/>
<error id="30036" message="Overflow." start="30" end="114"/>
<error id="30188" message="Declaration expected." start="128" end="137"/>
</errors>).
VerifyNoWhitespaceInKeywords()
End Sub
<WorkItem(926612, "DevDiv/Personal")>
<Fact>
Public Sub ScanMultilinesTriviaWithCRLFs()
ParseAndVerify(<![CDATA[Option Compare Text
Public Class Assembly001bDll
Sub main()
Dim Asb As System.Reflection.Assembly
Asb = System.Reflection.Assembly.GetExecutingAssembly()
apcompare(Left(CurDir(), 1) & ":\School\assembly001bdll.dll", Asb.Location, "location")
End Sub
End Class]]>)
End Sub
<Fact>
Public Sub IsWhiteSpace()
Assert.False(SyntaxFacts.IsWhitespace("A"c))
Assert.True(SyntaxFacts.IsWhitespace(" "c))
Assert.True(SyntaxFacts.IsWhitespace(ChrW(9)))
Assert.False(SyntaxFacts.IsWhitespace(ChrW(0)))
Assert.False(SyntaxFacts.IsWhitespace(ChrW(128)))
Assert.False(SyntaxFacts.IsWhitespace(ChrW(129)))
Assert.False(SyntaxFacts.IsWhitespace(ChrW(127)))
Assert.True(SyntaxFacts.IsWhitespace(ChrW(160)))
Assert.True(SyntaxFacts.IsWhitespace(ChrW(12288)))
Assert.True(SyntaxFacts.IsWhitespace(ChrW(8192)))
Assert.True(SyntaxFacts.IsWhitespace(ChrW(8203)))
End Sub
<Fact>
Public Sub IsNewline()
Assert.True(SyntaxFacts.IsNewLine(ChrW(13)))
Assert.True(SyntaxFacts.IsNewLine(ChrW(10)))
Assert.True(SyntaxFacts.IsNewLine(ChrW(133)))
Assert.True(SyntaxFacts.IsNewLine(ChrW(8232)))
Assert.True(SyntaxFacts.IsNewLine(ChrW(8233)))
Assert.False(SyntaxFacts.IsNewLine(ChrW(132)))
Assert.False(SyntaxFacts.IsNewLine(ChrW(160)))
Assert.False(SyntaxFacts.IsNewLine(" "c))
Assert.Equal(String.Empty, SyntaxFacts.MakeHalfWidthIdentifier(String.Empty))
Assert.Null(SyntaxFacts.MakeHalfWidthIdentifier(Nothing))
Assert.Equal("ABC", SyntaxFacts.MakeHalfWidthIdentifier("ABC"))
Assert.Equal(ChrW(65280), SyntaxFacts.MakeHalfWidthIdentifier(ChrW(65280)))
Assert.NotEqual(ChrW(65281), SyntaxFacts.MakeHalfWidthIdentifier(ChrW(65281)))
Assert.Equal(1, SyntaxFacts.MakeHalfWidthIdentifier(ChrW(65281)).Length)
End Sub
<Fact>
Public Sub MakeHalfWidthIdentifier()
Assert.Equal(String.Empty, SyntaxFacts.MakeHalfWidthIdentifier(String.Empty))
Assert.Equal(Nothing, SyntaxFacts.MakeHalfWidthIdentifier(Nothing))
Assert.Equal("ABC", SyntaxFacts.MakeHalfWidthIdentifier("ABC"))
Assert.Equal(ChrW(65280), SyntaxFacts.MakeHalfWidthIdentifier(ChrW(65280)))
Assert.NotEqual(ChrW(65281), SyntaxFacts.MakeHalfWidthIdentifier(ChrW(65281)))
Assert.Equal(1, SyntaxFacts.MakeHalfWidthIdentifier(ChrW(65281)).Length)
End Sub
End Class
Module SyntaxDiagnosticInfoListExtensions
<Extension>
Public Function Count(list As SyntaxDiagnosticInfoList) As Integer
Dim result = 0
For Each v In list
result += 1
Next
Return result
End Function
<Extension>
Public Function First(list As SyntaxDiagnosticInfoList) As DiagnosticInfo
For Each v In list
Return v
Next
Throw New InvalidOperationException()
End Function
<Extension>
Public Function ElementAt(list As SyntaxDiagnosticInfoList, index As Integer) As DiagnosticInfo
Dim i = 0
For Each v In list
If i = index Then
Return v
End If
i += 1
Next
Throw New IndexOutOfRangeException()
End Function
End Module
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/Core/Desktop/xlf/WorkspaceDesktopResources.fr.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="fr" original="../WorkspaceDesktopResources.resx">
<body>
<trans-unit id="Invalid_assembly_name">
<source>Invalid assembly name</source>
<target state="translated">Nom d'assembly non valide</target>
<note />
</trans-unit>
<trans-unit id="Invalid_characters_in_assembly_name">
<source>Invalid characters in assembly name</source>
<target state="translated">Caractères non valides dans le nom de l'assembly</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="fr" original="../WorkspaceDesktopResources.resx">
<body>
<trans-unit id="Invalid_assembly_name">
<source>Invalid assembly name</source>
<target state="translated">Nom d'assembly non valide</target>
<note />
</trans-unit>
<trans-unit id="Invalid_characters_in_assembly_name">
<source>Invalid characters in assembly name</source>
<target state="translated">Caractères non valides dans le nom de l'assembly</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/Core/Portable/Options/OptionSet.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Diagnostics;
namespace Microsoft.CodeAnalysis.Options
{
public abstract partial class OptionSet
{
private const string NoLanguageSentinel = "\0";
private static readonly ImmutableDictionary<string, AnalyzerConfigOptions> s_emptyAnalyzerConfigOptions =
ImmutableDictionary.Create<string, AnalyzerConfigOptions>(StringComparer.Ordinal);
/// <summary>
/// Map from language name to the <see cref="AnalyzerConfigOptions"/> wrapper.
/// </summary>
private ImmutableDictionary<string, AnalyzerConfigOptions> _lazyAnalyzerConfigOptions = s_emptyAnalyzerConfigOptions;
private readonly Func<OptionKey, object?> _getOptionCore;
protected OptionSet()
{
_getOptionCore = GetOptionCore;
}
private protected abstract object? GetOptionCore(OptionKey optionKey);
/// <summary>
/// Gets the value of the option, or the default value if not otherwise set.
/// </summary>
public object? GetOption(OptionKey optionKey)
=> OptionsHelpers.GetPublicOption(optionKey, _getOptionCore);
/// <summary>
/// Gets the value of the option cast to type <typeparamref name="T"/>, or the default value if not otherwise set.
/// </summary>
public T GetOption<T>(OptionKey optionKey)
=> OptionsHelpers.GetOption<T>(optionKey, _getOptionCore);
/// <summary>
/// Gets the value of the option, or the default value if not otherwise set.
/// </summary>
internal object? GetOption(OptionKey2 optionKey)
=> OptionsHelpers.GetOption<object?>(optionKey, _getOptionCore);
/// <summary>
/// Gets the value of the option cast to type <typeparamref name="T"/>, or the default value if not otherwise set.
/// </summary>
internal T GetOption<T>(OptionKey2 optionKey)
=> OptionsHelpers.GetOption<T>(optionKey, _getOptionCore);
/// <summary>
/// Gets the value of the option, or the default value if not otherwise set.
/// </summary>
public T GetOption<T>(Option<T> option)
=> OptionsHelpers.GetOption(option, _getOptionCore);
/// <summary>
/// Gets the value of the option, or the default value if not otherwise set.
/// </summary>
internal T GetOption<T>(Option2<T> option)
=> OptionsHelpers.GetOption(option, _getOptionCore);
/// <summary>
/// Gets the value of the option, or the default value if not otherwise set.
/// </summary>
public T GetOption<T>(PerLanguageOption<T> option, string? language)
=> OptionsHelpers.GetOption(option, language, _getOptionCore);
/// <summary>
/// Gets the value of the option, or the default value if not otherwise set.
/// </summary>
internal T GetOption<T>(PerLanguageOption2<T> option, string? language)
=> OptionsHelpers.GetOption(option, language, _getOptionCore);
/// <summary>
/// Creates a new <see cref="OptionSet" /> that contains the changed value.
/// </summary>
public abstract OptionSet WithChangedOption(OptionKey optionAndLanguage, object? value);
/// <summary>
/// Creates a new <see cref="OptionSet" /> that contains the changed value.
/// </summary>
internal OptionSet WithChangedOption(OptionKey2 optionAndLanguage, object? value)
=> WithChangedOption((OptionKey)optionAndLanguage, value);
/// <summary>
/// Creates a new <see cref="OptionSet" /> that contains the changed value.
/// </summary>
public OptionSet WithChangedOption<T>(Option<T> option, T value)
=> WithChangedOption(new OptionKey(option), value);
/// <summary>
/// Creates a new <see cref="OptionSet" /> that contains the changed value.
/// </summary>
internal OptionSet WithChangedOption<T>(Option2<T> option, T value)
=> WithChangedOption(new OptionKey(option), value);
/// <summary>
/// Creates a new <see cref="OptionSet" /> that contains the changed value.
/// </summary>
public OptionSet WithChangedOption<T>(PerLanguageOption<T> option, string? language, T value)
=> WithChangedOption(new OptionKey(option, language), value);
/// <summary>
/// Creates a new <see cref="OptionSet" /> that contains the changed value.
/// </summary>
internal OptionSet WithChangedOption<T>(PerLanguageOption2<T> option, string? language, T value)
=> WithChangedOption(new OptionKey(option, language), value);
internal AnalyzerConfigOptions AsAnalyzerConfigOptions(IOptionService optionService, string? language)
{
return ImmutableInterlocked.GetOrAdd(
ref _lazyAnalyzerConfigOptions,
language ?? NoLanguageSentinel,
(string language, (OptionSet self, IOptionService optionService) arg) => arg.self.CreateAnalyzerConfigOptions(arg.optionService, (object)language == NoLanguageSentinel ? null : language),
(this, optionService));
}
internal abstract IEnumerable<OptionKey> GetChangedOptions(OptionSet optionSet);
private protected virtual AnalyzerConfigOptions CreateAnalyzerConfigOptions(IOptionService optionService, string? language)
=> new AnalyzerConfigOptionsImpl(this, optionService, language);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.Options
{
public abstract partial class OptionSet
{
private const string NoLanguageSentinel = "\0";
private static readonly ImmutableDictionary<string, AnalyzerConfigOptions> s_emptyAnalyzerConfigOptions =
ImmutableDictionary.Create<string, AnalyzerConfigOptions>(StringComparer.Ordinal);
/// <summary>
/// Map from language name to the <see cref="AnalyzerConfigOptions"/> wrapper.
/// </summary>
private ImmutableDictionary<string, AnalyzerConfigOptions> _lazyAnalyzerConfigOptions = s_emptyAnalyzerConfigOptions;
private readonly Func<OptionKey, object?> _getOptionCore;
protected OptionSet()
{
_getOptionCore = GetOptionCore;
}
private protected abstract object? GetOptionCore(OptionKey optionKey);
/// <summary>
/// Gets the value of the option, or the default value if not otherwise set.
/// </summary>
public object? GetOption(OptionKey optionKey)
=> OptionsHelpers.GetPublicOption(optionKey, _getOptionCore);
/// <summary>
/// Gets the value of the option cast to type <typeparamref name="T"/>, or the default value if not otherwise set.
/// </summary>
public T GetOption<T>(OptionKey optionKey)
=> OptionsHelpers.GetOption<T>(optionKey, _getOptionCore);
/// <summary>
/// Gets the value of the option, or the default value if not otherwise set.
/// </summary>
internal object? GetOption(OptionKey2 optionKey)
=> OptionsHelpers.GetOption<object?>(optionKey, _getOptionCore);
/// <summary>
/// Gets the value of the option cast to type <typeparamref name="T"/>, or the default value if not otherwise set.
/// </summary>
internal T GetOption<T>(OptionKey2 optionKey)
=> OptionsHelpers.GetOption<T>(optionKey, _getOptionCore);
/// <summary>
/// Gets the value of the option, or the default value if not otherwise set.
/// </summary>
public T GetOption<T>(Option<T> option)
=> OptionsHelpers.GetOption(option, _getOptionCore);
/// <summary>
/// Gets the value of the option, or the default value if not otherwise set.
/// </summary>
internal T GetOption<T>(Option2<T> option)
=> OptionsHelpers.GetOption(option, _getOptionCore);
/// <summary>
/// Gets the value of the option, or the default value if not otherwise set.
/// </summary>
public T GetOption<T>(PerLanguageOption<T> option, string? language)
=> OptionsHelpers.GetOption(option, language, _getOptionCore);
/// <summary>
/// Gets the value of the option, or the default value if not otherwise set.
/// </summary>
internal T GetOption<T>(PerLanguageOption2<T> option, string? language)
=> OptionsHelpers.GetOption(option, language, _getOptionCore);
/// <summary>
/// Creates a new <see cref="OptionSet" /> that contains the changed value.
/// </summary>
public abstract OptionSet WithChangedOption(OptionKey optionAndLanguage, object? value);
/// <summary>
/// Creates a new <see cref="OptionSet" /> that contains the changed value.
/// </summary>
internal OptionSet WithChangedOption(OptionKey2 optionAndLanguage, object? value)
=> WithChangedOption((OptionKey)optionAndLanguage, value);
/// <summary>
/// Creates a new <see cref="OptionSet" /> that contains the changed value.
/// </summary>
public OptionSet WithChangedOption<T>(Option<T> option, T value)
=> WithChangedOption(new OptionKey(option), value);
/// <summary>
/// Creates a new <see cref="OptionSet" /> that contains the changed value.
/// </summary>
internal OptionSet WithChangedOption<T>(Option2<T> option, T value)
=> WithChangedOption(new OptionKey(option), value);
/// <summary>
/// Creates a new <see cref="OptionSet" /> that contains the changed value.
/// </summary>
public OptionSet WithChangedOption<T>(PerLanguageOption<T> option, string? language, T value)
=> WithChangedOption(new OptionKey(option, language), value);
/// <summary>
/// Creates a new <see cref="OptionSet" /> that contains the changed value.
/// </summary>
internal OptionSet WithChangedOption<T>(PerLanguageOption2<T> option, string? language, T value)
=> WithChangedOption(new OptionKey(option, language), value);
internal AnalyzerConfigOptions AsAnalyzerConfigOptions(IOptionService optionService, string? language)
{
return ImmutableInterlocked.GetOrAdd(
ref _lazyAnalyzerConfigOptions,
language ?? NoLanguageSentinel,
(string language, (OptionSet self, IOptionService optionService) arg) => arg.self.CreateAnalyzerConfigOptions(arg.optionService, (object)language == NoLanguageSentinel ? null : language),
(this, optionService));
}
internal abstract IEnumerable<OptionKey> GetChangedOptions(OptionSet optionSet);
private protected virtual AnalyzerConfigOptions CreateAnalyzerConfigOptions(IOptionService optionService, string? language)
=> new AnalyzerConfigOptionsImpl(this, optionService, language);
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/ExternalAccess/VSTypeScript/Api/IVSTypeScriptNavigableItem.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api
{
internal interface IVSTypeScriptNavigableItem
{
Glyph Glyph { get; }
/// <summary>
/// The tagged parts to display for this item. If default, the line of text from <see cref="Document"/> is used.
/// </summary>
ImmutableArray<TaggedText> DisplayTaggedParts { get; }
/// <summary>
/// Return true to display the file path of <see cref="Document"/> and the span of <see cref="SourceSpan"/> when displaying this item.
/// </summary>
bool DisplayFileLocation { get; }
/// <summary>
/// his is intended for symbols that are ordinary symbols in the language sense, and may be
/// used by code, but that are simply declared implicitly rather than with explicit language
/// syntax. For example, a default synthesized constructor in C# when the class contains no
/// explicit constructors.
/// </summary>
bool IsImplicitlyDeclared { get; }
Document Document { get; }
TextSpan SourceSpan { get; }
ImmutableArray<IVSTypeScriptNavigableItem> ChildItems { get; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api
{
internal interface IVSTypeScriptNavigableItem
{
Glyph Glyph { get; }
/// <summary>
/// The tagged parts to display for this item. If default, the line of text from <see cref="Document"/> is used.
/// </summary>
ImmutableArray<TaggedText> DisplayTaggedParts { get; }
/// <summary>
/// Return true to display the file path of <see cref="Document"/> and the span of <see cref="SourceSpan"/> when displaying this item.
/// </summary>
bool DisplayFileLocation { get; }
/// <summary>
/// his is intended for symbols that are ordinary symbols in the language sense, and may be
/// used by code, but that are simply declared implicitly rather than with explicit language
/// syntax. For example, a default synthesized constructor in C# when the class contains no
/// explicit constructors.
/// </summary>
bool IsImplicitlyDeclared { get; }
Document Document { get; }
TextSpan SourceSpan { get; }
ImmutableArray<IVSTypeScriptNavigableItem> ChildItems { get; }
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/Core/Portable/Rename/RenameOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.Rename
{
public static class RenameOptions
{
public static Option<bool> RenameOverloads { get; } = new Option<bool>(nameof(RenameOptions), nameof(RenameOverloads), defaultValue: false);
public static Option<bool> RenameInStrings { get; } = new Option<bool>(nameof(RenameOptions), nameof(RenameInStrings), defaultValue: false);
public static Option<bool> RenameInComments { get; } = new Option<bool>(nameof(RenameOptions), nameof(RenameInComments), defaultValue: false);
/// <summary>
/// Set to true if the file name should match the type name after a rename operation
/// </summary>
internal static Option<bool> RenameFile { get; } = new Option<bool>(nameof(RenameOptions), nameof(RenameFile), defaultValue: false);
public static Option<bool> PreviewChanges { get; } = new Option<bool>(nameof(RenameOptions), nameof(PreviewChanges), defaultValue: false);
}
internal struct RenameOptionSet
{
public readonly bool RenameOverloads;
public readonly bool RenameInStrings;
public readonly bool RenameInComments;
public readonly bool RenameFile;
public RenameOptionSet(bool renameOverloads, bool renameInStrings, bool renameInComments, bool renameFile)
{
RenameOverloads = renameOverloads;
RenameInStrings = renameInStrings;
RenameInComments = renameInComments;
RenameFile = renameFile;
}
internal static RenameOptionSet From(Solution solution)
=> From(solution, options: null);
internal static RenameOptionSet From(Solution solution, OptionSet options)
{
options ??= solution.Options;
return new RenameOptionSet(
options.GetOption(RenameOptions.RenameOverloads),
options.GetOption(RenameOptions.RenameInStrings),
options.GetOption(RenameOptions.RenameInComments),
options.GetOption(RenameOptions.RenameFile));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.Rename
{
public static class RenameOptions
{
public static Option<bool> RenameOverloads { get; } = new Option<bool>(nameof(RenameOptions), nameof(RenameOverloads), defaultValue: false);
public static Option<bool> RenameInStrings { get; } = new Option<bool>(nameof(RenameOptions), nameof(RenameInStrings), defaultValue: false);
public static Option<bool> RenameInComments { get; } = new Option<bool>(nameof(RenameOptions), nameof(RenameInComments), defaultValue: false);
/// <summary>
/// Set to true if the file name should match the type name after a rename operation
/// </summary>
internal static Option<bool> RenameFile { get; } = new Option<bool>(nameof(RenameOptions), nameof(RenameFile), defaultValue: false);
public static Option<bool> PreviewChanges { get; } = new Option<bool>(nameof(RenameOptions), nameof(PreviewChanges), defaultValue: false);
}
internal struct RenameOptionSet
{
public readonly bool RenameOverloads;
public readonly bool RenameInStrings;
public readonly bool RenameInComments;
public readonly bool RenameFile;
public RenameOptionSet(bool renameOverloads, bool renameInStrings, bool renameInComments, bool renameFile)
{
RenameOverloads = renameOverloads;
RenameInStrings = renameInStrings;
RenameInComments = renameInComments;
RenameFile = renameFile;
}
internal static RenameOptionSet From(Solution solution)
=> From(solution, options: null);
internal static RenameOptionSet From(Solution solution, OptionSet options)
{
options ??= solution.Options;
return new RenameOptionSet(
options.GetOption(RenameOptions.RenameOverloads),
options.GetOption(RenameOptions.RenameInStrings),
options.GetOption(RenameOptions.RenameInComments),
options.GetOption(RenameOptions.RenameFile));
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/DefaultExpressionSyntaxExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static class DefaultExpressionSyntaxExtensions
{
private static readonly LiteralExpressionSyntax s_defaultLiteralExpression =
SyntaxFactory.LiteralExpression(SyntaxKind.DefaultLiteralExpression);
public static bool CanReplaceWithDefaultLiteral(
this DefaultExpressionSyntax defaultExpression,
CSharpParseOptions parseOptions,
bool preferSimpleDefaultExpression,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
if (parseOptions.LanguageVersion < LanguageVersion.CSharp7_1 ||
!preferSimpleDefaultExpression)
{
return false;
}
// Using the speculation analyzer can be slow. Check for common cases first before
// trying the expensive path.
return CanReplaceWithDefaultLiteralFast(defaultExpression, semanticModel, cancellationToken) ??
CanReplaceWithDefaultLiteralSlow(defaultExpression, semanticModel, cancellationToken);
}
private static bool? CanReplaceWithDefaultLiteralFast(
DefaultExpressionSyntax defaultExpression, SemanticModel semanticModel, CancellationToken cancellationToken)
{
if (defaultExpression.IsParentKind(SyntaxKind.EqualsValueClause, out EqualsValueClauseSyntax equalsValueClause))
{
var typeSyntax = GetTypeSyntax(equalsValueClause);
if (typeSyntax != null)
{
if (typeSyntax.IsVar)
{
// If we have: var v = default(CancellationToken); then we can't simplify this.
return false;
}
var entityType = semanticModel.GetTypeInfo(typeSyntax, cancellationToken).Type;
var defaultType = semanticModel.GetTypeInfo(defaultExpression.Type, cancellationToken).Type;
if (entityType != null && entityType.Equals(defaultType))
{
// We have a simple case of "CancellationToken c = default(CancellationToken)".
// We can just simplify without having to do any additional analysis.
return true;
}
}
}
return null;
}
private static TypeSyntax GetTypeSyntax(EqualsValueClauseSyntax equalsValueClause)
{
if (equalsValueClause.IsParentKind(SyntaxKind.VariableDeclarator) &&
equalsValueClause.Parent.IsParentKind(SyntaxKind.VariableDeclaration, out VariableDeclarationSyntax declaration))
{
return declaration.Type;
}
else if (equalsValueClause.IsParentKind(SyntaxKind.Parameter, out ParameterSyntax parameter))
{
return parameter.Type;
}
return null;
}
private static bool CanReplaceWithDefaultLiteralSlow(
DefaultExpressionSyntax defaultExpression, SemanticModel semanticModel, CancellationToken cancellationToken)
{
var speculationAnalyzer = new SpeculationAnalyzer(
defaultExpression, s_defaultLiteralExpression, semanticModel,
cancellationToken,
skipVerificationForReplacedNode: false,
failOnOverloadResolutionFailuresInOriginalCode: true);
return !speculationAnalyzer.ReplacementChangesSemantics();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static class DefaultExpressionSyntaxExtensions
{
private static readonly LiteralExpressionSyntax s_defaultLiteralExpression =
SyntaxFactory.LiteralExpression(SyntaxKind.DefaultLiteralExpression);
public static bool CanReplaceWithDefaultLiteral(
this DefaultExpressionSyntax defaultExpression,
CSharpParseOptions parseOptions,
bool preferSimpleDefaultExpression,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
if (parseOptions.LanguageVersion < LanguageVersion.CSharp7_1 ||
!preferSimpleDefaultExpression)
{
return false;
}
// Using the speculation analyzer can be slow. Check for common cases first before
// trying the expensive path.
return CanReplaceWithDefaultLiteralFast(defaultExpression, semanticModel, cancellationToken) ??
CanReplaceWithDefaultLiteralSlow(defaultExpression, semanticModel, cancellationToken);
}
private static bool? CanReplaceWithDefaultLiteralFast(
DefaultExpressionSyntax defaultExpression, SemanticModel semanticModel, CancellationToken cancellationToken)
{
if (defaultExpression.IsParentKind(SyntaxKind.EqualsValueClause, out EqualsValueClauseSyntax equalsValueClause))
{
var typeSyntax = GetTypeSyntax(equalsValueClause);
if (typeSyntax != null)
{
if (typeSyntax.IsVar)
{
// If we have: var v = default(CancellationToken); then we can't simplify this.
return false;
}
var entityType = semanticModel.GetTypeInfo(typeSyntax, cancellationToken).Type;
var defaultType = semanticModel.GetTypeInfo(defaultExpression.Type, cancellationToken).Type;
if (entityType != null && entityType.Equals(defaultType))
{
// We have a simple case of "CancellationToken c = default(CancellationToken)".
// We can just simplify without having to do any additional analysis.
return true;
}
}
}
return null;
}
private static TypeSyntax GetTypeSyntax(EqualsValueClauseSyntax equalsValueClause)
{
if (equalsValueClause.IsParentKind(SyntaxKind.VariableDeclarator) &&
equalsValueClause.Parent.IsParentKind(SyntaxKind.VariableDeclaration, out VariableDeclarationSyntax declaration))
{
return declaration.Type;
}
else if (equalsValueClause.IsParentKind(SyntaxKind.Parameter, out ParameterSyntax parameter))
{
return parameter.Type;
}
return null;
}
private static bool CanReplaceWithDefaultLiteralSlow(
DefaultExpressionSyntax defaultExpression, SemanticModel semanticModel, CancellationToken cancellationToken)
{
var speculationAnalyzer = new SpeculationAnalyzer(
defaultExpression, s_defaultLiteralExpression, semanticModel,
cancellationToken,
skipVerificationForReplacedNode: false,
failOnOverloadResolutionFailuresInOriginalCode: true);
return !speculationAnalyzer.ReplacementChangesSemantics();
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Def/Implementation/Progression/GraphQueries/CallsGraphQuery.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.VisualStudio.GraphModel;
using Microsoft.VisualStudio.GraphModel.Schemas;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression
{
internal sealed class CallsGraphQuery : IGraphQuery
{
public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken)
{
var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false);
foreach (var node in context.InputNodes)
{
var symbol = graphBuilder.GetSymbol(node, cancellationToken);
if (symbol != null)
{
foreach (var newSymbol in await GetCalledMethodSymbolsAsync(symbol, solution, cancellationToken).ConfigureAwait(false))
{
cancellationToken.ThrowIfCancellationRequested();
var newNode = await graphBuilder.AddNodeAsync(newSymbol, relatedNode: node, cancellationToken).ConfigureAwait(false);
graphBuilder.AddLink(node, CodeLinkCategories.Calls, newNode, cancellationToken);
}
}
}
return graphBuilder;
}
private static async Task<ImmutableArray<ISymbol>> GetCalledMethodSymbolsAsync(
ISymbol symbol, Solution solution, CancellationToken cancellationToken)
{
using var _ = ArrayBuilder<ISymbol>.GetInstance(out var symbols);
foreach (var reference in symbol.DeclaringSyntaxReferences)
{
var semanticModel = await solution.GetDocument(reference.SyntaxTree).GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
foreach (var syntaxNode in (await reference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false)).DescendantNodes())
{
cancellationToken.ThrowIfCancellationRequested();
var newSymbol = semanticModel.GetSymbolInfo(syntaxNode, cancellationToken).Symbol;
if (newSymbol != null && newSymbol is IMethodSymbol &&
(newSymbol.CanBeReferencedByName || ((IMethodSymbol)newSymbol).MethodKind == MethodKind.Constructor))
{
symbols.Add(newSymbol);
}
}
}
return symbols.ToImmutable();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.VisualStudio.GraphModel;
using Microsoft.VisualStudio.GraphModel.Schemas;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression
{
internal sealed class CallsGraphQuery : IGraphQuery
{
public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken)
{
var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false);
foreach (var node in context.InputNodes)
{
var symbol = graphBuilder.GetSymbol(node, cancellationToken);
if (symbol != null)
{
foreach (var newSymbol in await GetCalledMethodSymbolsAsync(symbol, solution, cancellationToken).ConfigureAwait(false))
{
cancellationToken.ThrowIfCancellationRequested();
var newNode = await graphBuilder.AddNodeAsync(newSymbol, relatedNode: node, cancellationToken).ConfigureAwait(false);
graphBuilder.AddLink(node, CodeLinkCategories.Calls, newNode, cancellationToken);
}
}
}
return graphBuilder;
}
private static async Task<ImmutableArray<ISymbol>> GetCalledMethodSymbolsAsync(
ISymbol symbol, Solution solution, CancellationToken cancellationToken)
{
using var _ = ArrayBuilder<ISymbol>.GetInstance(out var symbols);
foreach (var reference in symbol.DeclaringSyntaxReferences)
{
var semanticModel = await solution.GetDocument(reference.SyntaxTree).GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
foreach (var syntaxNode in (await reference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false)).DescendantNodes())
{
cancellationToken.ThrowIfCancellationRequested();
var newSymbol = semanticModel.GetSymbolInfo(syntaxNode, cancellationToken).Symbol;
if (newSymbol != null && newSymbol is IMethodSymbol &&
(newSymbol.CanBeReferencedByName || ((IMethodSymbol)newSymbol).MethodKind == MethodKind.Constructor))
{
symbols.Add(newSymbol);
}
}
}
return symbols.ToImmutable();
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Test/Semantic/Semantics/RecordTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics
{
public class RecordTests : CompilingTestBase
{
private static CSharpCompilation CreateCompilation(CSharpTestSource source)
=> CSharpTestBase.CreateCompilation(new[] { source, IsExternalInitTypeDefinition },
parseOptions: TestOptions.RegularPreview);
private CompilationVerifier CompileAndVerify(
CSharpTestSource src,
string? expectedOutput = null,
IEnumerable<MetadataReference>? references = null)
=> base.CompileAndVerify(
new[] { src, IsExternalInitTypeDefinition },
expectedOutput: expectedOutput,
parseOptions: TestOptions.RegularPreview,
references: references,
// init-only is unverifiable
verify: Verification.Skipped);
[Fact, WorkItem(45900, "https://github.com/dotnet/roslyn/issues/45900")]
public void RecordLanguageVersion()
{
var src1 = @"
class Point(int x, int y);
";
var src2 = @"
record Point { }
";
var src3 = @"
record Point(int x, int y);
";
var comp = CreateCompilation(src1, parseOptions: TestOptions.Regular8, options: TestOptions.ReleaseDll);
comp.VerifyDiagnostics(
// (2,12): error CS8805: Program using top-level statements must be an executable.
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int x, int y);").WithLocation(2, 12),
// (2,12): error CS1514: { expected
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(2, 12),
// (2,12): error CS1513: } expected
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(2, 12),
// (2,12): error CS8400: Feature 'top-level statements' is not available in C# 8.0. Please use language version 9.0 or greater.
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(int x, int y);").WithArguments("top-level statements", "9.0").WithLocation(2, 12),
// (2,12): error CS8803: Top-level statements must precede namespace and type declarations.
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int x, int y);").WithLocation(2, 12),
// (2,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x, int y)").WithLocation(2, 12),
// (2,13): error CS8185: A declaration is not allowed in this context.
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x").WithLocation(2, 13),
// (2,13): error CS0165: Use of unassigned local variable 'x'
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int x").WithArguments("x").WithLocation(2, 13),
// (2,20): error CS8185: A declaration is not allowed in this context.
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int y").WithLocation(2, 20),
// (2,20): error CS0165: Use of unassigned local variable 'y'
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int y").WithArguments("y").WithLocation(2, 20)
);
comp = CreateCompilation(src2, parseOptions: TestOptions.Regular8, options: TestOptions.ReleaseDll);
comp.VerifyDiagnostics(
// (2,1): error CS0246: The type or namespace name 'record' could not be found (are you missing a using directive or an assembly reference?)
// record Point { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "record").WithArguments("record").WithLocation(2, 1),
// (2,8): error CS0116: A namespace cannot directly contain members such as fields or methods
// record Point { }
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "Point").WithLocation(2, 8),
// (2,8): error CS0548: '<invalid-global-code>.Point': property or indexer must have at least one accessor
// record Point { }
Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "Point").WithArguments("<invalid-global-code>.Point").WithLocation(2, 8)
);
comp = CreateCompilation(src3, parseOptions: TestOptions.Regular8, options: TestOptions.ReleaseDll);
comp.VerifyDiagnostics(
// (2,1): error CS8805: Program using top-level statements must be an executable.
// record Point(int x, int y);
Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "record Point(int x, int y);").WithLocation(2, 1),
// (2,1): error CS8400: Feature 'top-level statements' is not available in C# 8.0. Please use language version 9.0 or greater.
// record Point(int x, int y);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "record Point(int x, int y);").WithArguments("top-level statements", "9.0").WithLocation(2, 1),
// (2,1): error CS0246: The type or namespace name 'record' could not be found (are you missing a using directive or an assembly reference?)
// record Point(int x, int y);
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "record").WithArguments("record").WithLocation(2, 1),
// (2,8): error CS8112: Local function 'Point(int, int)' must declare a body because it is not marked 'static extern'.
// record Point(int x, int y);
Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "Point").WithArguments("Point(int, int)").WithLocation(2, 8),
// (2,8): warning CS8321: The local function 'Point' is declared but never used
// record Point(int x, int y);
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Point").WithArguments("Point").WithLocation(2, 8)
);
comp = CreateCompilation(src1, options: TestOptions.ReleaseDll);
comp.VerifyDiagnostics(
// (2,12): error CS8805: Program using top-level statements must be an executable.
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int x, int y);").WithLocation(2, 12),
// (2,12): error CS1514: { expected
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(2, 12),
// (2,12): error CS1513: } expected
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(2, 12),
// (2,12): error CS8803: Top-level statements must precede namespace and type declarations.
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int x, int y);").WithLocation(2, 12),
// (2,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x, int y)").WithLocation(2, 12),
// (2,13): error CS8185: A declaration is not allowed in this context.
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x").WithLocation(2, 13),
// (2,13): error CS0165: Use of unassigned local variable 'x'
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int x").WithArguments("x").WithLocation(2, 13),
// (2,20): error CS8185: A declaration is not allowed in this context.
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int y").WithLocation(2, 20),
// (2,20): error CS0165: Use of unassigned local variable 'y'
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int y").WithArguments("y").WithLocation(2, 20)
);
comp = CreateCompilation(src2);
comp.VerifyDiagnostics();
comp = CreateCompilation(src3);
comp.VerifyDiagnostics();
var point = comp.GlobalNamespace.GetTypeMember("Point");
Assert.True(point.IsReferenceType);
Assert.False(point.IsValueType);
Assert.Equal(TypeKind.Class, point.TypeKind);
Assert.Equal(SpecialType.System_Object, point.BaseTypeNoUseSiteDiagnostics.SpecialType);
}
[Fact, WorkItem(45900, "https://github.com/dotnet/roslyn/issues/45900")]
public void RecordLanguageVersion_Nested()
{
var src1 = @"
class C
{
class Point(int x, int y);
}
";
var src2 = @"
class D
{
record Point { }
}
";
var src3 = @"
class E
{
record Point(int x, int y);
}
";
var comp = CreateCompilation(src1, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (4,16): error CS1514: { expected
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(4, 16),
// (4,16): error CS1513: } expected
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(4, 16),
// (4,30): error CS1519: Invalid token ';' in class, struct, or interface member declaration
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 30),
// (4,30): error CS1519: Invalid token ';' in class, struct, or interface member declaration
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 30)
);
comp = CreateCompilation(src2, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (4,5): error CS0246: The type or namespace name 'record' could not be found (are you missing a using directive or an assembly reference?)
// record Point { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "record").WithArguments("record").WithLocation(4, 5),
// (4,12): error CS0548: 'D.Point': property or indexer must have at least one accessor
// record Point { }
Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "Point").WithArguments("D.Point").WithLocation(4, 12)
);
comp = CreateCompilation(src3, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (4,5): error CS0246: The type or namespace name 'record' could not be found (are you missing a using directive or an assembly reference?)
// record Point(int x, int y);
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "record").WithArguments("record").WithLocation(4, 5),
// (4,12): error CS0501: 'E.Point(int, int)' must declare a body because it is not marked abstract, extern, or partial
// record Point(int x, int y);
Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "Point").WithArguments("E.Point(int, int)").WithLocation(4, 12)
);
comp = CreateCompilation(src1);
comp.VerifyDiagnostics(
// (4,16): error CS1514: { expected
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(4, 16),
// (4,16): error CS1513: } expected
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(4, 16),
// (4,30): error CS1519: Invalid token ';' in class, struct, or interface member declaration
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 30),
// (4,30): error CS1519: Invalid token ';' in class, struct, or interface member declaration
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 30)
);
comp = CreateCompilation(src2);
comp.VerifyDiagnostics();
comp = CreateCompilation(src3);
comp.VerifyDiagnostics();
}
[Fact, WorkItem(45900, "https://github.com/dotnet/roslyn/issues/45900")]
public void RecordClassLanguageVersion()
{
var src = @"
record class Point(int x, int y);
";
var comp = CreateCompilation(src, parseOptions: TestOptions.Regular8, options: TestOptions.ReleaseDll);
comp.VerifyDiagnostics(
// (2,1): error CS0116: A namespace cannot directly contain members such as fields or methods
// record class Point(int x, int y);
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "record").WithLocation(2, 1),
// (2,19): error CS1514: { expected
// record class Point(int x, int y);
Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(2, 19),
// (2,19): error CS1513: } expected
// record class Point(int x, int y);
Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(2, 19),
// (2,19): error CS8400: Feature 'top-level statements' is not available in C# 8.0. Please use language version 9.0 or greater.
// record class Point(int x, int y);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(int x, int y);").WithArguments("top-level statements", "9.0").WithLocation(2, 19),
// (2,19): error CS8803: Top-level statements must precede namespace and type declarations.
// record class Point(int x, int y);
Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int x, int y);").WithLocation(2, 19),
// (2,19): error CS8805: Program using top-level statements must be an executable.
// record class Point(int x, int y);
Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int x, int y);").WithLocation(2, 19),
// (2,19): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// record class Point(int x, int y);
Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x, int y)").WithLocation(2, 19),
// (2,20): error CS8185: A declaration is not allowed in this context.
// record class Point(int x, int y);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x").WithLocation(2, 20),
// (2,20): error CS0165: Use of unassigned local variable 'x'
// record class Point(int x, int y);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int x").WithArguments("x").WithLocation(2, 20),
// (2,27): error CS8185: A declaration is not allowed in this context.
// record class Point(int x, int y);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int y").WithLocation(2, 27),
// (2,27): error CS0165: Use of unassigned local variable 'y'
// record class Point(int x, int y);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int y").WithArguments("y").WithLocation(2, 27)
);
comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyDiagnostics(
// (2,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater.
// record class Point(int x, int y);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "class").WithArguments("record structs", "10.0").WithLocation(2, 8)
);
comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10, options: TestOptions.ReleaseDll);
comp.VerifyDiagnostics();
}
[CombinatorialData]
[Theory, WorkItem(49302, "https://github.com/dotnet/roslyn/issues/49302")]
public void GetSimpleNonTypeMembers(bool useCompilationReference)
{
var lib_src = @"
public record RecordA(RecordB B);
public record RecordB(int C);
";
var lib_comp = CreateCompilation(lib_src);
var src = @"
class C
{
void M(RecordA a, RecordB b)
{
_ = a.B == b;
}
}
";
var comp = CreateCompilation(src, references: new[] { AsReference(lib_comp, useCompilationReference) });
comp.VerifyEmitDiagnostics();
}
[Fact, WorkItem(49302, "https://github.com/dotnet/roslyn/issues/49302")]
public void GetSimpleNonTypeMembers_SingleCompilation()
{
var src = @"
public record RecordA(RecordB B);
public record RecordB(int C);
class C
{
void M(RecordA a, RecordB b)
{
_ = a.B == b;
}
}
";
var comp = CreateCompilation(src);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree, ignoreAccessibility: false);
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
Assert.Equal("System.Boolean RecordB.op_Equality(RecordB? left, RecordB? right)",
model.GetSymbolInfo(node).Symbol.ToTestDisplayString());
}
[Fact, WorkItem(49302, "https://github.com/dotnet/roslyn/issues/49302")]
public void GetSimpleNonTypeMembers_DirectApiCheck()
{
var src = @"
public record RecordB();
";
var comp = CreateCompilation(src);
var b = comp.GlobalNamespace.GetTypeMember("RecordB");
AssertEx.SetEqual(new[] { "System.Boolean RecordB.op_Equality(RecordB? left, RecordB? right)" },
b.GetSimpleNonTypeMembers("op_Equality").ToTestDisplayStrings());
}
[Fact, WorkItem(49628, "https://github.com/dotnet/roslyn/issues/49628")]
public void AmbigCtor()
{
var src = @"
record R(R x);
#nullable enable
record R2(R2? x) { }
record R3([System.Diagnostics.CodeAnalysis.NotNull] R3 x);
";
var comp = CreateCompilation(new[] { src, NotNullAttributeDefinition });
comp.VerifyEmitDiagnostics(
// (2,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor.
// record R(R x);
Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R").WithLocation(2, 8),
// (5,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor.
// record R2(R2? x) { }
Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R2").WithLocation(5, 8),
// (7,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor.
// record R3([System.Diagnostics.CodeAnalysis.NotNull] R3 x);
Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R3").WithLocation(7, 8)
);
var r = comp.GlobalNamespace.GetTypeMember("R");
Assert.Equal(new[] { "R..ctor(R x)", "R..ctor(R original)" }, r.GetMembers(".ctor").ToTestDisplayStrings());
}
[Fact, WorkItem(49628, "https://github.com/dotnet/roslyn/issues/49628")]
public void AmbigCtor_Generic()
{
var src = @"
record R<T>(R<T> x);
#nullable enable
record R2<T>(R2<T?> x) { }
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (2,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor.
// record R<T>(R<T> x);
Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R").WithLocation(2, 8),
// (5,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor.
// record R2<T>(R2<T?> x) { }
Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R2").WithLocation(5, 8)
);
}
[Fact, WorkItem(49628, "https://github.com/dotnet/roslyn/issues/49628")]
public void AmbigCtor_WithExplicitCopyCtor()
{
var src = @"
record R(R x)
{
public R(R x) => throw null;
}
";
var comp = CreateCompilation(new[] { src, NotNullAttributeDefinition });
comp.VerifyEmitDiagnostics(
// (4,12): error CS0111: Type 'R' already defines a member called 'R' with the same parameter types
// public R(R x) => throw null;
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "R").WithArguments("R", "R").WithLocation(4, 12)
);
var r = comp.GlobalNamespace.GetTypeMember("R");
Assert.Equal(new[] { "R..ctor(R x)", "R..ctor(R x)" }, r.GetMembers(".ctor").ToTestDisplayStrings());
}
[Fact, WorkItem(49628, "https://github.com/dotnet/roslyn/issues/49628")]
public void AmbigCtor_WithBase()
{
var src = @"
record Base;
record R(R x) : Base; // 1
record Derived(Derived y) : R(y) // 2
{
public Derived(Derived y) : base(y) => throw null; // 3, 4, 5
}
record Derived2(Derived2 y) : R(y); // 6, 7, 8
record R2(R2 x) : Base
{
public R2(R2 x) => throw null; // 9, 10
}
record R3(R3 x) : Base
{
public R3(R3 x) : base(x) => throw null; // 11
}
";
var comp = CreateCompilation(new[] { src, NotNullAttributeDefinition });
comp.VerifyEmitDiagnostics(
// (4,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor.
// record R(R x) : Base; // 1
Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R").WithLocation(4, 8),
// (6,30): error CS0121: The call is ambiguous between the following methods or properties: 'R.R(R)' and 'R.R(R)'
// record Derived(Derived y) : R(y) // 2
Diagnostic(ErrorCode.ERR_AmbigCall, "(y)").WithArguments("R.R(R)", "R.R(R)").WithLocation(6, 30),
// (8,12): error CS0111: Type 'Derived' already defines a member called 'Derived' with the same parameter types
// public Derived(Derived y) : base(y) => throw null; // 3, 4, 5
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Derived").WithArguments("Derived", "Derived").WithLocation(8, 12),
// (8,33): error CS0121: The call is ambiguous between the following methods or properties: 'R.R(R)' and 'R.R(R)'
// public Derived(Derived y) : base(y) => throw null; // 3, 4, 5
Diagnostic(ErrorCode.ERR_AmbigCall, "base").WithArguments("R.R(R)", "R.R(R)").WithLocation(8, 33),
// (8,33): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object.
// public Derived(Derived y) : base(y) => throw null; // 3, 4, 5
Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "base").WithLocation(8, 33),
// (11,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor.
// record Derived2(Derived2 y) : R(y); // 6, 7, 8
Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "Derived2").WithLocation(11, 8),
// (11,8): error CS8867: No accessible copy constructor found in base type 'R'.
// record Derived2(Derived2 y) : R(y); // 6, 7, 8
Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "Derived2").WithArguments("R").WithLocation(11, 8),
// (11,32): error CS0121: The call is ambiguous between the following methods or properties: 'R.R(R)' and 'R.R(R)'
// record Derived2(Derived2 y) : R(y); // 6, 7, 8
Diagnostic(ErrorCode.ERR_AmbigCall, "(y)").WithArguments("R.R(R)", "R.R(R)").WithLocation(11, 32),
// (15,12): error CS0111: Type 'R2' already defines a member called 'R2' with the same parameter types
// public R2(R2 x) => throw null; // 9, 10
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "R2").WithArguments("R2", "R2").WithLocation(15, 12),
// (15,12): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object.
// public R2(R2 x) => throw null; // 9, 10
Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "R2").WithLocation(15, 12),
// (20,12): error CS0111: Type 'R3' already defines a member called 'R3' with the same parameter types
// public R3(R3 x) : base(x) => throw null; // 11
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "R3").WithArguments("R3", "R3").WithLocation(20, 12)
);
}
[Fact, WorkItem(49628, "https://github.com/dotnet/roslyn/issues/49628")]
public void AmbigCtor_WithPropertyInitializer()
{
var src = @"
record R(R X)
{
public R X { get; init; } = X;
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (2,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor.
// record R(R X)
Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R").WithLocation(2, 8)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree, ignoreAccessibility: false);
var parameterSyntax = tree.GetRoot().DescendantNodes().OfType<ParameterSyntax>().Single();
var parameter = model.GetDeclaredSymbol(parameterSyntax)!;
Assert.Equal("R X", parameter.ToTestDisplayString());
Assert.Equal(SymbolKind.Parameter, parameter.Kind);
Assert.Equal("R..ctor(R X)", parameter.ContainingSymbol.ToTestDisplayString());
var initializerSyntax = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Single();
var initializer = model.GetSymbolInfo(initializerSyntax.Value).Symbol!;
Assert.Equal("R X", initializer.ToTestDisplayString());
Assert.Equal(SymbolKind.Parameter, initializer.Kind);
Assert.Equal("R..ctor(R X)", initializer.ContainingSymbol.ToTestDisplayString());
}
[Fact]
public void GetDeclaredSymbolOnAnOutLocalInPropertyInitializer()
{
var src = @"
record R(int I)
{
public int I { get; init; } = M(out int i) ? i : 0;
static bool M(out int i) => throw null;
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (2,14): warning CS8907: Parameter 'I' is unread. Did you forget to use it to initialize the property with that name?
// record R(int I)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "I").WithArguments("I").WithLocation(2, 14)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree, ignoreAccessibility: false);
var outVarSyntax = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Single();
var outVar = model.GetDeclaredSymbol(outVarSyntax)!;
Assert.Equal("System.Int32 i", outVar.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, outVar.Kind);
Assert.Equal("System.Int32 R.<I>k__BackingField", outVar.ContainingSymbol.ToTestDisplayString());
}
[Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")]
public void IncompletePositionalRecord()
{
string source = @"
public record A(int i,) { }
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (2,23): error CS1031: Type expected
// public record A(int i,) { }
Diagnostic(ErrorCode.ERR_TypeExpected, ")").WithLocation(2, 23),
// (2,23): error CS1001: Identifier expected
// public record A(int i,) { }
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(2, 23)
);
var expectedMembers = new[]
{
"System.Type A.EqualityContract { get; }",
"System.Int32 A.i { get; init; }",
"? A. { get; init; }"
};
AssertEx.Equal(expectedMembers,
comp.GetMember<NamedTypeSymbol>("A").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings());
AssertEx.Equal(new[] { "A..ctor(System.Int32 i, ?)", "A..ctor(A original)" },
comp.GetMember<NamedTypeSymbol>("A").Constructors.ToTestDisplayStrings());
var primaryCtor = comp.GetMember<NamedTypeSymbol>("A").Constructors.First();
Assert.Equal("A..ctor(System.Int32 i, ?)", primaryCtor.ToTestDisplayString());
Assert.IsType<ParameterSyntax>(primaryCtor.Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax());
}
[Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")]
public void IncompletePositionalRecord_WithTrivia()
{
string source = @"
public record A(int i, // A
// B
, /* C */ ) { }
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (2,23): error CS1031: Type expected
// public record A(int i, // A
Diagnostic(ErrorCode.ERR_TypeExpected, "").WithLocation(2, 23),
// (2,23): error CS1001: Identifier expected
// public record A(int i, // A
Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(2, 23),
// (4,15): error CS1031: Type expected
// , /* C */ ) { }
Diagnostic(ErrorCode.ERR_TypeExpected, ")").WithLocation(4, 15),
// (4,15): error CS1001: Identifier expected
// , /* C */ ) { }
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(4, 15),
// (4,15): error CS0102: The type 'A' already contains a definition for ''
// , /* C */ ) { }
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("A", "").WithLocation(4, 15)
);
var primaryCtor = comp.GetMember<NamedTypeSymbol>("A").Constructors.First();
Assert.Equal("A..ctor(System.Int32 i, ?, ?)", primaryCtor.ToTestDisplayString());
Assert.IsType<ParameterSyntax>(primaryCtor.Parameters[0].DeclaringSyntaxReferences.Single().GetSyntax());
Assert.IsType<ParameterSyntax>(primaryCtor.Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax());
Assert.IsType<ParameterSyntax>(primaryCtor.Parameters[2].DeclaringSyntaxReferences.Single().GetSyntax());
}
[Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")]
public void IncompleteConstructor()
{
string source = @"
public class C
{
C(int i, ) { }
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (4,14): error CS1031: Type expected
// C(int i, ) { }
Diagnostic(ErrorCode.ERR_TypeExpected, ")").WithLocation(4, 14),
// (4,14): error CS1001: Identifier expected
// C(int i, ) { }
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(4, 14)
);
var ctor = comp.GetMember<NamedTypeSymbol>("C").Constructors.Single();
Assert.Equal("C..ctor(System.Int32 i, ?)", ctor.ToTestDisplayString());
Assert.IsType<ParameterSyntax>(ctor.Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax());
Assert.Equal(0, ctor.Parameters[1].Locations.Single().SourceSpan.Length);
}
[Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")]
public void IncompletePositionalRecord_WithType()
{
string source = @"
public record A(int i, int ) { }
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (2,28): error CS1001: Identifier expected
// public record A(int i, int ) { }
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(2, 28)
);
var expectedMembers = new[]
{
"System.Type A.EqualityContract { get; }",
"System.Int32 A.i { get; init; }",
"System.Int32 A. { get; init; }"
};
AssertEx.Equal(expectedMembers,
comp.GetMember<NamedTypeSymbol>("A").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings());
var ctor = comp.GetMember<NamedTypeSymbol>("A").Constructors[0];
Assert.Equal("A..ctor(System.Int32 i, System.Int32)", ctor.ToTestDisplayString());
Assert.IsType<ParameterSyntax>(ctor.Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax());
Assert.Equal(0, ctor.Parameters[1].Locations.Single().SourceSpan.Length);
}
[Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")]
public void IncompletePositionalRecord_WithTwoTypes()
{
string source = @"
public record A(int, string ) { }
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (2,20): error CS1001: Identifier expected
// public record A(int, string ) { }
Diagnostic(ErrorCode.ERR_IdentifierExpected, ",").WithLocation(2, 20),
// (2,29): error CS1001: Identifier expected
// public record A(int, string ) { }
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(2, 29),
// (2,29): error CS0102: The type 'A' already contains a definition for ''
// public record A(int, string ) { }
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("A", "").WithLocation(2, 29)
);
var expectedMembers = new[]
{
"System.Type A.EqualityContract { get; }",
"System.Int32 A. { get; init; }",
"System.String A. { get; init; }"
};
AssertEx.Equal(expectedMembers,
comp.GetMember<NamedTypeSymbol>("A").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings());
AssertEx.Equal(new[] { "A..ctor(System.Int32, System.String)", "A..ctor(A original)" },
comp.GetMember<NamedTypeSymbol>("A").Constructors.ToTestDisplayStrings());
Assert.IsType<ParameterSyntax>(comp.GetMember<NamedTypeSymbol>("A").Constructors[0].Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax());
}
[Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")]
public void IncompletePositionalRecord_WithTwoTypes_SameType()
{
string source = @"
public record A(int, int ) { }
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (2,20): error CS1001: Identifier expected
// public record A(int, int ) { }
Diagnostic(ErrorCode.ERR_IdentifierExpected, ",").WithLocation(2, 20),
// (2,26): error CS1001: Identifier expected
// public record A(int, int ) { }
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(2, 26),
// (2,26): error CS0102: The type 'A' already contains a definition for ''
// public record A(int, int ) { }
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("A", "").WithLocation(2, 26)
);
var expectedMembers = new[]
{
"System.Type A.EqualityContract { get; }",
"System.Int32 A. { get; init; }",
"System.Int32 A. { get; init; }"
};
AssertEx.Equal(expectedMembers,
comp.GetMember<NamedTypeSymbol>("A").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings());
AssertEx.Equal(new[] { "A..ctor(System.Int32, System.Int32)", "A..ctor(A original)" },
comp.GetMember<NamedTypeSymbol>("A").Constructors.ToTestDisplayStrings());
Assert.IsType<ParameterSyntax>(comp.GetMember<NamedTypeSymbol>("A").Constructors[0].Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax());
}
[Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")]
public void IncompletePositionalRecord_WithTwoTypes_WithTrivia()
{
string source = @"
public record A(int // A
// B
, int /* C */) { }
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (2,20): error CS1001: Identifier expected
// public record A(int // A
Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(2, 20),
// (4,18): error CS1001: Identifier expected
// , int /* C */) { }
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(4, 18),
// (4,18): error CS0102: The type 'A' already contains a definition for ''
// , int /* C */) { }
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("A", "").WithLocation(4, 18)
);
var ctor = comp.GetMember<NamedTypeSymbol>("A").Constructors[0];
Assert.IsType<ParameterSyntax>(ctor.Parameters[0].DeclaringSyntaxReferences.Single().GetSyntax());
Assert.IsType<ParameterSyntax>(ctor.Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax());
}
[Fact, WorkItem(46083, "https://github.com/dotnet/roslyn/issues/46083")]
public void IncompletePositionalRecord_SingleParameter()
{
string source = @"
record A(x)
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (2,10): error CS0246: The type or namespace name 'x' could not be found (are you missing a using directive or an assembly reference?)
// record A(x)
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "x").WithArguments("x").WithLocation(2, 10),
// (2,11): error CS1001: Identifier expected
// record A(x)
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(2, 11),
// (2,12): error CS1514: { expected
// record A(x)
Diagnostic(ErrorCode.ERR_LbraceExpected, "").WithLocation(2, 12),
// (2,12): error CS1513: } expected
// record A(x)
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(2, 12)
);
}
[Fact]
public void TestWithInExpressionTree()
{
var source = @"
using System;
using System.Linq.Expressions;
public record C(int i)
{
public static void M()
{
Expression<Func<C, C>> expr = c => c with { i = 5 };
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,44): error CS8849: An expression tree may not contain a with-expression.
// Expression<Func<C, C>> expr = c => c with { i = 5 };
Diagnostic(ErrorCode.ERR_ExpressionTreeContainsWithExpression, "c with { i = 5 }").WithLocation(8, 44)
);
}
[Fact]
public void PartialRecord_MixedWithClass()
{
var src = @"
partial record C(int X, int Y)
{
}
partial class C
{
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (5,15): error CS0261: Partial declarations of 'C' must be all classes, all record classes, all structs, all record structs, or all interfaces
// partial class C
Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "C").WithArguments("C").WithLocation(5, 15)
);
}
[Fact]
public void PartialRecord_ParametersInScopeOfBothParts()
{
var src = @"
var c = new C(2);
System.Console.Write((c.P1, c.P2));
public partial record C(int X)
{
public int P1 { get; set; } = X;
}
public partial record C
{
public int P2 { get; set; } = X;
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
CompileAndVerify(comp, expectedOutput: "(2, 2)", verify: Verification.Skipped /* init-only */).VerifyDiagnostics();
}
[Fact]
public void PartialRecord_ParametersInScopeOfBothParts_RecordClass()
{
var src = @"
var c = new C(2);
System.Console.Write((c.P1, c.P2));
public partial record C(int X)
{
public int P1 { get; set; } = X;
}
public partial record class C
{
public int P2 { get; set; } = X;
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular10);
CompileAndVerify(comp, expectedOutput: "(2, 2)", verify: Verification.Skipped /* init-only */).VerifyDiagnostics();
}
[Fact]
public void PartialRecord_DuplicateMemberNames()
{
var src = @"
public partial record C(int X)
{
public void M(int i) { }
}
public partial record C
{
public void M(string s) { }
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition });
var expectedMemberNames = new string[]
{
".ctor",
"get_EqualityContract",
"EqualityContract",
"<X>k__BackingField",
"get_X",
"set_X",
"X",
"M",
"M",
"ToString",
"PrintMembers",
"op_Inequality",
"op_Equality",
"GetHashCode",
"Equals",
"Equals",
"<Clone>$",
".ctor",
"Deconstruct"
};
AssertEx.Equal(expectedMemberNames, comp.GetMember<NamedTypeSymbol>("C").GetPublicSymbol().MemberNames);
}
[Fact]
public void RecordInsideGenericType()
{
var src = @"
var c = new C<int>.Nested(2);
System.Console.Write(c.T);
public class C<T>
{
public record Nested(T T);
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "2", verify: Verification.Skipped /* init-only */);
}
[Fact]
public void RecordProperties_01()
{
var src = @"
using System;
record C(int X, int Y)
{
int Z = 123;
public static void Main()
{
var c = new C(1, 2);
Console.WriteLine(c.X);
Console.WriteLine(c.Y);
Console.WriteLine(c.Z);
}
}";
var verifier = CompileAndVerify(src, expectedOutput: @"
1
2
123").VerifyDiagnostics();
verifier.VerifyIL("C..ctor(int, int)", @"
{
// Code size 29 (0x1d)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld ""int C.<X>k__BackingField""
IL_0007: ldarg.0
IL_0008: ldarg.2
IL_0009: stfld ""int C.<Y>k__BackingField""
IL_000e: ldarg.0
IL_000f: ldc.i4.s 123
IL_0011: stfld ""int C.Z""
IL_0016: ldarg.0
IL_0017: call ""object..ctor()""
IL_001c: ret
}
");
var c = verifier.Compilation.GlobalNamespace.GetTypeMember("C");
var x = (IPropertySymbol)c.GetMember("X");
Assert.Equal("System.Int32 C.X.get", x.GetMethod.ToTestDisplayString());
Assert.Equal("void modreq(System.Runtime.CompilerServices.IsExternalInit) C.X.init", x.SetMethod.ToTestDisplayString());
Assert.True(x.SetMethod!.IsInitOnly);
var xBackingField = (IFieldSymbol)c.GetMember("<X>k__BackingField");
Assert.Equal("System.Int32 C.<X>k__BackingField", xBackingField.ToTestDisplayString());
Assert.True(xBackingField.IsReadOnly);
}
[Fact]
public void RecordProperties_02()
{
var src = @"
using System;
record C(int X, int Y)
{
public C(int a, int b)
{
}
public static void Main()
{
var c = new C(1, 2);
Console.WriteLine(c.X);
Console.WriteLine(c.Y);
}
private int X1 = X;
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (5,12): error CS0111: Type 'C' already defines a member called 'C' with the same parameter types
// public C(int a, int b)
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments("C", "C").WithLocation(5, 12),
// (5,12): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer.
// public C(int a, int b)
Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "C").WithLocation(5, 12),
// (11,21): error CS0121: The call is ambiguous between the following methods or properties: 'C.C(int, int)' and 'C.C(int, int)'
// var c = new C(1, 2);
Diagnostic(ErrorCode.ERR_AmbigCall, "C").WithArguments("C.C(int, int)", "C.C(int, int)").WithLocation(11, 21)
);
}
[Fact]
public void RecordProperties_03()
{
var src = @"
using System;
record C(int X, int Y)
{
public int X { get; }
public static void Main()
{
var c = new C(1, 2);
Console.WriteLine(c.X);
Console.WriteLine(c.Y);
}
}";
CompileAndVerify(src, expectedOutput: @"
0
2").VerifyDiagnostics(
// (3,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X, int Y)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 14)
);
}
[Fact]
public void RecordProperties_04()
{
var src = @"
using System;
record C(int X, int Y)
{
public int X { get; } = 3;
public static void Main()
{
var c = new C(1, 2);
Console.WriteLine(c.X);
Console.WriteLine(c.Y);
}
}";
CompileAndVerify(src, expectedOutput: @"
3
2").VerifyDiagnostics(
// (3,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X, int Y)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 14)
);
}
[Fact, WorkItem(48947, "https://github.com/dotnet/roslyn/issues/48947")]
public void RecordProperties_05()
{
var src = @"
record C(int X, int X)
{
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (2,21): error CS0100: The parameter name 'X' is a duplicate
// record C(int X, int X)
Diagnostic(ErrorCode.ERR_DuplicateParamName, "X").WithArguments("X").WithLocation(2, 21),
// (2,21): error CS0102: The type 'C' already contains a definition for 'X'
// record C(int X, int X)
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("C", "X").WithLocation(2, 21)
);
var expectedMembers = new[]
{
"System.Type C.EqualityContract { get; }",
"System.Int32 C.X { get; init; }",
"System.Int32 C.X { get; init; }"
};
AssertEx.Equal(expectedMembers,
comp.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings());
var expectedMemberNames = new[] {
".ctor",
"get_EqualityContract",
"EqualityContract",
"<X>k__BackingField",
"get_X",
"set_X",
"X",
"<X>k__BackingField",
"get_X",
"set_X",
"X",
"ToString",
"PrintMembers",
"op_Inequality",
"op_Equality",
"GetHashCode",
"Equals",
"Equals",
"<Clone>$",
".ctor",
"Deconstruct"
};
AssertEx.Equal(expectedMemberNames, comp.GetMember<NamedTypeSymbol>("C").GetPublicSymbol().MemberNames);
}
[Fact]
public void RecordProperties_05_RecordClass()
{
var src = @"
record class C(int X, int X)
{
}";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10);
comp.VerifyDiagnostics(
// (2,27): error CS0100: The parameter name 'X' is a duplicate
// record class C(int X, int X)
Diagnostic(ErrorCode.ERR_DuplicateParamName, "X").WithArguments("X").WithLocation(2, 27),
// (2,27): error CS0102: The type 'C' already contains a definition for 'X'
// record class C(int X, int X)
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("C", "X").WithLocation(2, 27)
);
var expectedMembers = new[]
{
"System.Type C.EqualityContract { get; }",
"System.Int32 C.X { get; init; }",
"System.Int32 C.X { get; init; }"
};
AssertEx.Equal(expectedMembers,
comp.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings());
var expectedMemberNames = new[] {
".ctor",
"get_EqualityContract",
"EqualityContract",
"<X>k__BackingField",
"get_X",
"set_X",
"X",
"<X>k__BackingField",
"get_X",
"set_X",
"X",
"ToString",
"PrintMembers",
"op_Inequality",
"op_Equality",
"GetHashCode",
"Equals",
"Equals",
"<Clone>$",
".ctor",
"Deconstruct"
};
AssertEx.Equal(expectedMemberNames, comp.GetMember<NamedTypeSymbol>("C").GetPublicSymbol().MemberNames);
}
[Fact]
public void RecordProperties_06()
{
var src = @"
record C(int X, int Y)
{
public void get_X() { }
public void set_X() { }
int get_Y(int value) => value;
int set_Y(int value) => value;
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (2,14): error CS0082: Type 'C' already reserves a member called 'get_X' with the same parameter types
// record C(int X, int Y)
Diagnostic(ErrorCode.ERR_MemberReserved, "X").WithArguments("get_X", "C").WithLocation(2, 14),
// (2,21): error CS0082: Type 'C' already reserves a member called 'set_Y' with the same parameter types
// record C(int X, int Y)
Diagnostic(ErrorCode.ERR_MemberReserved, "Y").WithArguments("set_Y", "C").WithLocation(2, 21));
var actualMembers = comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings();
var expectedMembers = new[]
{
"C..ctor(System.Int32 X, System.Int32 Y)",
"System.Type C.EqualityContract.get",
"System.Type C.EqualityContract { get; }",
"System.Int32 C.<X>k__BackingField",
"System.Int32 C.X.get",
"void modreq(System.Runtime.CompilerServices.IsExternalInit) C.X.init",
"System.Int32 C.X { get; init; }",
"System.Int32 C.<Y>k__BackingField",
"System.Int32 C.Y.get",
"void modreq(System.Runtime.CompilerServices.IsExternalInit) C.Y.init",
"System.Int32 C.Y { get; init; }",
"void C.get_X()",
"void C.set_X()",
"System.Int32 C.get_Y(System.Int32 value)",
"System.Int32 C.set_Y(System.Int32 value)",
"System.String C.ToString()",
"System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)",
"System.Boolean C.op_Inequality(C? left, C? right)",
"System.Boolean C.op_Equality(C? left, C? right)",
"System.Int32 C.GetHashCode()",
"System.Boolean C.Equals(System.Object? obj)",
"System.Boolean C.Equals(C? other)",
"C C." + WellKnownMemberNames.CloneMethodName + "()",
"C..ctor(C original)",
"void C.Deconstruct(out System.Int32 X, out System.Int32 Y)"
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void RecordProperties_07()
{
var comp = CreateCompilation(@"
record C1(object P, object get_P);
record C2(object get_P, object P);");
comp.VerifyDiagnostics(
// (2,18): error CS0102: The type 'C1' already contains a definition for 'get_P'
// record C1(object P, object get_P);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C1", "get_P").WithLocation(2, 18),
// (3,32): error CS0102: The type 'C2' already contains a definition for 'get_P'
// record C2(object get_P, object P);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C2", "get_P").WithLocation(3, 32)
);
}
[Fact]
public void RecordProperties_08()
{
var comp = CreateCompilation(@"
record C1(object O1)
{
public object O1 { get; } = O1;
public object O2 { get; } = O1;
}");
comp.VerifyDiagnostics();
}
[Fact]
public void RecordProperties_09()
{
var src =
@"record C(object P1, object P2, object P3, object P4)
{
class P1 { }
object P2 = 2;
int P3(object o) => 3;
int P4<T>(T t) => 4;
}";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (1,17): error CS0102: The type 'C' already contains a definition for 'P1'
// record C(object P1, object P2, object P3, object P4)
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P1").WithArguments("C", "P1").WithLocation(1, 17),
// (1,21): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater.
// record C(object P1, object P2, object P3, object P4)
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object P2").WithArguments("positional fields in records", "10.0").WithLocation(1, 21),
// (1,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, object P2, object P3, object P4)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 28),
// (5,9): error CS0102: The type 'C' already contains a definition for 'P3'
// int P3(object o) => 3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P3").WithArguments("C", "P3").WithLocation(5, 9),
// (6,9): error CS0102: The type 'C' already contains a definition for 'P4'
// int P4<T>(T t) => 4;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P4").WithArguments("C", "P4").WithLocation(6, 9)
);
comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10);
comp.VerifyDiagnostics(
// (1,17): error CS0102: The type 'C' already contains a definition for 'P1'
// record C(object P1, object P2, object P3, object P4)
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P1").WithArguments("C", "P1").WithLocation(1, 17),
// (1,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, object P2, object P3, object P4)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 28),
// (5,9): error CS0102: The type 'C' already contains a definition for 'P3'
// int P3(object o) => 3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P3").WithArguments("C", "P3").WithLocation(5, 9),
// (6,9): error CS0102: The type 'C' already contains a definition for 'P4'
// int P4<T>(T t) => 4;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P4").WithArguments("C", "P4").WithLocation(6, 9)
);
}
[ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)]
[WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")]
public void RestrictedTypesAndPointerTypes()
{
var src = @"
class C<T> { }
static class C2 { }
ref struct RefLike{}
unsafe record C( // 1
int* P1, // 2
int*[] P2, // 3
C<int*[]> P3,
delegate*<int, int> P4, // 4
void P5, // 5
C2 P6, // 6, 7
System.ArgIterator P7, // 8
System.TypedReference P8, // 9
RefLike P9); // 10
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugDll);
comp.VerifyEmitDiagnostics(
// (6,15): error CS0721: 'C2': static types cannot be used as parameters
// unsafe record C( // 1
Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "C").WithArguments("C2").WithLocation(6, 15),
// (7,10): error CS8908: The type 'int*' may not be used for a field of a record.
// int* P1, // 2
Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P1").WithArguments("int*").WithLocation(7, 10),
// (8,12): error CS8908: The type 'int*[]' may not be used for a field of a record.
// int*[] P2, // 3
Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P2").WithArguments("int*[]").WithLocation(8, 12),
// (10,25): error CS8908: The type 'delegate*<int, int>' may not be used for a field of a record.
// delegate*<int, int> P4, // 4
Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P4").WithArguments("delegate*<int, int>").WithLocation(10, 25),
// (11,5): error CS1536: Invalid parameter type 'void'
// void P5, // 5
Diagnostic(ErrorCode.ERR_NoVoidParameter, "void").WithLocation(11, 5),
// (12,8): error CS0722: 'C2': static types cannot be used as return types
// C2 P6, // 6, 7
Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "P6").WithArguments("C2").WithLocation(12, 8),
// (12,8): error CS0721: 'C2': static types cannot be used as parameters
// C2 P6, // 6, 7
Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "P6").WithArguments("C2").WithLocation(12, 8),
// (13,5): error CS0610: Field or property cannot be of type 'ArgIterator'
// System.ArgIterator P7, // 8
Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(13, 5),
// (14,5): error CS0610: Field or property cannot be of type 'TypedReference'
// System.TypedReference P8, // 9
Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(14, 5),
// (15,5): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct.
// RefLike P9); // 10
Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(15, 5)
);
}
[ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)]
[WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")]
public void RestrictedTypesAndPointerTypes_NominalMembers()
{
var src = @"
public class C<T> { }
public static class C2 { }
public ref struct RefLike{}
public unsafe record C
{
public int* f1; // 1
public int*[] f2; // 2
public C<int*[]> f3;
public delegate*<int, int> f4; // 3
public void f5; // 4
public C2 f6; // 5
public System.ArgIterator f7; // 6
public System.TypedReference f8; // 7
public RefLike f9; // 8
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugDll);
comp.VerifyEmitDiagnostics(
// (8,17): error CS8908: The type 'int*' may not be used for a field of a record.
// public int* f1; // 1
Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f1").WithArguments("int*").WithLocation(8, 17),
// (9,19): error CS8908: The type 'int*[]' may not be used for a field of a record.
// public int*[] f2; // 2
Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f2").WithArguments("int*[]").WithLocation(9, 19),
// (11,32): error CS8908: The type 'delegate*<int, int>' may not be used for a field of a record.
// public delegate*<int, int> f4; // 3
Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f4").WithArguments("delegate*<int, int>").WithLocation(11, 32),
// (12,12): error CS0670: Field cannot have void type
// public void f5; // 4
Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void").WithLocation(12, 12),
// (13,15): error CS0723: Cannot declare a variable of static type 'C2'
// public C2 f6; // 5
Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "f6").WithArguments("C2").WithLocation(13, 15),
// (14,12): error CS0610: Field or property cannot be of type 'ArgIterator'
// public System.ArgIterator f7; // 6
Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(14, 12),
// (15,12): error CS0610: Field or property cannot be of type 'TypedReference'
// public System.TypedReference f8; // 7
Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(15, 12),
// (16,12): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct.
// public RefLike f9; // 8
Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(16, 12)
);
}
[ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)]
[WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")]
public void RestrictedTypesAndPointerTypes_NominalMembers_AutoProperties()
{
var src = @"
public class C<T> { }
public static class C2 { }
public ref struct RefLike{}
public unsafe record C
{
public int* f1 { get; set; } // 1
public int*[] f2 { get; set; } // 2
public C<int*[]> f3 { get; set; }
public delegate*<int, int> f4 { get; set; } // 3
public void f5 { get; set; } // 4
public C2 f6 { get; set; } // 5, 6
public System.ArgIterator f7 { get; set; } // 6
public System.TypedReference f8 { get; set; } // 7
public RefLike f9 { get; set; } // 8
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugDll);
comp.VerifyEmitDiagnostics(
// (8,17): error CS8908: The type 'int*' may not be used for a field of a record.
// public int* f1 { get; set; } // 1
Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f1").WithArguments("int*").WithLocation(8, 17),
// (9,19): error CS8908: The type 'int*[]' may not be used for a field of a record.
// public int*[] f2 { get; set; } // 2
Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f2").WithArguments("int*[]").WithLocation(9, 19),
// (11,32): error CS8908: The type 'delegate*<int, int>' may not be used for a field of a record.
// public delegate*<int, int> f4 { get; set; } // 3
Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f4").WithArguments("delegate*<int, int>").WithLocation(11, 32),
// (12,17): error CS0547: 'C.f5': property or indexer cannot have void type
// public void f5 { get; set; } // 4
Diagnostic(ErrorCode.ERR_PropertyCantHaveVoidType, "f5").WithArguments("C.f5").WithLocation(12, 17),
// (13,20): error CS0722: 'C2': static types cannot be used as return types
// public C2 f6 { get; set; } // 5, 6
Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "get").WithArguments("C2").WithLocation(13, 20),
// (13,25): error CS0721: 'C2': static types cannot be used as parameters
// public C2 f6 { get; set; } // 5, 6
Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "set").WithArguments("C2").WithLocation(13, 25),
// (14,12): error CS0610: Field or property cannot be of type 'ArgIterator'
// public System.ArgIterator f7 { get; set; } // 6
Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(14, 12),
// (15,12): error CS0610: Field or property cannot be of type 'TypedReference'
// public System.TypedReference f8 { get; set; } // 7
Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(15, 12),
// (16,12): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct.
// public RefLike f9 { get; set; } // 8
Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(16, 12)
);
}
[Fact]
[WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")]
public void RestrictedTypesAndPointerTypes_PointerTypeAllowedForParameterAndProperty()
{
var src = @"
class C<T> { }
unsafe record C(int* P1, int*[] P2, C<int*[]> P3)
{
int* P1
{
get { System.Console.Write(""P1 ""); return null; }
init { }
}
int*[] P2
{
get { System.Console.Write(""P2 ""); return null; }
init { }
}
C<int*[]> P3
{
get { System.Console.Write(""P3 ""); return null; }
init { }
}
public unsafe static void Main()
{
var x = new C(null, null, null);
var (x1, x2, x3) = x;
System.Console.Write(""RAN"");
}
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugExe);
comp.VerifyEmitDiagnostics(
// (4,22): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// unsafe record C(int* P1, int*[] P2, C<int*[]> P3)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(4, 22),
// (4,33): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// unsafe record C(int* P1, int*[] P2, C<int*[]> P3)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(4, 33),
// (4,47): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name?
// unsafe record C(int* P1, int*[] P2, C<int*[]> P3)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(4, 47)
);
CompileAndVerify(comp, expectedOutput: "P1 P2 P3 RAN", verify: Verification.Skipped /* pointers */);
}
[ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)]
[WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")]
public void RestrictedTypesAndPointerTypes_StaticFields()
{
var src = @"
public class C<T> { }
public static class C2 { }
public ref struct RefLike{}
public unsafe record C
{
public static int* f1;
public static int*[] f2;
public static C<int*[]> f3;
public static delegate*<int, int> f4;
public static C2 f6; // 1
public static System.ArgIterator f7; // 2
public static System.TypedReference f8; // 3
public static RefLike f9; // 4
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugDll);
comp.VerifyEmitDiagnostics(
// (12,22): error CS0723: Cannot declare a variable of static type 'C2'
// public static C2 f6; // 1
Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "f6").WithArguments("C2").WithLocation(12, 22),
// (13,19): error CS0610: Field or property cannot be of type 'ArgIterator'
// public static System.ArgIterator f7; // 2
Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(13, 19),
// (14,19): error CS0610: Field or property cannot be of type 'TypedReference'
// public static System.TypedReference f8; // 3
Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(14, 19),
// (15,19): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct.
// public static RefLike f9; // 4
Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(15, 19)
);
}
[Fact, WorkItem(48584, "https://github.com/dotnet/roslyn/issues/48584")]
public void RecordProperties_11_UnreadPositionalParameter()
{
var comp = CreateCompilation(@"
record C1(object O1, object O2, object O3) // 1, 2
{
public object O1 { get; init; }
public object O2 { get; init; } = M(O2);
public object O3 { get; init; } = M(O3 = null);
private static object M(object o) => o;
}
record Base(object O);
record C2(object O4) : Base(O4) // we didn't complain because the parameter is read
{
public object O4 { get; init; }
}
record C3(object O5) : Base((System.Func<object, object>)(x => x)) // 3
{
public object O5 { get; init; }
}
record C4(object O6) : Base((System.Func<object, object>)(_ => O6))
{
public object O6 { get; init; }
}
record C5(object O7) : Base((System.Func<object, object>)(_ => (O7 = 42) )) // 4
{
public object O7 { get; init; }
}
");
comp.VerifyDiagnostics(
// (2,18): warning CS8907: Parameter 'O1' is unread. Did you forget to use it to initialize the property with that name?
// record C1(object O1, object O2, object O3) // 1, 2
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O1").WithArguments("O1").WithLocation(2, 18),
// (2,40): warning CS8907: Parameter 'O3' is unread. Did you forget to use it to initialize the property with that name?
// record C1(object O1, object O2, object O3) // 1, 2
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O3").WithArguments("O3").WithLocation(2, 40),
// (16,18): warning CS8907: Parameter 'O5' is unread. Did you forget to use it to initialize the property with that name?
// record C3(object O5) : Base((System.Func<object, object>)(x => x)) // 3
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O5").WithArguments("O5").WithLocation(16, 18),
// (26,18): warning CS8907: Parameter 'O7' is unread. Did you forget to use it to initialize the property with that name?
// record C5(object O7) : Base((System.Func<object, object>)(_ => (O7 = 42) )) // 4
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O7").WithArguments("O7").WithLocation(26, 18)
);
}
[Fact, WorkItem(48584, "https://github.com/dotnet/roslyn/issues/48584")]
public void RecordProperties_11_UnreadPositionalParameter_InRefOut()
{
var comp = CreateCompilation(@"
record C1(object O1, object O2, object O3) // 1
{
public object O1 { get; init; } = MIn(in O1);
public object O2 { get; init; } = MRef(ref O2);
public object O3 { get; init; } = MOut(out O3);
static object MIn(in object o) => o;
static object MRef(ref object o) => o;
static object MOut(out object o) => throw null;
}
");
comp.VerifyDiagnostics(
// (2,40): warning CS8907: Parameter 'O3' is unread. Did you forget to use it to initialize the property with that name?
// record C1(object O1, object O2, object O3) // 1
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O3").WithArguments("O3").WithLocation(2, 40)
);
}
[Fact]
public void EmptyRecord_01()
{
var src = @"
record C();
class Program
{
static void Main()
{
var x = new C();
var y = new C();
System.Console.WriteLine(x == y);
}
}
";
var verifier = CompileAndVerify(src, expectedOutput: "True");
verifier.VerifyDiagnostics();
verifier.VerifyIL("C..ctor()", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ret
}
");
var comp = (CSharpCompilation)verifier.Compilation;
var actualMembers = comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings();
var expectedMembers = new[]
{
"C..ctor()",
"System.Type C.EqualityContract.get",
"System.Type C.EqualityContract { get; }",
"System.String C.ToString()",
"System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)",
"System.Boolean C.op_Inequality(C? left, C? right)",
"System.Boolean C.op_Equality(C? left, C? right)",
"System.Int32 C.GetHashCode()",
"System.Boolean C.Equals(System.Object? obj)",
"System.Boolean C.Equals(C? other)",
"C C." + WellKnownMemberNames.CloneMethodName + "()",
"C..ctor(C original)"
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void EmptyRecord_01_RecordClass()
{
var src = @"
record class C();
class Program
{
static void Main()
{
var x = new C();
var y = new C();
System.Console.WriteLine(x == y);
}
}
";
var verifier = CompileAndVerify(src, expectedOutput: "True", parseOptions: TestOptions.Regular10);
verifier.VerifyDiagnostics();
verifier.VerifyIL("C..ctor()", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ret
}
");
var comp = (CSharpCompilation)verifier.Compilation;
var actualMembers = comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings();
var expectedMembers = new[]
{
"C..ctor()",
"System.Type C.EqualityContract.get",
"System.Type C.EqualityContract { get; }",
"System.String C.ToString()",
"System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)",
"System.Boolean C.op_Inequality(C? left, C? right)",
"System.Boolean C.op_Equality(C? left, C? right)",
"System.Int32 C.GetHashCode()",
"System.Boolean C.Equals(System.Object? obj)",
"System.Boolean C.Equals(C? other)",
"C C." + WellKnownMemberNames.CloneMethodName + "()",
"C..ctor(C original)"
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void EmptyRecord_02()
{
var src = @"
record C()
{
C(int x)
{}
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (4,5): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer.
// C(int x)
Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "C", isSuppressed: false).WithLocation(4, 5)
);
}
[Fact]
public void EmptyRecord_03()
{
var src = @"
record B
{
public B(int x)
{
System.Console.WriteLine(x);
}
}
record C() : B(12)
{
C(int x) : this()
{}
}
class Program
{
static void Main()
{
_ = new C();
}
}
";
var verifier = CompileAndVerify(src, expectedOutput: "12");
verifier.VerifyDiagnostics();
verifier.VerifyIL("C..ctor()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 12
IL_0003: call ""B..ctor(int)""
IL_0008: ret
}
");
}
[Fact, WorkItem(50170, "https://github.com/dotnet/roslyn/issues/50170")]
public void StaticCtor()
{
var src = @"
record R(int x)
{
static void Main() { }
static R()
{
System.Console.Write(""static ctor"");
}
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
// [ : R::set_x] Cannot change initonly field outside its .ctor.
CompileAndVerify(comp, expectedOutput: "static ctor", verify: Verification.Skipped);
}
[Fact, WorkItem(50170, "https://github.com/dotnet/roslyn/issues/50170")]
public void StaticCtor_ParameterlessPrimaryCtor()
{
var src = @"
record R()
{
static R() { }
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics();
}
[Fact, WorkItem(50170, "https://github.com/dotnet/roslyn/issues/50170")]
public void StaticCtor_CopyCtor()
{
var src = @"
record R()
{
static R(R r) { }
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (4,12): error CS0132: 'R.R(R)': a static constructor must be parameterless
// static R(R r) { }
Diagnostic(ErrorCode.ERR_StaticConstParam, "R").WithArguments("R.R(R)").WithLocation(4, 12)
);
}
[Fact]
public void WithExpr1()
{
var src = @"
record C(int X)
{
public static void Main()
{
var c = new C(0);
_ = Main() with { };
_ = default with { };
_ = null with { };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (7,13): error CS8802: The receiver of a `with` expression must have a valid non-void type.
// _ = Main() with { };
Diagnostic(ErrorCode.ERR_InvalidWithReceiverType, "Main()").WithLocation(7, 13),
// (8,13): error CS8716: There is no target type for the default literal.
// _ = default with { };
Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(8, 13),
// (9,13): error CS8802: The receiver of a `with` expression must have a valid non-void type.
// _ = null with { };
Diagnostic(ErrorCode.ERR_InvalidWithReceiverType, "null").WithLocation(9, 13)
);
}
[Fact]
public void WithExpr2()
{
var src = @"
using System;
record C(int X)
{
public static void Main()
{
var c1 = new C(1);
c1 = c1 with { };
var c2 = c1 with { X = 11 };
Console.WriteLine(c1.X);
Console.WriteLine(c2.X);
}
}";
CompileAndVerify(src, expectedOutput: @"1
11").VerifyDiagnostics();
}
[Fact]
public void WithExpr3()
{
var src = @"
record C(int X)
{
public static void Main()
{
var c = new C(0);
c = c with { };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
var root = comp.SyntaxTrees[0].GetRoot();
var main = root.DescendantNodes().OfType<MethodDeclarationSyntax>().First();
Assert.Equal("Main", main.Identifier.ToString());
VerifyFlowGraph(comp, main, expectedFlowGraph: @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [C c]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'c = new C(0)')
Left:
ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C(0)')
Right:
IObjectCreationOperation (Constructor: C..ctor(System.Int32 X)) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C(0)')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: '0')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Initializer:
null
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = c with { };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: 'c = c with { }')
Left:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
Right:
IInvocationOperation (virtual C C." + WellKnownMemberNames.CloneMethodName + @"()) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'c with { }')
Instance Receiver:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
Arguments(0)
Next (Regular) Block[B2]
Leaving: {R1}
}
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
");
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")]
[WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")]
public void WithExpr4()
{
var src = @"
class B
{
public B Clone() => null;
}
record C(int X) : B
{
public static void Main()
{
var c = new C(0);
c = c with { };
}
public new C Clone() => null;
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact]
public void WithExpr6()
{
var src = @"
record B
{
public int X { get; init; }
}
record C : B
{
public static void Main()
{
var c = new C();
c = c with { };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact]
public void WithExpr7()
{
var src = @"
record B
{
public int X { get; }
}
record C : B
{
public new int X { get; init; }
public static void Main()
{
var c = new C();
B b = c;
b = b with { X = 0 };
var b2 = c with { X = 0 };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (14,22): error CS0200: Property or indexer 'B.X' cannot be assigned to -- it is read only
// b = b with { X = 0 };
Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "X").WithArguments("B.X").WithLocation(14, 22)
);
}
[Fact]
public void WithExpr8()
{
var src = @"
record B
{
public int X { get; }
}
record C : B
{
public string Y { get; }
public static void Main()
{
var c = new C();
B b = c;
b = b with { };
b = c with { };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact]
public void WithExpr9()
{
var src = @"
record C(int X)
{
public string Clone() => null;
public static void Main()
{
var c = new C(0);
c = c with { };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (4,19): error CS8859: Members named 'Clone' are disallowed in records.
// public string Clone() => null;
Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(4, 19)
);
}
[Fact]
public void WithExpr11()
{
var src = @"
record C(int X)
{
public static void Main()
{
var c = new C(0);
c = c with { X = """"};
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (8,26): error CS0029: Cannot implicitly convert type 'string' to 'int'
// c = c with { X = ""};
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""""").WithArguments("string", "int").WithLocation(8, 26)
);
}
[Fact]
public void WithExpr12()
{
var src = @"
using System;
record C(int X)
{
public static void Main()
{
var c = new C(0);
Console.WriteLine(c.X);
c = c with { X = 5 };
Console.WriteLine(c.X);
}
}";
var verifier = CompileAndVerify(src, expectedOutput: @"0
5").VerifyDiagnostics();
verifier.VerifyIL("C.Main", @"
{
// Code size 40 (0x28)
.maxstack 3
IL_0000: ldc.i4.0
IL_0001: newobj ""C..ctor(int)""
IL_0006: dup
IL_0007: callvirt ""int C.X.get""
IL_000c: call ""void System.Console.WriteLine(int)""
IL_0011: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()""
IL_0016: dup
IL_0017: ldc.i4.5
IL_0018: callvirt ""void C.X.init""
IL_001d: callvirt ""int C.X.get""
IL_0022: call ""void System.Console.WriteLine(int)""
IL_0027: ret
}");
}
[Fact]
public void WithExpr13()
{
var src = @"
using System;
record C(int X, int Y)
{
public override string ToString() => X + "" "" + Y;
public static void Main()
{
var c = new C(0, 1);
Console.WriteLine(c);
c = c with { X = 5 };
Console.WriteLine(c);
}
}";
var verifier = CompileAndVerify(src, expectedOutput: @"0 1
5 1").VerifyDiagnostics();
verifier.VerifyIL("C.Main", @"
{
// Code size 31 (0x1f)
.maxstack 3
IL_0000: ldc.i4.0
IL_0001: ldc.i4.1
IL_0002: newobj ""C..ctor(int, int)""
IL_0007: dup
IL_0008: call ""void System.Console.WriteLine(object)""
IL_000d: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()""
IL_0012: dup
IL_0013: ldc.i4.5
IL_0014: callvirt ""void C.X.init""
IL_0019: call ""void System.Console.WriteLine(object)""
IL_001e: ret
}");
}
[Fact]
public void WithExpr14()
{
var src = @"
using System;
record C(int X, int Y)
{
public override string ToString() => X + "" "" + Y;
public static void Main()
{
var c = new C(0, 1);
Console.WriteLine(c);
c = c with { X = 5 };
Console.WriteLine(c);
c = c with { Y = 2 };
Console.WriteLine(c);
}
}";
var verifier = CompileAndVerify(src, expectedOutput: @"0 1
5 1
5 2").VerifyDiagnostics();
verifier.VerifyIL("C.Main", @"
{
// Code size 49 (0x31)
.maxstack 3
IL_0000: ldc.i4.0
IL_0001: ldc.i4.1
IL_0002: newobj ""C..ctor(int, int)""
IL_0007: dup
IL_0008: call ""void System.Console.WriteLine(object)""
IL_000d: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()""
IL_0012: dup
IL_0013: ldc.i4.5
IL_0014: callvirt ""void C.X.init""
IL_0019: dup
IL_001a: call ""void System.Console.WriteLine(object)""
IL_001f: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()""
IL_0024: dup
IL_0025: ldc.i4.2
IL_0026: callvirt ""void C.Y.init""
IL_002b: call ""void System.Console.WriteLine(object)""
IL_0030: ret
}");
}
[Fact]
public void WithExpr15()
{
var src = @"
record C(int X, int Y)
{
public static void Main()
{
var c = new C(0, 0);
c = c with { = 5 };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (8,22): error CS1525: Invalid expression term '='
// c = c with { = 5 };
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "=").WithArguments("=").WithLocation(8, 22)
);
}
[Fact]
public void WithExpr16()
{
var src = @"
record C(int X, int Y)
{
public static void Main()
{
var c = new C(0, 0);
c = c with { X = };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (8,26): error CS1525: Invalid expression term '}'
// c = c with { X = };
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "}").WithArguments("}").WithLocation(8, 26)
);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")]
[WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")]
public void WithExpr17()
{
var src = @"
record B
{
public int X { get; }
private B Clone() => null;
}
record C(int X) : B
{
public static void Main()
{
var b = new B();
b = b with { };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (12,13): error CS8803: The 'with' expression requires the receiver type 'B' to have a single accessible non-inherited instance method named "Clone".
// b = b with { };
Diagnostic(ErrorCode.ERR_CannotClone, "b").WithArguments("B").WithLocation(12, 13)
);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")]
[WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")]
public void WithExpr18()
{
var src = @"
class B
{
public int X { get; }
protected B Clone() => null;
}
record C(int X) : B
{
public static void Main()
{
var b = new B();
b = b with { };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (12,13): error CS8803: The receiver type 'B' does not have an accessible parameterless instance method named "Clone".
// b = b with { };
Diagnostic(ErrorCode.ERR_CannotClone, "b").WithArguments("B").WithLocation(12, 13)
);
}
[Fact]
public void WithExpr19()
{
var src = @"
class B
{
public int X { get; }
protected B Clone() => null;
}
record C(int X)
{
public static void Main()
{
var b = new B();
b = b with { };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (12,13): error CS8803: The 'with' expression requires the receiver type 'B' to have a single accessible non-inherited instance method named "Clone".
// b = b with { };
Diagnostic(ErrorCode.ERR_CannotClone, "b").WithArguments("B").WithLocation(12, 13)
);
}
[Fact]
public void WithExpr20()
{
var src = @"
using System;
record C
{
public event Action X;
public static void Main()
{
var c = new C();
c = c with { X = null };
}
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (5,25): warning CS0067: The event 'C.X' is never used
// public event Action X;
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "X").WithArguments("C.X").WithLocation(5, 25)
);
}
[Fact]
public void WithExpr21()
{
var src = @"
record B
{
public class X { }
}
class C
{
public static void Main()
{
var b = new B();
b = b with { X = 0 };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (11,22): error CS0572: 'X': cannot reference a type through an expression; try 'B.X' instead
// b = b with { X = 0 };
Diagnostic(ErrorCode.ERR_BadTypeReference, "X").WithArguments("X", "B.X").WithLocation(11, 22),
// (11,22): error CS1913: Member 'X' cannot be initialized. It is not a field or property.
// b = b with { X = 0 };
Diagnostic(ErrorCode.ERR_MemberCannotBeInitialized, "X").WithArguments("X").WithLocation(11, 22)
);
}
[Fact]
public void WithExpr22()
{
var src = @"
record B
{
public int X = 0;
}
class C
{
public static void Main()
{
var b = new B();
b = b with { };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact]
public void WithExpr23()
{
var src = @"
class B
{
public int X = 0;
public B Clone() => null;
}
record C(int X)
{
public static void Main()
{
var b = new B();
b = b with { Y = 2 };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (12,13): error CS8858: The receiver type 'B' is not a valid record type.
// b = b with { Y = 2 };
Diagnostic(ErrorCode.ERR_CannotClone, "b").WithArguments("B").WithLocation(12, 13),
// (12,22): error CS0117: 'B' does not contain a definition for 'Y'
// b = b with { Y = 2 };
Diagnostic(ErrorCode.ERR_NoSuchMember, "Y").WithArguments("B", "Y").WithLocation(12, 22)
);
}
[Fact]
public void WithExpr24_Dynamic()
{
var src = @"
record C(int X)
{
public static void Main()
{
dynamic c = new C(1);
var x = c with { X = 2 };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (7,17): error CS8858: The receiver type 'dynamic' is not a valid record type.
// var x = c with { X = 2 };
Diagnostic(ErrorCode.ERR_CannotClone, "c").WithArguments("dynamic").WithLocation(7, 17)
);
}
[Fact, WorkItem(46427, "https://github.com/dotnet/roslyn/issues/46427"), WorkItem(46249, "https://github.com/dotnet/roslyn/issues/46249")]
public void WithExpr25_TypeParameterWithRecordConstraint()
{
var src = @"
record R(int X);
class C
{
public static T M<T>(T t) where T : R
{
return t with { X = 2 };
}
static void Main()
{
System.Console.Write(M(new R(-1)).X);
}
}";
var verifier = CompileAndVerify(src, expectedOutput: "2").VerifyDiagnostics();
verifier.VerifyIL("C.M<T>(T)", @"
{
// Code size 29 (0x1d)
.maxstack 3
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: callvirt ""R R.<Clone>$()""
IL_000b: unbox.any ""T""
IL_0010: dup
IL_0011: box ""T""
IL_0016: ldc.i4.2
IL_0017: callvirt ""void R.X.init""
IL_001c: ret
}
");
}
[Fact, WorkItem(46427, "https://github.com/dotnet/roslyn/issues/46427"), WorkItem(46249, "https://github.com/dotnet/roslyn/issues/46249")]
public void WithExpr26_TypeParameterWithRecordAndInterfaceConstraint()
{
var src = @"
record R
{
public int X { get; set; }
}
interface I { int Property { get; set; } }
record T : R, I
{
public int Property { get; set; }
}
class C
{
public static T M<T>(T t) where T : R, I
{
return t with { X = 2, Property = 3 };
}
static void Main()
{
System.Console.WriteLine(M(new T()).X);
System.Console.WriteLine(M(new T()).Property);
}
}";
var verifier = CompileAndVerify(
new[] { src, IsExternalInitTypeDefinition },
parseOptions: TestOptions.Regular9,
verify: Verification.Passes,
expectedOutput:
@"2
3").VerifyDiagnostics();
verifier.VerifyIL("C.M<T>(T)", @"
{
// Code size 41 (0x29)
.maxstack 3
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: callvirt ""R R.<Clone>$()""
IL_000b: unbox.any ""T""
IL_0010: dup
IL_0011: box ""T""
IL_0016: ldc.i4.2
IL_0017: callvirt ""void R.X.set""
IL_001c: dup
IL_001d: box ""T""
IL_0022: ldc.i4.3
IL_0023: callvirt ""void I.Property.set""
IL_0028: ret
}
");
}
[Fact]
public void WithExpr27_InExceptionFilter()
{
var src = @"
var r = new R(1);
try
{
throw new System.Exception();
}
catch (System.Exception) when ((r = r with { X = 2 }).X == 2)
{
System.Console.Write(""RAN "");
System.Console.Write(r.X);
}
record R(int X);
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "RAN 2", verify: Verification.Skipped /* init-only */);
}
[Fact]
public void WithExpr28_WithAwait()
{
var src = @"
var r = new R(1);
r = r with { X = await System.Threading.Tasks.Task.FromResult(42) };
System.Console.Write(r.X);
record R(int X);
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree, ignoreAccessibility: false);
var x = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Last().Left;
Assert.Equal("X", x.ToString());
var symbol = model.GetSymbolInfo(x).Symbol;
Assert.Equal("System.Int32 R.X { get; init; }", symbol.ToTestDisplayString());
}
[Fact, WorkItem(46465, "https://github.com/dotnet/roslyn/issues/46465")]
public void WithExpr29_DisallowedAsExpressionStatement()
{
var src = @"
record R(int X)
{
void M()
{
var r = new R(1);
r with { X = 2 };
}
}
";
// Note: we didn't parse the `with` as a `with` expression, but as a broken local declaration
// Tracked by https://github.com/dotnet/roslyn/issues/46465
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (7,9): error CS0118: 'r' is a variable but is used like a type
// r with { X = 2 };
Diagnostic(ErrorCode.ERR_BadSKknown, "r").WithArguments("r", "variable", "type").WithLocation(7, 9),
// (7,11): warning CS0168: The variable 'with' is declared but never used
// r with { X = 2 };
Diagnostic(ErrorCode.WRN_UnreferencedVar, "with").WithArguments("with").WithLocation(7, 11),
// (7,16): error CS1002: ; expected
// r with { X = 2 };
Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(7, 16),
// (7,18): error CS8852: Init-only property or indexer 'R.X' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor.
// r with { X = 2 };
Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "X").WithArguments("R.X").WithLocation(7, 18),
// (7,24): error CS1002: ; expected
// r with { X = 2 };
Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(7, 24)
);
}
[Fact]
public void WithExpr30_TypeParameterNoConstraint()
{
var src = @"
class C
{
public static void M<T>(T t)
{
_ = t with { X = 2 };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (6,13): error CS8858: The receiver type 'T' is not a valid record type.
// _ = t with { X = 2 };
Diagnostic(ErrorCode.ERR_CannotClone, "t").WithArguments("T").WithLocation(6, 13),
// (6,22): error CS0117: 'T' does not contain a definition for 'X'
// _ = t with { X = 2 };
Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("T", "X").WithLocation(6, 22)
);
}
[Fact]
public void WithExpr31_TypeParameterWithInterfaceConstraint()
{
var src = @"
interface I { int Property { get; set; } }
class C
{
public static void M<T>(T t) where T : I
{
_ = t with { X = 2, Property = 3 };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (8,13): error CS8858: The receiver type 'T' is not a valid record type.
// _ = t with { X = 2, Property = 3 };
Diagnostic(ErrorCode.ERR_CannotClone, "t").WithArguments("T").WithLocation(8, 13),
// (8,22): error CS0117: 'T' does not contain a definition for 'X'
// _ = t with { X = 2, Property = 3 };
Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("T", "X").WithLocation(8, 22)
);
}
[Fact]
public void WithExpr32_TypeParameterWithInterfaceConstraint()
{
var ilSource = @"
.class interface public auto ansi abstract I
{
// Methods
.method public hidebysig specialname newslot abstract virtual
instance class I '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
} // end of method I::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig specialname newslot abstract virtual
instance int32 get_Property () cil managed
{
} // end of method I::get_Property
.method public hidebysig specialname newslot abstract virtual
instance void set_Property (
int32 'value'
) cil managed
{
} // end of method I::set_Property
// Properties
.property instance int32 Property()
{
.get instance int32 I::get_Property()
.set instance void I::set_Property(int32)
}
} // end of class I
";
var src = @"
class C
{
public static void M<T>(T t) where T : I
{
_ = t with { X = 2, Property = 3 };
}
}";
var comp = CreateCompilationWithIL(new[] { src, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (6,13): error CS8858: The receiver type 'T' is not a valid record type.
// _ = t with { X = 2, Property = 3 };
Diagnostic(ErrorCode.ERR_CannotClone, "t").WithArguments("T").WithLocation(6, 13),
// (6,22): error CS0117: 'T' does not contain a definition for 'X'
// _ = t with { X = 2, Property = 3 };
Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("T", "X").WithLocation(6, 22)
);
}
[Fact]
public void WithExpr33_TypeParameterWithStructureConstraint()
{
var ilSource = @"
.class public sequential ansi sealed beforefieldinit S
extends System.ValueType
{
.pack 0
.size 1
// Methods
.method public hidebysig
instance valuetype S '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
// Method begins at RVA 0x2150
// Code size 2 (0x2)
.maxstack 1
.locals init (
[0] valuetype S
)
IL_0000: ldnull
IL_0001: throw
} // end of method S::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig specialname
instance int32 get_Property () cil managed
{
// Method begins at RVA 0x215e
// Code size 2 (0x2)
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method S::get_Property
.method public hidebysig specialname
instance void set_Property (
int32 'value'
) cil managed
{
// Method begins at RVA 0x215e
// Code size 2 (0x2)
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method S::set_Property
// Properties
.property instance int32 Property()
{
.get instance int32 S::get_Property()
.set instance void S::set_Property(int32)
}
} // end of class S
";
var src = @"
abstract class Base<T>
{
public abstract void M<U>(U t) where U : T;
}
class C : Base<S>
{
public override void M<U>(U t)
{
_ = t with { X = 2, Property = 3 };
}
}";
var comp = CreateCompilationWithIL(new[] { src, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (11,13): error CS8773: Feature 'with on structs' is not available in C# 9.0. Please use language version 10.0 or greater.
// _ = t with { X = 2, Property = 3 };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "t with { X = 2, Property = 3 }").WithArguments("with on structs", "10.0").WithLocation(11, 13),
// (11,22): error CS0117: 'U' does not contain a definition for 'X'
// _ = t with { X = 2, Property = 3 };
Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("U", "X").WithLocation(11, 22),
// (11,29): error CS0117: 'U' does not contain a definition for 'Property'
// _ = t with { X = 2, Property = 3 };
Diagnostic(ErrorCode.ERR_NoSuchMember, "Property").WithArguments("U", "Property").WithLocation(11, 29)
);
comp = CreateCompilationWithIL(new[] { src, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular10);
comp.VerifyDiagnostics(
// (11,22): error CS0117: 'U' does not contain a definition for 'X'
// _ = t with { X = 2, Property = 3 };
Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("U", "X").WithLocation(11, 22),
// (11,29): error CS0117: 'U' does not contain a definition for 'Property'
// _ = t with { X = 2, Property = 3 };
Diagnostic(ErrorCode.ERR_NoSuchMember, "Property").WithArguments("U", "Property").WithLocation(11, 29)
);
}
[Fact, WorkItem(47513, "https://github.com/dotnet/roslyn/issues/47513")]
public void BothGetHashCodeAndEqualsAreDefined()
{
var src = @"
public sealed record C
{
public object Data;
public bool Equals(C c) { return false; }
public override int GetHashCode() { return 0; }
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact, WorkItem(47513, "https://github.com/dotnet/roslyn/issues/47513")]
public void BothGetHashCodeAndEqualsAreNotDefined()
{
var src = @"
public sealed record C
{
public object Data;
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact, WorkItem(47513, "https://github.com/dotnet/roslyn/issues/47513")]
public void GetHashCodeIsDefinedButEqualsIsNot()
{
var src = @"
public sealed record C
{
public object Data;
public override int GetHashCode() { return 0; }
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact, WorkItem(47513, "https://github.com/dotnet/roslyn/issues/47513")]
public void EqualsIsDefinedButGetHashCodeIsNot()
{
var src = @"
public sealed record C
{
public object Data;
public bool Equals(C c) { return false; }
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (5,17): warning CS8851: 'C' defines 'Equals' but not 'GetHashCode'
// public bool Equals(C c) { return false; }
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("C").WithLocation(5, 17));
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord()
{
var src = @"
class record { }
class C
{
record M(record r) => r;
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (2,7): error CS8860: Types and aliases should not be named 'record'.
// class record { }
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 7),
// (6,24): error CS1514: { expected
// record M(record r) => r;
Diagnostic(ErrorCode.ERR_LbraceExpected, "=>").WithLocation(6, 24),
// (6,24): error CS1513: } expected
// record M(record r) => r;
Diagnostic(ErrorCode.ERR_RbraceExpected, "=>").WithLocation(6, 24),
// (6,24): error CS1519: Invalid token '=>' in class, record, struct, or interface member declaration
// record M(record r) => r;
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=>").WithArguments("=>").WithLocation(6, 24),
// (6,28): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration
// record M(record r) => r;
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(6, 28),
// (6,28): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration
// record M(record r) => r;
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(6, 28)
);
comp = CreateCompilation(src, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics();
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord_Struct()
{
var src = @"
struct record { }
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (2,8): warning CS8860: Types and aliases should not be named 'record'.
// struct record { }
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 8)
);
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord_Interface()
{
var src = @"
interface record { }
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (2,11): warning CS8860: Types and aliases should not be named 'record'.
// interface record { }
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 11)
);
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord_Enum()
{
var src = @"
enum record { }
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (2,6): warning CS8860: Types and aliases should not be named 'record'.
// enum record { }
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 6)
);
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord_Delegate()
{
var src = @"
delegate void record();
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (2,15): warning CS8860: Types and aliases should not be named 'record'.
// delegate void record();
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 15)
);
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord_Delegate_Escaped()
{
var src = @"
delegate void @record();
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord_Alias()
{
var src = @"
using record = System.Console;
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (2,1): hidden CS8019: Unnecessary using directive.
// using record = System.Console;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using record = System.Console;").WithLocation(2, 1),
// (2,7): warning CS8860: Types and aliases should not be named 'record'.
// using record = System.Console;
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 7)
);
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord_Alias_Escaped()
{
var src = @"
using @record = System.Console;
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (2,1): hidden CS8019: Unnecessary using directive.
// using @record = System.Console;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using @record = System.Console;").WithLocation(2, 1)
);
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord_TypeParameter()
{
var src = @"
class C<record> { } // 1
class C2
{
class Nested<record> { } // 2
}
class C3
{
void Method<record>() { } // 3
void Method2()
{
void local<record>() // 4
{
local<record>();
}
}
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (2,9): warning CS8860: Types and aliases should not be named 'record'.
// class C<record> { } // 1
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 9),
// (5,18): warning CS8860: Types and aliases should not be named 'record'.
// class Nested<record> { } // 2
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(5, 18),
// (9,17): warning CS8860: Types and aliases should not be named 'record'.
// void Method<record>() { } // 3
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(9, 17),
// (13,20): warning CS8860: Types and aliases should not be named 'record'.
// void local<record>() // 4
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(13, 20)
);
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord_TypeParameter_Escaped()
{
var src = @"
class C<@record> { }
class C2
{
class Nested<@record> { }
}
class C3
{
void Method<@record>() { }
void Method2()
{
void local<@record>()
{
local<record>();
}
}
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord_TypeParameter_Escaped_Partial()
{
var src = @"
partial class C<@record> { }
partial class C<record> { } // 1
partial class D<record> { } // 2
partial class D<@record> { }
partial class D<record> { } // 3
partial class D<record> { } // 4
partial class E<@record> { }
partial class E<@record> { }
partial class C2
{
partial class Nested<record> { } // 5
partial class Nested<@record> { }
}
partial class C3
{
partial void Method<@record>();
partial void Method<record>() { } // 6
partial void Method2<@record>() { }
partial void Method2<record>(); // 7
partial void Method3<record>(); // 8
partial void Method3<@record>() { }
partial void Method4<record>() { } // 9
partial void Method4<@record>();
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (3,17): warning CS8860: Types and aliases should not be named 'record'.
// partial class C<record> { } // 1
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(3, 17),
// (5,17): warning CS8860: Types and aliases should not be named 'record'.
// partial class D<record> { } // 2
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(5, 17),
// (8,17): warning CS8860: Types and aliases should not be named 'record'.
// partial class D<record> { } // 3
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(8, 17),
// (9,17): warning CS8860: Types and aliases should not be named 'record'.
// partial class D<record> { } // 4
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(9, 17),
// (16,26): warning CS8860: Types and aliases should not be named 'record'.
// partial class Nested<record> { } // 5
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(16, 26),
// (22,25): warning CS8860: Types and aliases should not be named 'record'.
// partial void Method<record>() { } // 6
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(22, 25),
// (25,26): warning CS8860: Types and aliases should not be named 'record'.
// partial void Method2<record>(); // 7
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(25, 26),
// (27,26): warning CS8860: Types and aliases should not be named 'record'.
// partial void Method3<record>(); // 8
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(27, 26),
// (30,26): warning CS8860: Types and aliases should not be named 'record'.
// partial void Method4<record>() { } // 9
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(30, 26)
);
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord_Record()
{
var src = @"
record record { }
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (2,8): warning CS8860: Types and aliases should not be named 'record'.
// record record { }
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 8)
);
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord_TwoParts()
{
var src = @"
partial class record { }
partial class record { }
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (2,15): warning CS8860: Types and aliases should not be named 'record'.
// partial class record { }
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 15),
// (3,15): warning CS8860: Types and aliases should not be named 'record'.
// partial class record { }
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(3, 15)
);
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord_Escaped()
{
var src = @"
class @record { }
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord_MixedEscapedPartial()
{
var src = @"
partial class @record { }
partial class record { }
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (3,15): warning CS8860: Types and aliases should not be named 'record'.
// partial class record { }
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(3, 15)
);
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord_MixedEscapedPartial_ReversedOrder()
{
var src = @"
partial class record { }
partial class @record { }
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (2,15): warning CS8860: Types and aliases should not be named 'record'.
// partial class record { }
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 15)
);
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord_BothEscapedPartial()
{
var src = @"
partial class @record { }
partial class @record { }
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact]
public void TypeNamedRecord_EscapedReturnType()
{
var src = @"
class record { }
class C
{
@record M(record r)
{
System.Console.Write(""RAN"");
return r;
}
public static void Main()
{
var c = new C();
_ = c.M(new record());
}
}";
var comp = CreateCompilation(src, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics(
// (2,7): warning CS8860: Types and aliases should not be named 'record'.
// class record { }
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 7)
);
CompileAndVerify(comp, expectedOutput: "RAN");
}
[Fact, WorkItem(45591, "https://github.com/dotnet/roslyn/issues/45591")]
public void Clone_DisallowedInSource()
{
var src = @"
record C1(string Clone); // 1
record C2
{
string Clone; // 2
}
record C3
{
string Clone { get; set; } // 3
}
record C4
{
data string Clone; // 4 not yet supported
}
record C5
{
void Clone() { } // 5
void Clone(int i) { } // 6
}
record C6
{
class Clone { } // 7
}
record C7
{
delegate void Clone(); // 8
}
record C8
{
event System.Action Clone; // 9
}
record Clone
{
Clone(int i) => throw null;
}
record C9 : System.ICloneable
{
object System.ICloneable.Clone() => throw null;
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (2,18): error CS8859: Members named 'Clone' are disallowed in records.
// record C1(string Clone); // 1
Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(2, 18),
// (5,12): error CS8859: Members named 'Clone' are disallowed in records.
// string Clone; // 2
Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(5, 12),
// (5,12): warning CS0169: The field 'C2.Clone' is never used
// string Clone; // 2
Diagnostic(ErrorCode.WRN_UnreferencedField, "Clone").WithArguments("C2.Clone").WithLocation(5, 12),
// (9,12): error CS8859: Members named 'Clone' are disallowed in records.
// string Clone { get; set; } // 3
Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(9, 12),
// (13,10): error CS1519: Invalid token 'string' in class, record, struct, or interface member declaration
// data string Clone; // 4 not yet supported
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "string").WithArguments("string").WithLocation(13, 10),
// (13,17): error CS8859: Members named 'Clone' are disallowed in records.
// data string Clone; // 4 not yet supported
Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(13, 17),
// (13,17): warning CS0169: The field 'C4.Clone' is never used
// data string Clone; // 4 not yet supported
Diagnostic(ErrorCode.WRN_UnreferencedField, "Clone").WithArguments("C4.Clone").WithLocation(13, 17),
// (17,10): error CS8859: Members named 'Clone' are disallowed in records.
// void Clone() { } // 5
Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(17, 10),
// (18,10): error CS8859: Members named 'Clone' are disallowed in records.
// void Clone(int i) { } // 6
Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(18, 10),
// (22,11): error CS8859: Members named 'Clone' are disallowed in records.
// class Clone { } // 7
Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(22, 11),
// (26,19): error CS8859: Members named 'Clone' are disallowed in records.
// delegate void Clone(); // 8
Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(26, 19),
// (30,25): error CS8859: Members named 'Clone' are disallowed in records.
// event System.Action Clone; // 9
Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(30, 25),
// (30,25): warning CS0067: The event 'C8.Clone' is never used
// event System.Action Clone; // 9
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Clone").WithArguments("C8.Clone").WithLocation(30, 25)
);
}
[Fact]
public void Clone_LoadedFromMetadata()
{
// IL for ' public record Base(int i);' with a 'void Clone()' method added
var il = @"
.class public auto ansi beforefieldinit Base
extends [mscorlib]System.Object
implements class [mscorlib]System.IEquatable`1<class Base>
{
.field private initonly int32 '<i>k__BackingField'
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
.method public hidebysig specialname newslot virtual instance class Base '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldarg.0
IL_0001: newobj instance void Base::.ctor(class Base)
IL_0006: ret
}
.method family hidebysig specialname newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
IL_0000: ldtoken Base
IL_0005: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
IL_000a: ret
}
.method public hidebysig specialname rtspecialname instance void .ctor ( int32 i ) cil managed
{
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld int32 Base::'<i>k__BackingField'
IL_0007: ldarg.0
IL_0008: call instance void [mscorlib]System.Object::.ctor()
IL_000d: ret
}
.method public hidebysig specialname instance int32 get_i () cil managed
{
IL_0000: ldarg.0
IL_0001: ldfld int32 Base::'<i>k__BackingField'
IL_0006: ret
}
.method public hidebysig specialname instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_i ( int32 'value' ) cil managed
{
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld int32 Base::'<i>k__BackingField'
IL_0007: ret
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: call class [mscorlib]System.Collections.Generic.EqualityComparer`1<!0> class [mscorlib]System.Collections.Generic.EqualityComparer`1<class [mscorlib]System.Type>::get_Default()
IL_0005: ldarg.0
IL_0006: callvirt instance class [mscorlib]System.Type Base::get_EqualityContract()
IL_000b: callvirt instance int32 class [mscorlib]System.Collections.Generic.EqualityComparer`1<class [mscorlib]System.Type>::GetHashCode(!0)
IL_0010: ldc.i4 -1521134295
IL_0015: mul
IL_0016: call class [mscorlib]System.Collections.Generic.EqualityComparer`1<!0> class [mscorlib]System.Collections.Generic.EqualityComparer`1<int32>::get_Default()
IL_001b: ldarg.0
IL_001c: ldfld int32 Base::'<i>k__BackingField'
IL_0021: callvirt instance int32 class [mscorlib]System.Collections.Generic.EqualityComparer`1<int32>::GetHashCode(!0)
IL_0026: add
IL_0027: ret
}
.method public hidebysig virtual instance bool Equals ( object obj ) cil managed
{
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: isinst Base
IL_0007: callvirt instance bool Base::Equals(class Base)
IL_000c: ret
}
.method public newslot virtual instance bool Equals ( class Base '' ) cil managed
{
IL_0000: ldarg.1
IL_0001: brfalse.s IL_002d
IL_0003: ldarg.0
IL_0004: callvirt instance class [mscorlib]System.Type Base::get_EqualityContract()
IL_0009: ldarg.1
IL_000a: callvirt instance class [mscorlib]System.Type Base::get_EqualityContract()
IL_000f: call bool [mscorlib]System.Type::op_Equality(class [mscorlib]System.Type, class [mscorlib]System.Type)
IL_0014: brfalse.s IL_002d
IL_0016: call class [mscorlib]System.Collections.Generic.EqualityComparer`1<!0> class [mscorlib]System.Collections.Generic.EqualityComparer`1<int32>::get_Default()
IL_001b: ldarg.0
IL_001c: ldfld int32 Base::'<i>k__BackingField'
IL_0021: ldarg.1
IL_0022: ldfld int32 Base::'<i>k__BackingField'
IL_0027: callvirt instance bool class [mscorlib]System.Collections.Generic.EqualityComparer`1<int32>::Equals(!0, !0)
IL_002c: ret
IL_002d: ldc.i4.0
IL_002e: ret
}
.method family hidebysig specialname rtspecialname instance void .ctor ( class Base '' ) cil managed
{
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ldarg.0
IL_0007: ldarg.1
IL_0008: ldfld int32 Base::'<i>k__BackingField'
IL_000d: stfld int32 Base::'<i>k__BackingField'
IL_0012: ret
}
.method public hidebysig instance void Deconstruct ( [out] int32& i ) cil managed
{
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: call instance int32 Base::get_i()
IL_0007: stind.i4
IL_0008: ret
}
.method public hidebysig instance void Clone () cil managed
{
IL_0000: ldstr ""RAN""
IL_0005: call void [mscorlib]System.Console::Write(string)
IL_000a: ret
}
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type Base::get_EqualityContract()
}
.property instance int32 i()
{
.get instance int32 Base::get_i()
.set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) Base::set_i(int32)
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}
.class public auto ansi abstract sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends [mscorlib]System.Object
{
}
";
var src = @"
record R(int i) : Base(i);
public class C
{
public static void Main()
{
var r = new R(1);
r.Clone();
}
}
";
var comp = CreateCompilationWithIL(src, il, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "RAN").VerifyDiagnostics();
// Note: we do load the Clone method from metadata
}
[Fact]
public void Clone_01()
{
var src = @"
abstract sealed record C1;
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (2,24): error CS0418: 'C1': an abstract type cannot be sealed or static
// abstract sealed record C1;
Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C1").WithArguments("C1").WithLocation(2, 24)
);
var clone = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.CloneMethodName);
Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility);
Assert.False(clone.IsOverride);
Assert.False(clone.IsVirtual);
Assert.True(clone.IsAbstract);
Assert.False(clone.IsSealed);
Assert.True(clone.IsImplicitlyDeclared);
Assert.True(clone.ContainingType.IsSealed);
Assert.True(clone.ContainingType.IsAbstract);
var namedTypeSymbol = comp.GlobalNamespace.GetTypeMember("C1");
Assert.True(namedTypeSymbol.IsRecord);
Assert.Equal("record C1", namedTypeSymbol
.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword)));
}
[Fact]
public void Clone_02()
{
var src = @"
sealed abstract record C1;
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (2,24): error CS0418: 'C1': an abstract type cannot be sealed or static
// sealed abstract record C1;
Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C1").WithArguments("C1").WithLocation(2, 24)
);
var clone = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.CloneMethodName);
Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility);
Assert.False(clone.IsOverride);
Assert.False(clone.IsVirtual);
Assert.True(clone.IsAbstract);
Assert.False(clone.IsSealed);
Assert.True(clone.IsImplicitlyDeclared);
Assert.True(clone.ContainingType.IsSealed);
Assert.True(clone.ContainingType.IsAbstract);
var namedTypeSymbol = comp.GlobalNamespace.GetTypeMember("C1");
Assert.True(namedTypeSymbol.IsRecord);
Assert.Equal("record C1", namedTypeSymbol
.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword)));
}
[Fact]
public void Clone_03()
{
var src = @"
record C1;
abstract sealed record C2 : C1;
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (3,24): error CS0418: 'C2': an abstract type cannot be sealed or static
// abstract sealed record C2 : C1;
Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C2").WithArguments("C2").WithLocation(3, 24)
);
var clone = comp.GetMember<MethodSymbol>("C2." + WellKnownMemberNames.CloneMethodName);
Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility);
Assert.True(clone.IsOverride);
Assert.False(clone.IsVirtual);
Assert.True(clone.IsAbstract);
Assert.False(clone.IsSealed);
Assert.True(clone.IsImplicitlyDeclared);
Assert.True(clone.ContainingType.IsSealed);
Assert.True(clone.ContainingType.IsAbstract);
}
[Fact]
public void Clone_04()
{
var src = @"
record C1;
sealed abstract record C2 : C1;
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (3,24): error CS0418: 'C2': an abstract type cannot be sealed or static
// sealed abstract record C2 : C1;
Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C2").WithArguments("C2").WithLocation(3, 24)
);
var clone = comp.GetMember<MethodSymbol>("C2." + WellKnownMemberNames.CloneMethodName);
Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility);
Assert.True(clone.IsOverride);
Assert.False(clone.IsVirtual);
Assert.True(clone.IsAbstract);
Assert.False(clone.IsSealed);
Assert.True(clone.IsImplicitlyDeclared);
Assert.True(clone.ContainingType.IsSealed);
Assert.True(clone.ContainingType.IsAbstract);
var namedTypeSymbol = comp.GlobalNamespace.GetTypeMember("C1");
Assert.True(namedTypeSymbol.IsRecord);
Assert.Equal("record C1", namedTypeSymbol
.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword)));
}
[Fact]
public void Clone_05_IntReturnType_UsedAsBaseType()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool PrintMembers ( class [mscorlib]System.Text.StringBuilder builder ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,19): error CS8864: Records may only inherit from object or another record
// public record B : A {
Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(2, 19)
);
Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A")
.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword)));
}
[Fact]
public void Clone_06_IntReturnType_UsedInWith()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
} // end of class A
";
var source = @"
public class Program
{
static void Main()
{
A x = new A() with { };
}
}
";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (6,15): error CS8858: The receiver type 'A' is not a valid record type.
// A x = new A() with { };
Diagnostic(ErrorCode.ERR_CannotClone, "new A()").WithArguments("A").WithLocation(6, 15)
);
Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A")
.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword)));
}
[Fact]
public void Clone_07_Ambiguous_UsedAsBaseType()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool PrintMembers ( class [mscorlib]System.Text.StringBuilder builder ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,19): error CS8864: Records may only inherit from object or another record
// public record B : A {
Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(2, 19)
);
Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A")
.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword)));
}
[Fact]
public void Clone_08_Ambiguous_UsedInWith()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
} // end of class A
";
var source = @"
public class Program
{
static void Main()
{
A x = new A() with { };
}
}
";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (6,15): error CS8858: The receiver type 'A' is not a valid record type.
// A x = new A() with { };
Diagnostic(ErrorCode.ERR_CannotClone, "new A()").WithArguments("A").WithLocation(6, 15)
);
Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A")
.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword)));
}
[Fact]
public void Clone_09_AmbiguousReverseOrder_UsedAsBaseType()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig specialname newslot virtual
instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool PrintMembers ( class [mscorlib]System.Text.StringBuilder builder ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,19): error CS8864: Records may only inherit from object or another record
// public record B : A {
Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(2, 19)
);
Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A")
.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword)));
}
[Fact]
public void Clone_10_AmbiguousReverseOrder_UsedInWith()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig specialname newslot virtual
instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
} // end of class A
";
var source = @"
public class Program
{
static void Main()
{
A x = new A() with { };
}
}
";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (6,15): error CS8858: The receiver type 'A' is not a valid record type.
// A x = new A() with { };
Diagnostic(ErrorCode.ERR_CannotClone, "new A()").WithArguments("A").WithLocation(6, 15)
);
Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A")
.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword)));
}
[Fact]
public void Clone_11()
{
string source1 = @"
public record A;
";
var comp1Ref = CreateCompilation(source1).EmitToImageReference();
string source2 = @"
public record B(int X) : A;
";
var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference();
string source3 = @"
class Program
{
public static void Main()
{
var c1 = new B(1);
var c2 = c1 with { X = 11 };
System.Console.WriteLine(c1.X);
System.Console.WriteLine(c2.X);
}
}
";
CompileAndVerify(source3, references: new[] { comp1Ref, comp2Ref }, expectedOutput: @"1
11").VerifyDiagnostics();
}
[Fact]
public void Clone_12()
{
string source1 = @"
public record A;
";
var comp1Ref = CreateCompilation(new[] { source1, IsExternalInitTypeDefinition }, assemblyName: "Clone_12", parseOptions: TestOptions.Regular9).EmitToImageReference();
string source2 = @"
public record B(int X) : A;
";
var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference();
string source3 = @"
class Program
{
public static void Main()
{
var c1 = new B(1);
var c2 = c1 with { X = 11 };
System.Console.WriteLine(c1.X);
System.Console.WriteLine(c2.X);
}
}
";
var comp3 = CreateCompilation(new[] { source3, IsExternalInitTypeDefinition }, references: new[] { comp2Ref }, parseOptions: TestOptions.Regular9);
comp3.VerifyEmitDiagnostics(
// (7,18): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_12, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// var c2 = c1 with { X = 11 };
Diagnostic(ErrorCode.ERR_NoTypeDef, "c1").WithArguments("A", "Clone_12, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18)
);
}
[Fact]
public void Clone_13()
{
string source1 = @"
public record A;
";
var comp1Ref = CreateCompilation(new[] { source1, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9).EmitToImageReference();
string source2 = @"
public record B(int X) : A;
";
var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, assemblyName: "Clone_13", references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference();
string source3 = @"
public record C(int X) : B(X);
";
var comp3Ref = CreateCompilation(new[] { source3, IsExternalInitTypeDefinition }, references: new[] { comp1Ref, comp2Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference();
string source4 = @"
class Program
{
public static void Main()
{
var c1 = new C(1);
var c2 = c1 with { X = 11 };
}
}
";
var comp4 = CreateCompilation(new[] { source4, IsExternalInitTypeDefinition }, references: new[] { comp1Ref, comp3Ref }, parseOptions: TestOptions.Regular9);
comp4.VerifyEmitDiagnostics(
// (7,18): error CS8858: The receiver type 'C' is not a valid record type.
// var c2 = c1 with { X = 11 };
Diagnostic(ErrorCode.ERR_CannotClone, "c1").WithArguments("C").WithLocation(7, 18),
// (7,18): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// var c2 = c1 with { X = 11 };
Diagnostic(ErrorCode.ERR_NoTypeDef, "c1").WithArguments("B", "Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18),
// (7,28): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// var c2 = c1 with { X = 11 };
Diagnostic(ErrorCode.ERR_NoTypeDef, "X").WithArguments("B", "Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 28),
// (7,28): error CS0117: 'C' does not contain a definition for 'X'
// var c2 = c1 with { X = 11 };
Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("C", "X").WithLocation(7, 28)
);
var comp5 = CreateCompilation(new[] { source4, IsExternalInitTypeDefinition }, references: new[] { comp3Ref }, parseOptions: TestOptions.Regular9);
comp5.VerifyEmitDiagnostics(
// (7,18): error CS8858: The receiver type 'C' is not a valid record type.
// var c2 = c1 with { X = 11 };
Diagnostic(ErrorCode.ERR_CannotClone, "c1").WithArguments("C").WithLocation(7, 18),
// (7,18): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// var c2 = c1 with { X = 11 };
Diagnostic(ErrorCode.ERR_NoTypeDef, "c1").WithArguments("B", "Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18),
// (7,28): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// var c2 = c1 with { X = 11 };
Diagnostic(ErrorCode.ERR_NoTypeDef, "X").WithArguments("B", "Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 28),
// (7,28): error CS0117: 'C' does not contain a definition for 'X'
// var c2 = c1 with { X = 11 };
Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("C", "X").WithLocation(7, 28)
);
}
[Fact]
public void Clone_14()
{
string source1 = @"
public record A;
";
var comp1Ref = CreateCompilation(source1).EmitToImageReference();
string source2 = @"
public record B(int X) : A;
";
var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference();
string source3 = @"
record C(int X) : B(X)
{
public static void Main()
{
var c1 = new C(1);
var c2 = c1 with { X = 11 };
System.Console.WriteLine(c1.X);
System.Console.WriteLine(c2.X);
}
}
";
CompileAndVerify(source3, references: new[] { comp1Ref, comp2Ref }, expectedOutput: @"1
11").VerifyDiagnostics();
}
[Fact]
public void Clone_15()
{
string source1 = @"
public record A;
";
var comp1Ref = CreateCompilation(new[] { source1, IsExternalInitTypeDefinition }, assemblyName: "Clone_15", parseOptions: TestOptions.Regular9).EmitToImageReference();
string source2 = @"
public record B(int X) : A;
";
var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference();
string source3 = @"
record C(int X) : B(X)
{
public static void Main()
{
var c1 = new C(1);
var c2 = c1 with { X = 11 };
System.Console.WriteLine(c1.X);
System.Console.WriteLine(c2.X);
}
}
";
var comp3 = CreateCompilation(new[] { source3, IsExternalInitTypeDefinition }, references: new[] { comp2Ref }, parseOptions: TestOptions.Regular9);
comp3.VerifyEmitDiagnostics(
// (2,8): error CS8869: 'C.Equals(object?)' does not override expected method from 'object'.
// record C(int X) : B(X)
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "C").WithArguments("C.Equals(object?)").WithLocation(2, 8),
// (2,8): error CS8869: 'C.GetHashCode()' does not override expected method from 'object'.
// record C(int X) : B(X)
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "C").WithArguments("C.GetHashCode()").WithLocation(2, 8),
// (2,8): error CS8869: 'C.ToString()' does not override expected method from 'object'.
// record C(int X) : B(X)
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "C").WithArguments("C.ToString()").WithLocation(2, 8),
// (2,8): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// record C(int X) : B(X)
Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 8),
// (2,19): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// record C(int X) : B(X)
Diagnostic(ErrorCode.ERR_NoTypeDef, "B").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19),
// (2,19): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// record C(int X) : B(X)
Diagnostic(ErrorCode.ERR_NoTypeDef, "B").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19),
// (6,22): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// var c1 = new C(1);
Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 22),
// (7,18): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// var c2 = c1 with { X = 11 };
Diagnostic(ErrorCode.ERR_NoTypeDef, "c1").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18),
// (8,9): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// System.Console.WriteLine(c1.X);
Diagnostic(ErrorCode.ERR_NoTypeDef, "System").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(8, 9),
// (9,9): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// System.Console.WriteLine(c2.X);
Diagnostic(ErrorCode.ERR_NoTypeDef, "System").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(9, 9)
);
}
[Fact]
public void Clone_16()
{
string source1 = @"
public record A;
";
var comp1Ref = CreateCompilation(new[] { source1, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9).EmitToImageReference();
string source2 = @"
public record B(int X) : A;
";
var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, assemblyName: "Clone_16", references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference();
string source3 = @"
public record C(int X) : B(X);
";
var comp3Ref = CreateCompilation(new[] { source3, IsExternalInitTypeDefinition }, references: new[] { comp1Ref, comp2Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference();
string source4 = @"
record D(int X) : C(X)
{
public static void Main()
{
var c1 = new D(1);
var c2 = c1 with { X = 11 };
}
}
";
var comp4 = CreateCompilation(new[] { source4, IsExternalInitTypeDefinition }, references: new[] { comp1Ref, comp3Ref }, parseOptions: TestOptions.Regular9);
comp4.VerifyEmitDiagnostics(
// (2,8): error CS8869: 'D.Equals(object?)' does not override expected method from 'object'.
// record D(int X) : C(X)
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.Equals(object?)").WithLocation(2, 8),
// (2,8): error CS8869: 'D.GetHashCode()' does not override expected method from 'object'.
// record D(int X) : C(X)
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.GetHashCode()").WithLocation(2, 8),
// (2,8): error CS8869: 'D.ToString()' does not override expected method from 'object'.
// record D(int X) : C(X)
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.ToString()").WithLocation(2, 8),
// (2,19): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// record D(int X) : C(X)
Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19),
// (2,19): error CS8864: Records may only inherit from object or another record
// record D(int X) : C(X)
Diagnostic(ErrorCode.ERR_BadRecordBase, "C").WithLocation(2, 19),
// (2,19): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// record D(int X) : C(X)
Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19),
// (6,22): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// var c1 = new D(1);
Diagnostic(ErrorCode.ERR_NoTypeDef, "D").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 22)
);
var comp5 = CreateCompilation(new[] { source4, IsExternalInitTypeDefinition }, references: new[] { comp3Ref }, parseOptions: TestOptions.Regular9);
comp5.VerifyEmitDiagnostics(
// (2,8): error CS8869: 'D.Equals(object?)' does not override expected method from 'object'.
// record D(int X) : C(X)
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.Equals(object?)").WithLocation(2, 8),
// (2,8): error CS8869: 'D.GetHashCode()' does not override expected method from 'object'.
// record D(int X) : C(X)
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.GetHashCode()").WithLocation(2, 8),
// (2,8): error CS8869: 'D.ToString()' does not override expected method from 'object'.
// record D(int X) : C(X)
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.ToString()").WithLocation(2, 8),
// (2,19): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// record D(int X) : C(X)
Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19),
// (2,19): error CS8864: Records may only inherit from object or another record
// record D(int X) : C(X)
Diagnostic(ErrorCode.ERR_BadRecordBase, "C").WithLocation(2, 19),
// (2,19): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// record D(int X) : C(X)
Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19),
// (6,22): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// var c1 = new D(1);
Diagnostic(ErrorCode.ERR_NoTypeDef, "D").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 22)
);
}
[Fact]
public void Clone_17_NonOverridable()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool PrintMembers ( class [mscorlib]System.Text.StringBuilder builder ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,19): error CS8864: Records may only inherit from object or another record
// public record B : A {
Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(2, 19)
);
Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A")
.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword)));
}
[Fact]
public void Clone_18_NonOverridable()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual final
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool PrintMembers ( class [mscorlib]System.Text.StringBuilder builder ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,19): error CS8864: Records may only inherit from object or another record
// public record B : A {
Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(2, 19)
);
Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A")
.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword)));
}
[Fact]
public void Clone_19()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
.class public auto ansi beforefieldinit B
extends A
{
// Methods
.method public hidebysig specialname virtual final
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method B::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public final virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public newslot virtual
instance bool Equals (
class B ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class B ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method B::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type B::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class B
";
var source = @"
public record C : B {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0239: 'C.<Clone>$()': cannot override inherited member 'B.<Clone>$()' because it is sealed
// public record C : B {
Diagnostic(ErrorCode.ERR_CantOverrideSealed, "C").WithArguments("C.<Clone>$()", "B.<Clone>$()").WithLocation(2, 15)
);
}
[Fact, WorkItem(47093, "https://github.com/dotnet/roslyn/issues/47093")]
public void ToString_TopLevelRecord_Empty()
{
var src = @"
var c1 = new C1();
System.Console.Write(c1.ToString());
record C1;
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
var v = CompileAndVerify(comp, expectedOutput: "C1 { }");
var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName);
Assert.Equal(Accessibility.Protected, print.DeclaredAccessibility);
Assert.False(print.IsOverride);
Assert.True(print.IsVirtual);
Assert.False(print.IsAbstract);
Assert.False(print.IsSealed);
Assert.True(print.IsImplicitlyDeclared);
var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString);
Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility);
Assert.True(toString.IsOverride);
Assert.False(toString.IsVirtual);
Assert.False(toString.IsAbstract);
Assert.False(toString.IsSealed);
Assert.True(toString.IsImplicitlyDeclared);
v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @"
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: ret
}
");
v.VerifyIL("C1." + WellKnownMemberNames.ObjectToString, @"
{
// Code size 64 (0x40)
.maxstack 2
.locals init (System.Text.StringBuilder V_0)
IL_0000: newobj ""System.Text.StringBuilder..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldstr ""C1""
IL_000c: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_0011: pop
IL_0012: ldloc.0
IL_0013: ldstr "" { ""
IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_001d: pop
IL_001e: ldarg.0
IL_001f: ldloc.0
IL_0020: callvirt ""bool C1.PrintMembers(System.Text.StringBuilder)""
IL_0025: brfalse.s IL_0030
IL_0027: ldloc.0
IL_0028: ldc.i4.s 32
IL_002a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)""
IL_002f: pop
IL_0030: ldloc.0
IL_0031: ldc.i4.s 125
IL_0033: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)""
IL_0038: pop
IL_0039: ldloc.0
IL_003a: callvirt ""string object.ToString()""
IL_003f: ret
}
");
}
[Fact]
public void ToString_TopLevelRecord_AbstractRecord()
{
var src = @"
var c2 = new C2();
System.Console.Write(c2);
abstract record C1;
record C2 : C1
{
public override string ToString() => base.ToString();
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
var v = CompileAndVerify(comp, expectedOutput: "C1 { }");
var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName);
Assert.Equal(Accessibility.Protected, print.DeclaredAccessibility);
Assert.False(print.IsOverride);
Assert.True(print.IsVirtual);
Assert.False(print.IsAbstract);
Assert.False(print.IsSealed);
Assert.True(print.IsImplicitlyDeclared);
var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString);
Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility);
Assert.True(toString.IsOverride);
Assert.False(toString.IsVirtual);
Assert.False(toString.IsAbstract);
Assert.False(toString.IsSealed);
Assert.True(toString.IsImplicitlyDeclared);
v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @"
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: ret
}
");
v.VerifyIL("C1." + WellKnownMemberNames.ObjectToString, @"
{
// Code size 64 (0x40)
.maxstack 2
.locals init (System.Text.StringBuilder V_0)
IL_0000: newobj ""System.Text.StringBuilder..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldstr ""C1""
IL_000c: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_0011: pop
IL_0012: ldloc.0
IL_0013: ldstr "" { ""
IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_001d: pop
IL_001e: ldarg.0
IL_001f: ldloc.0
IL_0020: callvirt ""bool C1.PrintMembers(System.Text.StringBuilder)""
IL_0025: brfalse.s IL_0030
IL_0027: ldloc.0
IL_0028: ldc.i4.s 32
IL_002a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)""
IL_002f: pop
IL_0030: ldloc.0
IL_0031: ldc.i4.s 125
IL_0033: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)""
IL_0038: pop
IL_0039: ldloc.0
IL_003a: callvirt ""string object.ToString()""
IL_003f: ret
}
");
}
[Fact]
public void ToString_DerivedRecord_AbstractRecord()
{
var src = @"
var c2 = new C2();
System.Console.Write(c2);
record Base;
abstract record C1 : Base;
record C2 : C1
{
public override string ToString() => base.ToString();
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
var v = CompileAndVerify(comp, expectedOutput: "C1 { }");
var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName);
Assert.Equal(Accessibility.Protected, print.DeclaredAccessibility);
Assert.True(print.IsOverride);
Assert.False(print.IsVirtual);
Assert.False(print.IsAbstract);
Assert.False(print.IsSealed);
Assert.True(print.IsImplicitlyDeclared);
var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString);
Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility);
Assert.True(toString.IsOverride);
Assert.False(toString.IsVirtual);
Assert.False(toString.IsAbstract);
Assert.False(toString.IsSealed);
Assert.True(toString.IsImplicitlyDeclared);
v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""bool Base.PrintMembers(System.Text.StringBuilder)""
IL_0007: ret
}
");
v.VerifyIL("C1." + WellKnownMemberNames.ObjectToString, @"
{
// Code size 64 (0x40)
.maxstack 2
.locals init (System.Text.StringBuilder V_0)
IL_0000: newobj ""System.Text.StringBuilder..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldstr ""C1""
IL_000c: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_0011: pop
IL_0012: ldloc.0
IL_0013: ldstr "" { ""
IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_001d: pop
IL_001e: ldarg.0
IL_001f: ldloc.0
IL_0020: callvirt ""bool Base.PrintMembers(System.Text.StringBuilder)""
IL_0025: brfalse.s IL_0030
IL_0027: ldloc.0
IL_0028: ldc.i4.s 32
IL_002a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)""
IL_002f: pop
IL_0030: ldloc.0
IL_0031: ldc.i4.s 125
IL_0033: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)""
IL_0038: pop
IL_0039: ldloc.0
IL_003a: callvirt ""string object.ToString()""
IL_003f: ret
}
");
}
[Fact]
public void ToString_TopLevelRecord_MissingStringBuilder()
{
var src = @"
record C1;
";
var comp = CreateCompilation(src);
comp.MakeTypeMissing(WellKnownType.System_Text_StringBuilder);
comp.VerifyEmitDiagnostics(
// (2,1): error CS0518: Predefined type 'System.Text.StringBuilder' is not defined or imported
// record C1;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "record C1;").WithArguments("System.Text.StringBuilder").WithLocation(2, 1),
// (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder..ctor'
// record C1;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1;").WithArguments("System.Text.StringBuilder", ".ctor").WithLocation(2, 1),
// (2,8): error CS0518: Predefined type 'System.Text.StringBuilder' is not defined or imported
// record C1;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "C1").WithArguments("System.Text.StringBuilder").WithLocation(2, 8)
);
}
[Fact]
public void ToString_TopLevelRecord_MissingStringBuilderCtor()
{
var src = @"
record C1;
";
var comp = CreateCompilation(src);
comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__ctor);
comp.VerifyEmitDiagnostics(
// (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder..ctor'
// record C1;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1;").WithArguments("System.Text.StringBuilder", ".ctor").WithLocation(2, 1)
);
}
[Fact]
public void ToString_TopLevelRecord_MissingStringBuilderAppendString()
{
var src = @"
record C1;
";
var comp = CreateCompilation(src);
comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__AppendString);
comp.VerifyEmitDiagnostics(
// (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append'
// record C1;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1;").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1)
);
}
[Fact]
public void ToString_TopLevelRecord_OneProperty_MissingStringBuilderAppendString()
{
var src = @"
record C1(int P);
";
var comp = CreateCompilation(src);
comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__AppendString);
comp.VerifyEmitDiagnostics(
// (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append'
// record C1(int P);
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1),
// (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append'
// record C1(int P);
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1)
);
}
[Fact]
public void ToString_TopLevelRecord_OneProperty_MissingStringBuilderAppendStringAndChar()
{
var src = @"
record C1(int P);
";
var comp = CreateCompilation(src);
comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__AppendString);
comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__AppendChar);
comp.VerifyEmitDiagnostics(
// (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append'
// record C1(int P);
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1),
// (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append'
// record C1(int P);
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1)
);
}
[Fact]
public void ToString_TopLevelRecord_Empty_Sealed()
{
var src = @"
var c1 = new C1();
System.Console.Write(c1.ToString());
sealed record C1;
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "C1 { }");
var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName);
Assert.Equal(Accessibility.Private, print.DeclaredAccessibility);
Assert.False(print.IsOverride);
Assert.False(print.IsVirtual);
Assert.False(print.IsAbstract);
Assert.False(print.IsSealed);
Assert.True(print.IsImplicitlyDeclared);
var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString);
Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility);
Assert.True(toString.IsOverride);
Assert.False(toString.IsVirtual);
Assert.False(toString.IsAbstract);
Assert.False(toString.IsSealed);
Assert.True(toString.IsImplicitlyDeclared);
}
[Fact]
public void ToString_AbstractRecord()
{
var src = @"
var c2 = new C2(42, 43);
System.Console.Write(c2.ToString());
abstract record C1(int I1);
sealed record C2(int I1, int I2) : C1(I1);
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "C2 { I1 = 42, I2 = 43 }", verify: Verification.Skipped /* init-only */);
}
[Fact, WorkItem(47672, "https://github.com/dotnet/roslyn/issues/47672")]
public void ToString_RecordWithIndexer()
{
var src = @"
var c1 = new C1(42);
System.Console.Write(c1.ToString());
record C1(int I1)
{
private int field = 44;
public int this[int i] => 0;
public int PropertyWithoutGetter { set { } }
public int P2 { get => 43; }
public ref int P3 { get => ref field; }
public event System.Action a;
private int field1 = 100;
internal int field2 = 100;
protected int field3 = 100;
private protected int field4 = 100;
internal protected int field5 = 100;
private int Property1 { get; set; } = 100;
internal int Property2 { get; set; } = 100;
protected int Property3 { get; set; } = 100;
private protected int Property4 { get; set; } = 100;
internal protected int Property5 { get; set; } = 100;
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "C1 { I1 = 42, P2 = 43, P3 = 44 }", verify: Verification.Skipped /* init-only */);
comp.VerifyEmitDiagnostics(
// (12,32): warning CS0067: The event 'C1.a' is never used
// public event System.Action a;
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "a", isSuppressed: false).WithArguments("C1.a").WithLocation(12, 32),
// (14,17): warning CS0414: The field 'C1.field1' is assigned but its value is never used
// private int field1 = 100;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field1", isSuppressed: false).WithArguments("C1.field1").WithLocation(14, 17)
);
}
[Fact, WorkItem(47672, "https://github.com/dotnet/roslyn/issues/47672")]
public void ToString_PrivateGetter()
{
var src = @"
var c1 = new C1();
System.Console.Write(c1.ToString());
record C1
{
public int P1 { private get => 43; set => throw null; }
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "C1 { P1 = 43 }");
comp.VerifyEmitDiagnostics();
}
[Fact, WorkItem(47797, "https://github.com/dotnet/roslyn/issues/47797")]
public void ToString_OverriddenVirtualProperty_NoRepetition()
{
var src = @"
System.Console.WriteLine(new B() { P = 2 }.ToString());
abstract record A
{
public virtual int P { get; set; }
}
record B : A
{
public override int P { get; set; }
}
";
var comp = CreateCompilation(src, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "B { P = 2 }");
}
[Fact, WorkItem(47797, "https://github.com/dotnet/roslyn/issues/47797")]
public void ToString_OverriddenAbstractProperty_NoRepetition()
{
var src = @"
System.Console.Write(new B1() { P = 1 });
System.Console.Write("" "");
System.Console.Write(new B2(2));
abstract record A1
{
public abstract int P { get; set; }
}
record B1 : A1
{
public override int P { get; set; }
}
abstract record A2(int P);
record B2(int P) : A2(P);
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "B1 { P = 1 } B2 { P = 2 }", verify: Verification.Skipped /* init-only */);
}
[Fact]
public void ToString_ErrorBase()
{
var src = @"
record C2: Error;
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (2,8): error CS0115: 'C2.ToString()': no suitable method found to override
// record C2: Error;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.ToString()").WithLocation(2, 8),
// (2,8): error CS0115: 'C2.EqualityContract': no suitable method found to override
// record C2: Error;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.EqualityContract").WithLocation(2, 8),
// (2,8): error CS0115: 'C2.Equals(object?)': no suitable method found to override
// record C2: Error;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.Equals(object?)").WithLocation(2, 8),
// (2,8): error CS0115: 'C2.GetHashCode()': no suitable method found to override
// record C2: Error;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.GetHashCode()").WithLocation(2, 8),
// (2,8): error CS0115: 'C2.PrintMembers(StringBuilder)': no suitable method found to override
// record C2: Error;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8),
// (2,12): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?)
// record C2: Error;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(2, 12)
);
}
[Fact, WorkItem(49263, "https://github.com/dotnet/roslyn/issues/49263")]
public void ToString_SelfReferentialBase()
{
var src = @"
record R : R;
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (2,8): error CS0146: Circular base type dependency involving 'R' and 'R'
// record R : R;
Diagnostic(ErrorCode.ERR_CircularBase, "R").WithArguments("R", "R").WithLocation(2, 8),
// (2,8): error CS0115: 'R.ToString()': no suitable method found to override
// record R : R;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R").WithArguments("R.ToString()").WithLocation(2, 8),
// (2,8): error CS0115: 'R.EqualityContract': no suitable method found to override
// record R : R;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R").WithArguments("R.EqualityContract").WithLocation(2, 8),
// (2,8): error CS0115: 'R.Equals(object?)': no suitable method found to override
// record R : R;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R").WithArguments("R.Equals(object?)").WithLocation(2, 8),
// (2,8): error CS0115: 'R.GetHashCode()': no suitable method found to override
// record R : R;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R").WithArguments("R.GetHashCode()").WithLocation(2, 8),
// (2,8): error CS0115: 'R.PrintMembers(StringBuilder)': no suitable method found to override
// record R : R;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R").WithArguments("R.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8)
);
}
[Fact]
public void ToString_TopLevelRecord_Empty_AbstractSealed()
{
var src = @"
abstract sealed record C1;
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (2,24): error CS0418: 'C1': an abstract type cannot be sealed or static
// abstract sealed record C1;
Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C1").WithArguments("C1").WithLocation(2, 24)
);
var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName);
Assert.Equal(Accessibility.Private, print.DeclaredAccessibility);
Assert.False(print.IsOverride);
Assert.False(print.IsVirtual);
Assert.False(print.IsAbstract);
Assert.False(print.IsSealed);
Assert.True(print.IsImplicitlyDeclared);
var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString);
Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility);
Assert.True(toString.IsOverride);
Assert.False(toString.IsVirtual);
Assert.False(toString.IsAbstract);
Assert.False(toString.IsSealed);
Assert.True(toString.IsImplicitlyDeclared);
}
[Fact, WorkItem(47092, "https://github.com/dotnet/roslyn/issues/47092")]
public void ToString_TopLevelRecord_OneField_ValueType()
{
var src = @"
var c1 = new C1() { field = 42 };
System.Console.Write(c1.ToString());
record C1
{
public int field;
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
var v = CompileAndVerify(comp, expectedOutput: "C1 { field = 42 }");
var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName);
Assert.Equal(Accessibility.Protected, print.DeclaredAccessibility);
Assert.False(print.IsOverride);
Assert.True(print.IsVirtual);
Assert.False(print.IsAbstract);
Assert.False(print.IsSealed);
Assert.True(print.IsImplicitlyDeclared);
var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString);
Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility);
Assert.True(toString.IsOverride);
Assert.False(toString.IsVirtual);
Assert.False(toString.IsAbstract);
Assert.False(toString.IsSealed);
Assert.True(toString.IsImplicitlyDeclared);
v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @"
{
// Code size 38 (0x26)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldstr ""field = ""
IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_000b: pop
IL_000c: ldarg.1
IL_000d: ldarg.0
IL_000e: ldflda ""int C1.field""
IL_0013: constrained. ""int""
IL_0019: callvirt ""string object.ToString()""
IL_001e: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_0023: pop
IL_0024: ldc.i4.1
IL_0025: ret
}
");
}
[Fact, WorkItem(47092, "https://github.com/dotnet/roslyn/issues/47092")]
public void ToString_TopLevelRecord_OneField_ConstrainedValueType()
{
var src = @"
var c1 = new C1<int>() { field = 42 };
System.Console.Write(c1.ToString());
record C1<T> where T : struct
{
public T field;
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
var v = CompileAndVerify(comp, expectedOutput: "C1 { field = 42 }");
v.VerifyIL("C1<T>." + WellKnownMemberNames.PrintMembersMethodName, @"
{
// Code size 38 (0x26)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldstr ""field = ""
IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_000b: pop
IL_000c: ldarg.1
IL_000d: ldarg.0
IL_000e: ldflda ""T C1<T>.field""
IL_0013: constrained. ""T""
IL_0019: callvirt ""string object.ToString()""
IL_001e: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_0023: pop
IL_0024: ldc.i4.1
IL_0025: ret
}
");
}
[Fact, WorkItem(47092, "https://github.com/dotnet/roslyn/issues/47092")]
public void ToString_TopLevelRecord_OneField_ReferenceType()
{
var src = @"
var c1 = new C1() { field = ""hello"" };
System.Console.Write(c1.ToString());
record C1
{
public string field;
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
var v = CompileAndVerify(comp, expectedOutput: "C1 { field = hello }");
v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @"
{
// Code size 27 (0x1b)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldstr ""field = ""
IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_000b: pop
IL_000c: ldarg.1
IL_000d: ldarg.0
IL_000e: ldfld ""string C1.field""
IL_0013: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)""
IL_0018: pop
IL_0019: ldc.i4.1
IL_001a: ret
}
");
}
[Fact, WorkItem(47092, "https://github.com/dotnet/roslyn/issues/47092")]
public void ToString_TopLevelRecord_OneField_Unconstrained()
{
var src = @"
var c1 = new C1<string>() { field = ""hello"" };
System.Console.Write(c1.ToString());
System.Console.Write("" "");
var c2 = new C1<int>() { field = 42 };
System.Console.Write(c2.ToString());
record C1<T>
{
public T field;
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
var v = CompileAndVerify(comp, expectedOutput: "C1 { field = hello } C1 { field = 42 }", verify: Verification.Skipped /* init-only */);
v.VerifyIL("C1<T>." + WellKnownMemberNames.PrintMembersMethodName, @"
{
// Code size 32 (0x20)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldstr ""field = ""
IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_000b: pop
IL_000c: ldarg.1
IL_000d: ldarg.0
IL_000e: ldfld ""T C1<T>.field""
IL_0013: box ""T""
IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)""
IL_001d: pop
IL_001e: ldc.i4.1
IL_001f: ret
}
");
}
[Fact]
public void ToString_TopLevelRecord_OneField_ErrorType()
{
var src = @"
record C1
{
public Error field;
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (4,12): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?)
// public Error field;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(4, 12),
// (4,18): warning CS0649: Field 'C1.field' is never assigned to, and will always have its default value null
// public Error field;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("C1.field", "null").WithLocation(4, 18)
);
}
[Fact]
public void ToString_TopLevelRecord_TwoFields_ReferenceType()
{
var src = @"
var c1 = new C1() { field1 = ""hi"", field2 = null };
System.Console.Write(c1.ToString());
record C1
{
public string field1;
public string field2;
private string field3;
internal string field4;
protected string field5;
protected internal string field6;
private protected string field7;
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics(
// (10,20): warning CS0169: The field 'C1.field3' is never used
// private string field3;
Diagnostic(ErrorCode.WRN_UnreferencedField, "field3").WithArguments("C1.field3").WithLocation(10, 20),
// (11,21): warning CS0649: Field 'C1.field4' is never assigned to, and will always have its default value null
// internal string field4;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field4").WithArguments("C1.field4", "null").WithLocation(11, 21),
// (12,22): warning CS0649: Field 'C1.field5' is never assigned to, and will always have its default value null
// protected string field5;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field5").WithArguments("C1.field5", "null").WithLocation(12, 22),
// (13,31): warning CS0649: Field 'C1.field6' is never assigned to, and will always have its default value null
// protected internal string field6;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field6").WithArguments("C1.field6", "null").WithLocation(13, 31),
// (14,30): warning CS0649: Field 'C1.field7' is never assigned to, and will always have its default value null
// private protected string field7;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field7").WithArguments("C1.field7", "null").WithLocation(14, 30)
);
var v = CompileAndVerify(comp, expectedOutput: "C1 { field1 = hi, field2 = }");
v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @"
{
// Code size 52 (0x34)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldstr ""field1 = ""
IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_000b: pop
IL_000c: ldarg.1
IL_000d: ldarg.0
IL_000e: ldfld ""string C1.field1""
IL_0013: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)""
IL_0018: pop
IL_0019: ldarg.1
IL_001a: ldstr "", field2 = ""
IL_001f: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_0024: pop
IL_0025: ldarg.1
IL_0026: ldarg.0
IL_0027: ldfld ""string C1.field2""
IL_002c: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)""
IL_0031: pop
IL_0032: ldc.i4.1
IL_0033: ret
}
");
}
[Fact]
public void ToString_TopLevelRecord_OneProperty()
{
var src = @"
var c1 = new C1(Property: 42);
System.Console.Write(c1.ToString());
record C1(int Property)
{
private int Property2;
internal int Property3;
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics(
// (7,17): warning CS0169: The field 'C1.Property2' is never used
// private int Property2;
Diagnostic(ErrorCode.WRN_UnreferencedField, "Property2").WithArguments("C1.Property2").WithLocation(7, 17),
// (8,18): warning CS0649: Field 'C1.Property3' is never assigned to, and will always have its default value 0
// internal int Property3;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Property3").WithArguments("C1.Property3", "0").WithLocation(8, 18)
);
var v = CompileAndVerify(comp, expectedOutput: "C1 { Property = 42 }", verify: Verification.Skipped /* init-only */);
v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @"
{
// Code size 41 (0x29)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarg.1
IL_0001: ldstr ""Property = ""
IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_000b: pop
IL_000c: ldarg.1
IL_000d: ldarg.0
IL_000e: call ""int C1.Property.get""
IL_0013: stloc.0
IL_0014: ldloca.s V_0
IL_0016: constrained. ""int""
IL_001c: callvirt ""string object.ToString()""
IL_0021: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_0026: pop
IL_0027: ldc.i4.1
IL_0028: ret
}
");
}
[Fact]
public void ToString_TopLevelRecord_TwoFieldsAndTwoProperties()
{
var src = @"
var c1 = new C1<int, string>(42, null) { field1 = 43, field2 = ""hi"" };
System.Console.Write(c1.ToString());
record C1<T1, T2>(T1 Property1, T2 Property2)
{
public T1 field1;
public T2 field2;
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "C1 { Property1 = 42, Property2 = , field1 = 43, field2 = hi }", verify: Verification.Skipped /* init-only */);
}
[Fact]
public void ToString_DerivedRecord_TwoFieldsAndTwoProperties()
{
var src = @"
var c1 = new C1(42, 43) { A2 = 100, B2 = 101 };
System.Console.Write(c1.ToString());
record Base(int A1)
{
public int A2;
}
record C1(int A1, int B1) : Base(A1)
{
public int B2;
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
var v = CompileAndVerify(comp, expectedOutput: "C1 { A1 = 42, A2 = 100, B1 = 43, B2 = 101 }", verify: Verification.Skipped /* init-only */);
v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @"
{
// Code size 98 (0x62)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""bool Base.PrintMembers(System.Text.StringBuilder)""
IL_0007: brfalse.s IL_0015
IL_0009: ldarg.1
IL_000a: ldstr "", ""
IL_000f: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_0014: pop
IL_0015: ldarg.1
IL_0016: ldstr ""B1 = ""
IL_001b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_0020: pop
IL_0021: ldarg.1
IL_0022: ldarg.0
IL_0023: call ""int C1.B1.get""
IL_0028: stloc.0
IL_0029: ldloca.s V_0
IL_002b: constrained. ""int""
IL_0031: callvirt ""string object.ToString()""
IL_0036: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_003b: pop
IL_003c: ldarg.1
IL_003d: ldstr "", B2 = ""
IL_0042: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_0047: pop
IL_0048: ldarg.1
IL_0049: ldarg.0
IL_004a: ldflda ""int C1.B2""
IL_004f: constrained. ""int""
IL_0055: callvirt ""string object.ToString()""
IL_005a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_005f: pop
IL_0060: ldc.i4.1
IL_0061: ret
}
");
}
[Fact]
public void ToString_DerivedRecord_AbstractSealed()
{
var src = @"
record C1;
abstract sealed record C2 : C1;
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (3,24): error CS0418: 'C2': an abstract type cannot be sealed or static
// abstract sealed record C2 : C1;
Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C2").WithArguments("C2").WithLocation(3, 24)
);
var print = comp.GetMember<MethodSymbol>("C2." + WellKnownMemberNames.PrintMembersMethodName);
Assert.Equal(Accessibility.Protected, print.DeclaredAccessibility);
Assert.True(print.IsOverride);
Assert.False(print.IsVirtual);
Assert.False(print.IsAbstract);
Assert.False(print.IsSealed);
Assert.True(print.IsImplicitlyDeclared);
var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString);
Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility);
Assert.True(toString.IsOverride);
Assert.False(toString.IsVirtual);
Assert.False(toString.IsAbstract);
Assert.False(toString.IsSealed);
Assert.True(toString.IsImplicitlyDeclared);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void ToString_DerivedRecord_BaseHasSealedToString(bool usePreview)
{
var src = @"
var c = new C2();
System.Console.Write(c.ToString());
record C1
{
public sealed override string ToString() => ""C1"";
}
record C2 : C1;
";
var comp = CreateCompilation(src, parseOptions: usePreview ? TestOptions.Regular10 : TestOptions.Regular9, options: TestOptions.DebugExe);
if (usePreview)
{
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "C1");
}
else
{
comp.VerifyEmitDiagnostics(
// (7,35): error CS8773: Feature 'sealed ToString in record' is not available in C# 9.0. Please use language version 10.0 or greater.
// public sealed override string ToString() => "C1";
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "ToString").WithArguments("sealed ToString in record", "10.0").WithLocation(7, 35)
);
}
}
[Fact]
public void ToString_DerivedRecord_BaseBaseHasSealedToString()
{
var src = @"
var c = new C3();
System.Console.Write(c.ToString());
record C1
{
public sealed override string ToString() => ""C1"";
}
record C2 : C1;
record C3 : C2;
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "C1");
}
[Fact]
public void ToString_DerivedRecord_BaseBaseHasSealedToString_And_BaseTriesToOverride()
{
var src = @"
var c = new C3();
System.Console.Write(c.ToString());
record C1
{
public sealed override string ToString() => ""C1"";
}
record C2 : C1
{
public override string ToString() => ""C2"";
}
record C3 : C2;
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics(
// (11,28): error CS0239: 'C2.ToString()': cannot override inherited member 'C1.ToString()' because it is sealed
// public override string ToString() => "C2";
Diagnostic(ErrorCode.ERR_CantOverrideSealed, "ToString").WithArguments("C2.ToString()", "C1.ToString()").WithLocation(11, 28)
);
}
[Fact]
public void ToString_DerivedRecord_BaseBaseHasSealedToString_And_BaseShadowsToStringPrivate()
{
var src = @"
var c = new C3();
System.Console.Write(c.ToString());
record C1
{
public sealed override string ToString() => ""C1"";
}
record C2 : C1
{
private new string ToString() => ""C2"";
}
record C3 : C2;
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "C1");
var actualMembers = comp.GetMember<NamedTypeSymbol>("C3").GetMembers().ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type C3.EqualityContract.get",
"System.Type C3.EqualityContract { get; }",
"System.Boolean C3." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)",
"System.Boolean C3.op_Inequality(C3? left, C3? right)",
"System.Boolean C3.op_Equality(C3? left, C3? right)",
"System.Int32 C3.GetHashCode()",
"System.Boolean C3.Equals(System.Object? obj)",
"System.Boolean C3.Equals(C2? other)",
"System.Boolean C3.Equals(C3? other)",
"C1 C3." + WellKnownMemberNames.CloneMethodName + "()",
"C3..ctor(C3 original)",
"C3..ctor()"
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void ToString_DerivedRecord_BaseBaseHasSealedToString_And_BaseShadowsToStringNonSealed()
{
var src = @"
C3 c3 = new C3();
System.Console.Write(c3.ToString());
C1 c1 = c3;
System.Console.Write(c1.ToString());
record C1
{
public sealed override string ToString() => ""C1"";
}
record C2 : C1
{
public new virtual string ToString() => ""C2"";
}
record C3 : C2;
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "C2C1");
var actualMembers = comp.GetMember<NamedTypeSymbol>("C3").GetMembers().ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type C3.EqualityContract.get",
"System.Type C3.EqualityContract { get; }",
"System.Boolean C3." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)",
"System.Boolean C3.op_Inequality(C3? left, C3? right)",
"System.Boolean C3.op_Equality(C3? left, C3? right)",
"System.Int32 C3.GetHashCode()",
"System.Boolean C3.Equals(System.Object? obj)",
"System.Boolean C3.Equals(C2? other)",
"System.Boolean C3.Equals(C3? other)",
"C1 C3." + WellKnownMemberNames.CloneMethodName + "()",
"C3..ctor(C3 original)",
"C3..ctor()"
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void ToString_DerivedRecord_BaseBaseHasSealedToString_And_BaseHasToStringWithDifferentSignature()
{
var src = @"
var c = new C3();
System.Console.Write(c.ToString());
record C1
{
public sealed override string ToString() => ""C1"";
}
record C2 : C1
{
public string ToString(int n) => throw null;
}
record C3 : C2;
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "C1");
var actualMembers = comp.GetMember<NamedTypeSymbol>("C3").GetMembers().ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type C3.EqualityContract.get",
"System.Type C3.EqualityContract { get; }",
"System.Boolean C3." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)",
"System.Boolean C3.op_Inequality(C3? left, C3? right)",
"System.Boolean C3.op_Equality(C3? left, C3? right)",
"System.Int32 C3.GetHashCode()",
"System.Boolean C3.Equals(System.Object? obj)",
"System.Boolean C3.Equals(C2? other)",
"System.Boolean C3.Equals(C3? other)",
"C1 C3." + WellKnownMemberNames.CloneMethodName + "()",
"C3..ctor(C3 original)",
"C3..ctor()"
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void ToString_DerivedRecord_BaseBaseHasSealedToString_And_BaseHasToStringWithDifferentReturnType()
{
var src = @"
C1 c = new C3();
System.Console.Write(c.ToString());
record C1
{
public sealed override string ToString() => ""C1"";
}
record C2 : C1
{
public new int ToString() => throw null;
}
record C3 : C2;
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "C1");
var actualMembers = comp.GetMember<NamedTypeSymbol>("C3").GetMembers().ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type C3.EqualityContract.get",
"System.Type C3.EqualityContract { get; }",
"System.Boolean C3." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)",
"System.Boolean C3.op_Inequality(C3? left, C3? right)",
"System.Boolean C3.op_Equality(C3? left, C3? right)",
"System.Int32 C3.GetHashCode()",
"System.Boolean C3.Equals(System.Object? obj)",
"System.Boolean C3.Equals(C2? other)",
"System.Boolean C3.Equals(C3? other)",
"C1 C3." + WellKnownMemberNames.CloneMethodName + "()",
"C3..ctor(C3 original)",
"C3..ctor()"
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void ToString_DerivedRecord_TwoFieldsAndTwoProperties_ReverseOrder()
{
var src = @"
var c1 = new C1(42, 43) { A1 = 100, B1 = 101 };
System.Console.Write(c1.ToString());
record Base(int A2)
{
public int A1;
}
record C1(int A2, int B2) : Base(A2)
{
public int B1;
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "C1 { A2 = 42, A1 = 100, B2 = 43, B1 = 101 }", verify: Verification.Skipped /* init-only */);
}
[Fact]
public void ToString_DerivedRecord_TwoFieldsAndTwoProperties_Partial()
{
var src1 = @"
var c1 = new C1() { A1 = 100, B1 = 101 };
System.Console.Write(c1.ToString());
partial record C1
{
public int A1;
}
";
var src2 = @"
partial record C1
{
public int B1;
}
";
var comp = CreateCompilation(new[] { src1, src2, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "C1 { A1 = 100, B1 = 101 }", verify: Verification.Skipped /* init-only */);
}
[Fact]
public void ToString_DerivedRecord_TwoFieldsAndTwoProperties_Partial_ReverseOrder()
{
var src1 = @"
var c1 = new C1() { A1 = 100, B1 = 101 };
System.Console.Write(c1.ToString());
partial record C1
{
public int B1;
}
";
var src2 = @"
partial record C1
{
public int A1;
}
";
var comp = CreateCompilation(new[] { src1, src2, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "C1 { B1 = 101, A1 = 100 }", verify: Verification.Skipped /* init-only */);
}
[Fact]
public void ToString_BadBase_MissingToString()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
.method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals ( object other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public newslot virtual instance bool Equals ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
}
.method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance string ToString () cil managed
{
IL_0000: ldstr ""RAN""
IL_0005: ret
}
}
.class public auto ansi beforefieldinit B
extends A
{
.method family hidebysig specialname virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname static bool op_Inequality ( class B r1, class B r2 ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname static bool op_Equality ( class B r1, class B r2 ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals ( object obj ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public final hidebysig virtual instance bool Equals ( class A other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig newslot virtual instance bool Equals ( class B other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig specialname rtspecialname instance void .ctor ( class B original ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldarg.0
IL_0001: call instance void A::.ctor()
IL_0006: ret
}
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type B::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
// no override for ToString
}
";
var source = @"
var c = new C();
System.Console.Write(c);
public record C : B
{
public override string ToString() => base.ToString();
}
";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "RAN");
}
[Fact]
public void ToString_BadBase_PrintMembersSealed()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
.method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals ( object other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public newslot virtual instance bool Equals ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method final family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0506: 'B.PrintMembers(StringBuilder)': cannot override inherited member 'A.PrintMembers(StringBuilder)' because it is not marked virtual, abstract, or override
// public record B : A {
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)", "A.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 15)
);
}
[Fact]
public void ToString_BadBase_PrintMembersInaccessible()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
.method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals ( object other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public newslot virtual instance bool Equals ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method private hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0115: 'B.PrintMembers(StringBuilder)': no suitable method found to override
// public record B : A {
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 15)
);
}
[Fact]
public void ToString_BadBase_PrintMembersReturnsInt()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
.method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals ( object other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public newslot virtual instance bool Equals ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance int32 '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0508: 'B.PrintMembers(StringBuilder)': return type must be 'int' to match overridden member 'A.PrintMembers(StringBuilder)'
// public record B : A {
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)", "A.PrintMembers(System.Text.StringBuilder)", "int").WithLocation(2, 15)
);
}
[Fact]
public void EqualityContract_BadBase_ReturnsInt()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
.method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals ( object other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public newslot virtual instance bool Equals ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig newslot virtual instance int32 get_EqualityContract () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.property instance int32 EqualityContract()
{
.get instance int32 A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS1715: 'B.EqualityContract': type must be 'int' to match overridden member 'A.EqualityContract'
// public record B : A {
Diagnostic(ErrorCode.ERR_CantChangeTypeOnOverride, "B").WithArguments("B.EqualityContract", "A.EqualityContract", "int").WithLocation(2, 15)
);
}
[Fact]
public void ToString_BadBase_PrintMembersIsAmbiguous()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
.method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals ( object other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public newslot virtual instance bool Equals ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance int32 '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics();
}
[Fact]
public void ToString_BadBase_MissingPrintMembers()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
.method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals ( object other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public newslot virtual instance bool Equals ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
}
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0115: 'B.PrintMembers(StringBuilder)': no suitable method found to override
// public record B : A {
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 15)
);
}
[Fact]
public void ToString_BadBase_DuplicatePrintMembers()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
.method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals ( object other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public newslot virtual instance bool Equals ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder modopt(int64) builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance string ToString () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics();
}
[Fact]
public void ToString_BadBase_PrintMembersNotOverriddenInBase()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
.method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals ( object other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public newslot virtual instance bool Equals ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance string ToString () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}
.class public auto ansi beforefieldinit B
extends A
{
.method family hidebysig specialname virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname static bool op_Inequality ( class B r1, class B r2 ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname static bool op_Equality ( class B r1, class B r2 ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals ( object obj ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public final hidebysig virtual instance bool Equals ( class A other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig newslot virtual instance bool Equals ( class B other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig specialname rtspecialname instance void .ctor ( class B original ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type B::get_EqualityContract()
}
// no override for PrintMembers
}
";
var source = @"
public record C : B
{
protected override bool PrintMembers(System.Text.StringBuilder builder) => throw null;
}
";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (4,29): error CS8871: 'C.PrintMembers(StringBuilder)' does not override expected method from 'B'.
// protected override bool PrintMembers(System.Text.StringBuilder builder) => throw null;
Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseMethod, "PrintMembers").WithArguments("C.PrintMembers(System.Text.StringBuilder)", "B").WithLocation(4, 29)
);
var source2 = @"
public record C : B;
";
comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS8871: 'C.PrintMembers(StringBuilder)' does not override expected method from 'B'.
// public record C : B;
Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseMethod, "C").WithArguments("C.PrintMembers(System.Text.StringBuilder)", "B").WithLocation(2, 15)
);
}
[Fact]
public void ToString_BadBase_PrintMembersWithModOpt()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
.method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals ( object other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public newslot virtual instance bool Equals ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder modopt(int64) builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance string ToString () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics();
var print = comp.GetMember<MethodSymbol>("B." + WellKnownMemberNames.PrintMembersMethodName);
Assert.Equal("System.Boolean B.PrintMembers(System.Text.StringBuilder modopt(System.Int64) builder)", print.ToTestDisplayString());
Assert.Equal("System.Boolean A.PrintMembers(System.Text.StringBuilder modopt(System.Int64) builder)", print.OverriddenMethod.ToTestDisplayString());
}
[Fact]
public void ToString_BadBase_NewToString()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
.method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals ( object other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public newslot virtual instance bool Equals ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig newslot virtual instance string ToString () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS8869: 'B.ToString()' does not override expected method from 'object'.
// public record B : A {
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "B").WithArguments("B.ToString()").WithLocation(2, 15)
);
}
[Fact]
public void ToString_NewToString_SealedBaseToString()
{
var source = @"
B b = new B();
System.Console.Write(b.ToString());
A a = b;
System.Console.Write(a.ToString());
public record A
{
public sealed override string ToString() => ""A"";
}
public record B : A
{
public new string ToString() => ""B"";
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "BA");
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void ToString_BadBase_SealedToString(bool usePreview)
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
.method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals ( object other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public newslot virtual instance bool Equals ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
}
.method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public final hidebysig virtual instance string ToString () cil managed
{
IL_0000: ldstr ""A""
IL_0001: ret
}
}
";
var source = @"
var b = new B();
System.Console.Write(b.ToString());
public record B : A {
}";
var comp = CreateCompilationWithIL(
new[] { source, IsExternalInitTypeDefinition },
ilSource: ilSource,
parseOptions: usePreview ? TestOptions.Regular10 : TestOptions.Regular9);
if (usePreview)
{
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "A");
}
else
{
comp.VerifyEmitDiagnostics(
// (5,15): error CS8912: Inheriting from a record with a sealed 'Object.ToString' is not supported in C# 9.0. Please use language version '10.0' or greater.
// public record B : A {
Diagnostic(ErrorCode.ERR_InheritingFromRecordWithSealedToString, "B").WithArguments("9.0", "10.0").WithLocation(5, 15)
);
}
}
[Fact]
public void ToString_TopLevelRecord_UserDefinedToString()
{
var src = @"
var c1 = new C1();
System.Console.Write(c1.ToString());
record C1
{
public override string ToString() => ""RAN"";
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "RAN");
var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName);
Assert.Equal("System.Boolean C1." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", print.ToTestDisplayString());
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void ToString_TopLevelRecord_UserDefinedToString_Sealed(bool usePreview)
{
var src = @"
record C1
{
public sealed override string ToString() => throw null;
}
";
var comp = CreateCompilation(src, parseOptions: usePreview ? TestOptions.Regular10 : TestOptions.Regular9);
if (usePreview)
{
comp.VerifyEmitDiagnostics();
}
else
{
comp.VerifyEmitDiagnostics(
// (4,35): error CS8773: Feature 'sealed ToString in record' is not available in C# 9.0. Please use language version 10.0 or greater.
// public sealed override string ToString() => throw null;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "ToString").WithArguments("sealed ToString in record", "10.0").WithLocation(4, 35)
);
}
}
[Fact]
public void ToString_TopLevelRecord_UserDefinedToString_Sealed_InSealedRecord()
{
var src = @"
sealed record C1
{
public sealed override string ToString() => throw null;
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics();
}
[Fact]
public void ToString_UserDefinedPrintMembers_WithNullableStringBuilder()
{
var src = @"
#nullable enable
record C1
{
protected virtual bool PrintMembers(System.Text.StringBuilder? builder) => throw null!;
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics();
}
[Fact]
public void ToString_UserDefinedPrintMembers_ErrorReturnType()
{
var src = @"
record C1
{
protected virtual Error PrintMembers(System.Text.StringBuilder builder) => throw null;
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (4,23): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?)
// protected virtual Error PrintMembers(System.Text.StringBuilder builder) => throw null;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(4, 23)
);
}
[Fact]
public void ToString_UserDefinedPrintMembers_WrongReturnType()
{
var src = @"
record C1
{
protected virtual int PrintMembers(System.Text.StringBuilder builder) => throw null;
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (4,27): error CS8874: Record member 'C1.PrintMembers(StringBuilder)' must return 'bool'.
// protected virtual int PrintMembers(System.Text.StringBuilder builder) => throw null;
Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)", "bool").WithLocation(4, 27)
);
}
[Fact]
public void ToString_UserDefinedPrintMembers_Sealed()
{
var src = @"
record C1(int I1);
record C2(int I1, int I2) : C1(I1)
{
protected sealed override bool PrintMembers(System.Text.StringBuilder builder) => throw null;
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (5,36): error CS8872: 'C2.PrintMembers(StringBuilder)' must allow overriding because the containing record is not sealed.
// protected sealed override bool PrintMembers(System.Text.StringBuilder builder) => throw null;
Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "PrintMembers").WithArguments("C2.PrintMembers(System.Text.StringBuilder)").WithLocation(5, 36)
);
}
[Fact]
public void ToString_UserDefinedPrintMembers_NonVirtual()
{
var src = @"
record C1
{
protected bool PrintMembers(System.Text.StringBuilder builder) => throw null;
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (4,20): error CS8872: 'C1.PrintMembers(StringBuilder)' must allow overriding because the containing record is not sealed.
// protected bool PrintMembers(System.Text.StringBuilder builder) => throw null;
Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 20)
);
}
[Fact]
public void ToString_UserDefinedPrintMembers_SealedInSealedRecord()
{
var src = @"
record C1(int I1);
sealed record C2(int I1, int I2) : C1(I1)
{
protected sealed override bool PrintMembers(System.Text.StringBuilder builder) => throw null;
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics();
}
[Fact]
public void ToString_UserDefinedPrintMembers_Static()
{
var src = @"
sealed record C
{
private static bool PrintMembers(System.Text.StringBuilder builder) => throw null;
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (4,25): error CS8877: Record member 'C.PrintMembers(StringBuilder)' may not be static.
// private static bool PrintMembers(System.Text.StringBuilder builder) => throw null;
Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "PrintMembers").WithArguments("C.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 25)
);
}
[Fact]
public void ToString_UserDefinedPrintMembers()
{
var src = @"
var c1 = new C1();
System.Console.Write(c1.ToString());
record C1
{
protected virtual bool PrintMembers(System.Text.StringBuilder builder)
{
builder.Append(""RAN"");
return true;
}
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "C1 { RAN }");
}
[Fact]
public void ToString_UserDefinedPrintMembers_WrongAccessibility()
{
var src = @"
record C1
{
public virtual bool PrintMembers(System.Text.StringBuilder builder) => throw null;
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (4,25): error CS8875: Record member 'C1.PrintMembers(StringBuilder)' must be protected.
// public virtual bool PrintMembers(System.Text.StringBuilder builder) => throw null;
Diagnostic(ErrorCode.ERR_NonProtectedAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 25)
);
}
[Fact]
public void ToString_UserDefinedPrintMembers_WrongAccessibility_SealedRecord()
{
var src = @"
sealed record C1
{
protected bool PrintMembers(System.Text.StringBuilder builder) => throw null;
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (4,20): warning CS0628: 'C1.PrintMembers(StringBuilder)': new protected member declared in sealed type
// protected bool PrintMembers(System.Text.StringBuilder builder) => throw null;
Diagnostic(ErrorCode.WRN_ProtectedInSealed, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 20),
// (4,20): error CS8879: Record member 'C1.PrintMembers(StringBuilder)' must be private.
// protected bool PrintMembers(System.Text.StringBuilder builder) => throw null;
Diagnostic(ErrorCode.ERR_NonPrivateAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 20)
);
}
[Fact]
public void ToString_UserDefinedPrintMembers_DerivedRecord_WrongAccessibility()
{
var src = @"
record B;
record C1 : B
{
public bool PrintMembers(System.Text.StringBuilder builder) => throw null;
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (5,17): error CS8875: Record member 'C1.PrintMembers(StringBuilder)' must be protected.
// public bool PrintMembers(System.Text.StringBuilder builder) => throw null;
Diagnostic(ErrorCode.ERR_NonProtectedAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(5, 17),
// (5,17): error CS8860: 'C1.PrintMembers(StringBuilder)' does not override expected method from 'B'.
// public bool PrintMembers(System.Text.StringBuilder builder) => throw null;
Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseMethod, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)", "B").WithLocation(5, 17),
// (5,17): error CS8872: 'C1.PrintMembers(StringBuilder)' must allow overriding because the containing record is not sealed.
// public bool PrintMembers(System.Text.StringBuilder builder) => throw null;
Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(5, 17),
// (5,17): warning CS0114: 'C1.PrintMembers(StringBuilder)' hides inherited member 'B.PrintMembers(StringBuilder)'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.
// public bool PrintMembers(System.Text.StringBuilder builder) => throw null;
Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)", "B.PrintMembers(System.Text.StringBuilder)").WithLocation(5, 17)
);
}
[Fact]
public void ToString_UserDefinedPrintMembers_New()
{
var src = @"
record B;
record C1 : B
{
protected new virtual bool PrintMembers(System.Text.StringBuilder builder) => throw null;
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (5,32): error CS8860: 'C1.PrintMembers(StringBuilder)' does not override expected method from 'B'.
// protected new virtual bool PrintMembers(System.Text.StringBuilder builder) => throw null;
Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseMethod, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)", "B").WithLocation(5, 32)
);
}
[Fact]
public void ToString_TopLevelRecord_EscapedNamed()
{
var src = @"
var c1 = new @base();
System.Console.Write(c1.ToString());
record @base;
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "base { }");
}
[Fact]
public void ToString_DerivedDerivedRecord()
{
var src = @"
var r1 = new R1(1);
System.Console.Write(r1.ToString());
System.Console.Write("" "");
var r2 = new R2(10, 11);
System.Console.Write(r2.ToString());
System.Console.Write("" "");
var r3 = new R3(20, 21, 22);
System.Console.Write(r3.ToString());
record R1(int I1);
record R2(int I1, int I2) : R1(I1);
record R3(int I1, int I2, int I3) : R2(I1, I2);
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "R1 { I1 = 1 } R2 { I1 = 10, I2 = 11 } R3 { I1 = 20, I2 = 21, I3 = 22 }", verify: Verification.Skipped /* init-only */);
}
[Fact]
public void WithExpr24()
{
string source = @"
record C(int X)
{
public static void Main()
{
var c1 = new C(1);
c1 = c1 with { };
var c2 = c1 with { X = 11 };
System.Console.WriteLine(c1.X);
System.Console.WriteLine(c2.X);
}
protected C(ref C other) : this(-1)
{
}
protected C(C other)
{
X = other.X;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"1
11").VerifyDiagnostics();
verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: newobj ""C..ctor(C)""
IL_0006: ret
}
");
var clone = verifier.Compilation.GetMember("C." + WellKnownMemberNames.CloneMethodName);
Assert.Equal("<Clone>$", clone.Name);
}
[Fact]
public void WithExpr25()
{
string source = @"
record C(int X)
{
public static void Main()
{
var c1 = new C(1);
c1 = c1 with { };
var c2 = c1 with { X = 11 };
System.Console.WriteLine(c1.X);
System.Console.WriteLine(c2.X);
}
protected C(in C other) : this(-1)
{
}
protected C(C other)
{
X = other.X;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"1
11").VerifyDiagnostics();
verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: newobj ""C..ctor(C)""
IL_0006: ret
}
");
}
[Fact]
public void WithExpr26()
{
string source = @"
record C(int X)
{
public static void Main()
{
var c1 = new C(1);
c1 = c1 with { };
var c2 = c1 with { X = 11 };
System.Console.WriteLine(c1.X);
System.Console.WriteLine(c2.X);
}
protected C(out C other) : this(-1)
{
other = null;
}
protected C(C other)
{
X = other.X;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"1
11").VerifyDiagnostics();
verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: newobj ""C..ctor(C)""
IL_0006: ret
}
");
}
[Fact]
public void WithExpr27()
{
string source = @"
record C(int X)
{
public static void Main()
{
var c1 = new C(1);
c1 = c1 with { };
var c2 = c1 with { X = 11 };
System.Console.WriteLine(c1.X);
System.Console.WriteLine(c2.X);
}
protected C(ref C other) : this(-1)
{
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"1
11").VerifyDiagnostics();
verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: newobj ""C..ctor(C)""
IL_0006: ret
}
");
}
[Fact]
public void WithExpr28()
{
string source = @"
record C(int X)
{
public static void Main()
{
var c1 = new C(1);
c1 = c1 with { };
var c2 = c1 with { X = 11 };
System.Console.WriteLine(c1.X);
System.Console.WriteLine(c2.X);
}
protected C(in C other) : this(-1)
{
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"1
11").VerifyDiagnostics();
verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: newobj ""C..ctor(C)""
IL_0006: ret
}
");
}
[Fact]
public void WithExpr29()
{
string source = @"
record C(int X)
{
public static void Main()
{
var c1 = new C(1);
c1 = c1 with { };
var c2 = c1 with { X = 11 };
System.Console.WriteLine(c1.X);
System.Console.WriteLine(c2.X);
}
protected C(out C other) : this(-1)
{
other = null;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"1
11").VerifyDiagnostics();
verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: newobj ""C..ctor(C)""
IL_0006: ret
}
");
}
[Fact]
public void AccessibilityOfBaseCtor_01()
{
var src = @"
using System;
record Base
{
protected Base(int X, int Y)
{
Console.WriteLine(X);
Console.WriteLine(Y);
}
public Base() {}
public static void Main()
{
var c = new C(1, 2);
}
}
record C(int X, int Y) : Base(X, Y);
";
CompileAndVerify(src, expectedOutput: @"
1
2
").VerifyDiagnostics();
}
[Fact]
public void AccessibilityOfBaseCtor_02()
{
var src = @"
using System;
record Base
{
protected Base(int X, int Y)
{
Console.WriteLine(X);
Console.WriteLine(Y);
}
public Base() {}
public static void Main()
{
var c = new C(1, 2);
}
}
record C(int X, int Y) : Base(X, Y) {}
";
CompileAndVerify(src, expectedOutput: @"
1
2
").VerifyDiagnostics();
}
[Fact]
[WorkItem(44898, "https://github.com/dotnet/roslyn/issues/44898")]
public void AccessibilityOfBaseCtor_03()
{
var src = @"
abstract record A
{
protected A() {}
protected A(A x) {}
};
record B(object P) : A;
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics();
}
[Fact]
[WorkItem(44898, "https://github.com/dotnet/roslyn/issues/44898")]
public void AccessibilityOfBaseCtor_04()
{
var src = @"
abstract record A
{
protected A() {}
protected A(A x) {}
};
record B(object P) : A {}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact]
[WorkItem(44898, "https://github.com/dotnet/roslyn/issues/44898")]
public void AccessibilityOfBaseCtor_05()
{
var src = @"
abstract record A
{
protected A() {}
protected A(A x) {}
};
record B : A;
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics();
}
[Fact]
[WorkItem(44898, "https://github.com/dotnet/roslyn/issues/44898")]
public void AccessibilityOfBaseCtor_06()
{
var src = @"
abstract record A
{
protected A() {}
protected A(A x) {}
};
record B : A {}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact]
public void WithExprNestedErrors()
{
var src = @"
class C
{
public int X { get; init; }
public static void Main()
{
var c = new C();
c = c with { X = """"-3 };
}
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (8,13): error CS8808: The receiver type 'C' does not have an accessible parameterless instance method named "Clone".
// c = c with { X = ""-3 };
Diagnostic(ErrorCode.ERR_CannotClone, "c").WithArguments("C").WithLocation(8, 13),
// (8,26): error CS0019: Operator '-' cannot be applied to operands of type 'string' and 'int'
// c = c with { X = ""-3 };
Diagnostic(ErrorCode.ERR_BadBinaryOps, @"""""-3").WithArguments("-", "string", "int").WithLocation(8, 26)
);
}
[Fact]
public void WithExprNoExpressionToPropertyTypeConversion()
{
var src = @"
record C(int X)
{
public static void Main()
{
var c = new C(0);
c = c with { X = """" };
}
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (8,26): error CS0029: Cannot implicitly convert type 'string' to 'int'
// c = c with { X = "" };
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""""").WithArguments("string", "int").WithLocation(8, 26)
);
}
[Fact]
public void WithExprPropertyInaccessibleSet()
{
var src = @"
record C
{
public int X { get; private set; }
}
class D
{
public static void Main()
{
var c = new C();
c = c with { X = 0 };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (11,22): error CS0272: The property or indexer 'C.X' cannot be used in this context because the set accessor is inaccessible
// c = c with { X = 0 };
Diagnostic(ErrorCode.ERR_InaccessibleSetter, "X").WithArguments("C.X").WithLocation(11, 22)
);
}
[Fact]
public void WithExprSideEffects1()
{
var src = @"
using System;
record C(int X, int Y, int Z)
{
public static void Main()
{
var c = new C(0, 1, 2);
c = c with { Y = W(""Y""), X = W(""X"") };
}
public static int W(string s)
{
Console.WriteLine(s);
return 0;
}
}
";
var verifier = CompileAndVerify(src, expectedOutput: @"
Y
X").VerifyDiagnostics();
verifier.VerifyIL("C.Main", @"
{
// Code size 47 (0x2f)
.maxstack 3
IL_0000: ldc.i4.0
IL_0001: ldc.i4.1
IL_0002: ldc.i4.2
IL_0003: newobj ""C..ctor(int, int, int)""
IL_0008: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()""
IL_000d: dup
IL_000e: ldstr ""Y""
IL_0013: call ""int C.W(string)""
IL_0018: callvirt ""void C.Y.init""
IL_001d: dup
IL_001e: ldstr ""X""
IL_0023: call ""int C.W(string)""
IL_0028: callvirt ""void C.X.init""
IL_002d: pop
IL_002e: ret
}");
var comp = (CSharpCompilation)verifier.Compilation;
var tree = comp.SyntaxTrees.First();
var root = tree.GetRoot();
var model = comp.GetSemanticModel(tree);
var withExpr1 = root.DescendantNodes().OfType<WithExpressionSyntax>().First();
comp.VerifyOperationTree(withExpr1, @"
IWithOperation (OperationKind.With, Type: C) (Syntax: 'c with { Y ... = W(""X"") }')
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
CloneMethod: C C." + WellKnownMemberNames.CloneMethodName + @"()
Initializer:
IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C) (Syntax: '{ Y = W(""Y"" ... = W(""X"") }')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'Y = W(""Y"")')
Left:
IPropertyReferenceOperation: System.Int32 C.Y { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Y')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'Y')
Right:
IInvocationOperation (System.Int32 C.W(System.String s)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'W(""Y"")')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: s) (OperationKind.Argument, Type: null) (Syntax: '""Y""')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""Y"") (Syntax: '""Y""')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = W(""X"")')
Left:
IPropertyReferenceOperation: System.Int32 C.X { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X')
Right:
IInvocationOperation (System.Int32 C.W(System.String s)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'W(""X"")')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: s) (OperationKind.Argument, Type: null) (Syntax: '""X""')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""X"") (Syntax: '""X""')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
var main = root.DescendantNodes().OfType<MethodDeclarationSyntax>().First();
Assert.Equal("Main", main.Identifier.ToString());
VerifyFlowGraph(comp, main, expectedFlowGraph: @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [C c]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'c = new C(0, 1, 2)')
Left:
ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C(0, 1, 2)')
Right:
IObjectCreationOperation (Constructor: C..ctor(System.Int32 X, System.Int32 Y, System.Int32 Z)) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C(0, 1, 2)')
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: '0')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Z) (OperationKind.Argument, Type: null) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [0] [1]
Block[B2] - Block
Predecessors: [B1]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c')
Value:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c with { Y ... = W(""X"") }')
Value:
IInvocationOperation (virtual C C." + WellKnownMemberNames.CloneMethodName + @"()) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'c with { Y ... = W(""X"") }')
Instance Receiver:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
Arguments(0)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'Y = W(""Y"")')
Left:
IPropertyReferenceOperation: System.Int32 C.Y { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Y')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c with { Y ... = W(""X"") }')
Right:
IInvocationOperation (System.Int32 C.W(System.String s)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'W(""Y"")')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: s) (OperationKind.Argument, Type: null) (Syntax: '""Y""')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""Y"") (Syntax: '""Y""')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = W(""X"")')
Left:
IPropertyReferenceOperation: System.Int32 C.X { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c with { Y ... = W(""X"") }')
Right:
IInvocationOperation (System.Int32 C.W(System.String s)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'W(""X"")')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: s) (OperationKind.Argument, Type: null) (Syntax: '""X""')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""X"") (Syntax: '""X""')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = c with ... = W(""X"") };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: 'c = c with ... = W(""X"") }')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c with { Y ... = W(""X"") }')
Next (Regular) Block[B3]
Leaving: {R2} {R1}
}
}
Block[B3] - Exit
Predecessors: [B2]
Statements (0)
");
}
[Fact]
public void WithExprConversions1()
{
var src = @"
using System;
record C(long X)
{
public static void Main()
{
var c = new C(0);
Console.WriteLine((c with { X = 11 }).X);
}
}";
var verifier = CompileAndVerify(src, expectedOutput: "11").VerifyDiagnostics();
verifier.VerifyIL("C.Main", @"
{
// Code size 32 (0x20)
.maxstack 3
IL_0000: ldc.i4.0
IL_0001: conv.i8
IL_0002: newobj ""C..ctor(long)""
IL_0007: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()""
IL_000c: dup
IL_000d: ldc.i4.s 11
IL_000f: conv.i8
IL_0010: callvirt ""void C.X.init""
IL_0015: callvirt ""long C.X.get""
IL_001a: call ""void System.Console.WriteLine(long)""
IL_001f: ret
}");
}
[Fact]
public void WithExprConversions2()
{
var src = @"
using System;
struct S
{
private int _i;
public S(int i)
{
_i = i;
}
public static implicit operator long(S s)
{
Console.WriteLine(""conversion"");
return s._i;
}
}
record C(long X)
{
public static void Main()
{
var c = new C(0);
var s = new S(11);
Console.WriteLine((c with { X = s }).X);
}
}";
var verifier = CompileAndVerify(src, expectedOutput: @"
conversion
11").VerifyDiagnostics();
verifier.VerifyIL("C.Main", @"
{
// Code size 44 (0x2c)
.maxstack 3
.locals init (S V_0) //s
IL_0000: ldc.i4.0
IL_0001: conv.i8
IL_0002: newobj ""C..ctor(long)""
IL_0007: ldloca.s V_0
IL_0009: ldc.i4.s 11
IL_000b: call ""S..ctor(int)""
IL_0010: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()""
IL_0015: dup
IL_0016: ldloc.0
IL_0017: call ""long S.op_Implicit(S)""
IL_001c: callvirt ""void C.X.init""
IL_0021: callvirt ""long C.X.get""
IL_0026: call ""void System.Console.WriteLine(long)""
IL_002b: ret
}");
}
[Fact]
public void WithExprConversions3()
{
var src = @"
using System;
struct S
{
private int _i;
public S(int i)
{
_i = i;
}
public static explicit operator int(S s)
{
Console.WriteLine(""conversion"");
return s._i;
}
}
record C(long X)
{
public static void Main()
{
var c = new C(0);
var s = new S(11);
Console.WriteLine((c with { X = (int)s }).X);
}
}";
var verifier = CompileAndVerify(src, expectedOutput: @"
conversion
11").VerifyDiagnostics();
}
[Fact]
public void WithExprConversions4()
{
var src = @"
using System;
struct S
{
private int _i;
public S(int i)
{
_i = i;
}
public static explicit operator long(S s) => s._i;
}
record C(long X)
{
public static void Main()
{
var c = new C(0);
var s = new S(11);
Console.WriteLine((c with { X = s }).X);
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (19,41): error CS0266: Cannot implicitly convert type 'S' to 'long'. An explicit conversion exists (are you missing a cast?)
// Console.WriteLine((c with { X = s }).X);
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "s").WithArguments("S", "long").WithLocation(19, 41)
);
}
[Fact]
public void WithExprConversions5()
{
var src = @"
using System;
record C(object X)
{
public static void Main()
{
var c = new C(0);
Console.WriteLine((c with { X = ""abc"" }).X);
}
}";
CompileAndVerify(src, expectedOutput: "abc").VerifyDiagnostics();
}
[Fact]
public void WithExprConversions6()
{
var src = @"
using System;
struct S
{
private int _i;
public S(int i)
{
_i = i;
}
public static implicit operator int(S s)
{
Console.WriteLine(""conversion"");
return s._i;
}
}
record C
{
private readonly long _x;
public long X { get => _x; init { Console.WriteLine(""set""); _x = value; } }
public static void Main()
{
var c = new C();
var s = new S(11);
Console.WriteLine((c with { X = s }).X);
}
}";
var verifier = CompileAndVerify(src, expectedOutput: @"
conversion
set
11").VerifyDiagnostics();
verifier.VerifyIL("C.Main", @"
{
// Code size 43 (0x2b)
.maxstack 3
.locals init (S V_0) //s
IL_0000: newobj ""C..ctor()""
IL_0005: ldloca.s V_0
IL_0007: ldc.i4.s 11
IL_0009: call ""S..ctor(int)""
IL_000e: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()""
IL_0013: dup
IL_0014: ldloc.0
IL_0015: call ""int S.op_Implicit(S)""
IL_001a: conv.i8
IL_001b: callvirt ""void C.X.init""
IL_0020: callvirt ""long C.X.get""
IL_0025: call ""void System.Console.WriteLine(long)""
IL_002a: ret
}");
}
[Fact]
public void WithExprStaticProperty()
{
var src = @"
record C
{
public static int X { get; set; }
public static void Main()
{
var c = new C();
c = c with { };
c = c with { X = 11 };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (9,22): error CS0176: Member 'C.X' cannot be accessed with an instance reference; qualify it with a type name instead
// c = c with { X = 11 };
Diagnostic(ErrorCode.ERR_ObjectProhibited, "X").WithArguments("C.X").WithLocation(9, 22)
);
}
[Fact]
public void WithExprMethodAsArgument()
{
var src = @"
record C
{
public int X() => 0;
public static void Main()
{
var c = new C();
c = c with { };
c = c with { X = 11 };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (9,22): error CS1913: Member 'X' cannot be initialized. It is not a field or property.
// c = c with { X = 11 };
Diagnostic(ErrorCode.ERR_MemberCannotBeInitialized, "X").WithArguments("X").WithLocation(9, 22)
);
}
[Fact]
public void WithExprStaticWithMethod()
{
var src = @"
class C
{
public int X = 0;
public static C Clone() => null;
public static void Main()
{
var c = new C();
c = c with { };
c = c with { X = 11 };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (9,13): error CS8808: The receiver type 'C' does not have an accessible parameterless instance method named "Clone".
// c = c with { };
Diagnostic(ErrorCode.ERR_CannotClone, "c").WithArguments("C").WithLocation(9, 13),
// (10,13): error CS8808: The receiver type 'C' does not have an accessible parameterless instance method named "Clone".
// c = c with { X = 11 };
Diagnostic(ErrorCode.ERR_CannotClone, "c").WithArguments("C").WithLocation(10, 13)
);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")]
[WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")]
public void WithExprStaticWithMethod2()
{
var src = @"
class B
{
public B Clone() => null;
}
class C : B
{
public int X = 0;
public static new C Clone() => null; // static
public static void Main()
{
var c = new C();
c = c with { };
c = c with { X = 11 };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (13,13): error CS0266: Cannot implicitly convert type 'B' to 'C'. An explicit conversion exists (are you missing a cast?)
// c = c with { };
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "c with { }").WithArguments("B", "C").WithLocation(13, 13),
// (14,22): error CS0117: 'B' does not contain a definition for 'X'
// c = c with { X = 11 };
Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("B", "X").WithLocation(14, 22)
);
}
[Fact]
public void WithExprBadMemberBadType()
{
var src = @"
record C
{
public int X { get; init; }
public static void Main()
{
var c = new C();
c = c with { X = ""a"" };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (8,26): error CS0029: Cannot implicitly convert type 'string' to 'int'
// c = c with { X = "a" };
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""a""").WithArguments("string", "int").WithLocation(8, 26)
);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")]
[WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")]
public void WithExprCloneReturnDifferent()
{
var src = @"
class B
{
public int X { get; init; }
}
class C : B
{
public B Clone() => new B();
public static void Main()
{
var c = new C();
var b = c with { X = 0 };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact]
public void WithSemanticModel1()
{
var src = @"
record C(int X, string Y)
{
public static void Main()
{
var c = new C(0, ""a"");
c = c with { X = 2 };
}
}";
var comp = CreateCompilation(src);
var tree = comp.SyntaxTrees[0];
var root = tree.GetRoot();
var model = comp.GetSemanticModel(tree);
var withExpr = root.DescendantNodes().OfType<WithExpressionSyntax>().Single();
var typeInfo = model.GetTypeInfo(withExpr);
var c = comp.GlobalNamespace.GetTypeMember("C");
Assert.True(c.IsRecord);
Assert.True(c.ISymbol.Equals(typeInfo.Type));
var x = c.GetMembers("X").Single();
var xId = withExpr.DescendantNodes().Single(id => id.ToString() == "X");
var symbolInfo = model.GetSymbolInfo(xId);
Assert.True(x.ISymbol.Equals(symbolInfo.Symbol));
comp.VerifyOperationTree(withExpr, @"
IWithOperation (OperationKind.With, Type: C) (Syntax: 'c with { X = 2 }')
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
CloneMethod: C C." + WellKnownMemberNames.CloneMethodName + @"()
Initializer:
IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C) (Syntax: '{ X = 2 }')
Initializers(1):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 2')
Left:
IPropertyReferenceOperation: System.Int32 C.X { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')");
var main = root.DescendantNodes().OfType<MethodDeclarationSyntax>().Single();
Assert.Equal("Main", main.Identifier.ToString());
VerifyFlowGraph(comp, main, expectedFlowGraph: @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [C c]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'c = new C(0, ""a"")')
Left:
ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C(0, ""a"")')
Right:
IObjectCreationOperation (Constructor: C..ctor(System.Int32 X, System.String Y)) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C(0, ""a"")')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: '0')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: '""a""')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""a"") (Syntax: '""a""')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [0] [1]
Block[B2] - Block
Predecessors: [B1]
Statements (4)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c')
Value:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c with { X = 2 }')
Value:
IInvocationOperation (virtual C C." + WellKnownMemberNames.CloneMethodName + @"()) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'c with { X = 2 }')
Instance Receiver:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
Arguments(0)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 2')
Left:
IPropertyReferenceOperation: System.Int32 C.X { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c with { X = 2 }')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = c with { X = 2 };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: 'c = c with { X = 2 }')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c with { X = 2 }')
Next (Regular) Block[B3]
Leaving: {R2} {R1}
}
}
Block[B3] - Exit
Predecessors: [B2]
Statements (0)
");
}
[Fact]
public void NoCloneMethod_01()
{
var src = @"
class C
{
int X { get; set; }
public static void Main()
{
var c = new C();
c = c with { X = 2 };
}
}";
var comp = CreateCompilation(src);
var tree = comp.SyntaxTrees[0];
var root = tree.GetRoot();
var withExpr = root.DescendantNodes().OfType<WithExpressionSyntax>().Single();
comp.VerifyOperationTree(withExpr, @"
IWithOperation (OperationKind.With, Type: C, IsInvalid) (Syntax: 'c with { X = 2 }')
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c')
CloneMethod: null
Initializer:
IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C) (Syntax: '{ X = 2 }')
Initializers(1):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 2')
Left:
IPropertyReferenceOperation: System.Int32 C.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')");
var main = root.DescendantNodes().OfType<MethodDeclarationSyntax>().Single();
Assert.Equal("Main", main.Identifier.ToString());
VerifyFlowGraph(comp, main, expectedFlowGraph: @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [C c]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'c = new C()')
Left:
ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C()')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [0] [1]
Block[B2] - Block
Predecessors: [B1]
Statements (4)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c')
Value:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c')
Value:
IInvalidOperation (OperationKind.Invalid, Type: C, IsInvalid, IsImplicit) (Syntax: 'c')
Children(1):
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 2')
Left:
IPropertyReferenceOperation: System.Int32 C.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'c')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'c = c with { X = 2 };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsInvalid) (Syntax: 'c = c with { X = 2 }')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'c')
Next (Regular) Block[B3]
Leaving: {R2} {R1}
}
}
Block[B3] - Exit
Predecessors: [B2]
Statements (0)
");
}
[Fact]
public void NoCloneMethod_02()
{
var source =
@"#nullable enable
class R
{
public object? P { get; set; }
}
class Program
{
static void Main()
{
R r = new R();
_ = r with { P = 2 };
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (11,13): error CS8858: The receiver type 'R' is not a valid record type.
// _ = r with { P = 2 };
Diagnostic(ErrorCode.ERR_CannotClone, "r").WithArguments("R").WithLocation(11, 13));
}
[Fact]
public void WithBadExprArg()
{
var src = @"
record C(int X, int Y)
{
public static void Main()
{
var c = new C(0, 0);
c = c with { 5 };
c = c with { { X = 2 } };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (8,22): error CS0747: Invalid initializer member declarator
// c = c with { 5 };
Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "5").WithLocation(8, 22),
// (9,22): error CS1513: } expected
// c = c with { { X = 2 } };
Diagnostic(ErrorCode.ERR_RbraceExpected, "{").WithLocation(9, 22),
// (9,22): error CS1002: ; expected
// c = c with { { X = 2 } };
Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(9, 22),
// (9,24): error CS0120: An object reference is required for the non-static field, method, or property 'C.X'
// c = c with { { X = 2 } };
Diagnostic(ErrorCode.ERR_ObjectRequired, "X").WithArguments("C.X").WithLocation(9, 24),
// (9,30): error CS1002: ; expected
// c = c with { { X = 2 } };
Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(9, 30),
// (9,33): error CS1597: Semicolon after method or accessor block is not valid
// c = c with { { X = 2 } };
Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(9, 33),
// (11,1): error CS1022: Type or namespace definition, or end-of-file expected
// }
Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(11, 1)
);
var tree = comp.SyntaxTrees[0];
var root = tree.GetRoot();
var model = comp.GetSemanticModel(tree);
VerifyClone(model);
var withExpr1 = root.DescendantNodes().OfType<WithExpressionSyntax>().First();
comp.VerifyOperationTree(withExpr1, @"
IWithOperation (OperationKind.With, Type: C, IsInvalid) (Syntax: 'c with { 5 }')
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
CloneMethod: C C." + WellKnownMemberNames.CloneMethodName + @"()
Initializer:
IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C, IsInvalid) (Syntax: '{ 5 }')
Initializers(1):
IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '5')
Children(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5, IsInvalid) (Syntax: '5')");
var withExpr2 = root.DescendantNodes().OfType<WithExpressionSyntax>().Skip(1).Single();
comp.VerifyOperationTree(withExpr2, @"
IWithOperation (OperationKind.With, Type: C, IsInvalid) (Syntax: 'c with { ')
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
CloneMethod: C C." + WellKnownMemberNames.CloneMethodName + @"()
Initializer:
IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C, IsInvalid) (Syntax: '{ ')
Initializers(0)");
}
[Fact]
public void WithExpr_DefiniteAssignment_01()
{
var src = @"
record B(int X)
{
static void M(B b)
{
int y;
_ = b with { X = y = 42 };
y.ToString();
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact]
public void WithExpr_DefiniteAssignment_02()
{
var src = @"
record B(int X, string Y)
{
static void M(B b)
{
int z;
_ = b with { X = z = 42, Y = z.ToString() };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact]
public void WithExpr_DefiniteAssignment_03()
{
var src = @"
record B(int X, string Y)
{
static void M(B b)
{
int z;
_ = b with { Y = z.ToString(), X = z = 42 };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (7,26): error CS0165: Use of unassigned local variable 'z'
// _ = b with { Y = z.ToString(), X = z = 42 };
Diagnostic(ErrorCode.ERR_UseDefViolation, "z").WithArguments("z").WithLocation(7, 26));
}
[Fact]
public void WithExpr_DefiniteAssignment_04()
{
var src = @"
record B(int X)
{
static void M()
{
B b;
_ = (b = new B(42)) with { X = b.X };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact]
public void WithExpr_DefiniteAssignment_05()
{
var src = @"
record B(int X)
{
static void M()
{
B b;
_ = new B(b.X) with { X = (b = new B(42)).X };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (7,19): error CS0165: Use of unassigned local variable 'b'
// _ = new B(b.X) with { X = new B(42).X };
Diagnostic(ErrorCode.ERR_UseDefViolation, "b").WithArguments("b").WithLocation(7, 19));
}
[Fact]
public void WithExpr_DefiniteAssignment_06()
{
var src = @"
record B(int X)
{
static void M(B b)
{
int y;
_ = b with { X = M(out y) };
y.ToString();
}
static int M(out int y) { y = 42; return 43; }
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact]
public void WithExpr_DefiniteAssignment_07()
{
var src = @"
record B(int X)
{
static void M(B b)
{
_ = b with { X = M(out int y) };
y.ToString();
}
static int M(out int y) { y = 42; return 43; }
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact]
public void WithExpr_NullableAnalysis_01()
{
var src = @"
#nullable enable
record B(int X)
{
static void M(B b)
{
string? s = null;
_ = b with { X = M(out s) };
s.ToString();
}
static int M(out string s) { s = ""a""; return 42; }
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact]
public void WithExpr_NullableAnalysis_02()
{
var src = @"
#nullable enable
record B(string X)
{
static void M(B b, string? s)
{
b.X.ToString();
_ = b with { X = s }; // 1
b.X.ToString(); // 2
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (8,26): warning CS8601: Possible null reference assignment.
// _ = b with { X = s }; // 1
Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "s").WithLocation(8, 26));
}
[Fact]
public void WithExpr_NullableAnalysis_03()
{
var src = @"
#nullable enable
record B(string? X)
{
static void M1(B b, string s, bool flag)
{
if (flag) { b.X.ToString(); } // 1
_ = b with { X = s };
if (flag) { b.X.ToString(); } // 2
}
static void M2(B b, string s, bool flag)
{
if (flag) { b.X.ToString(); } // 3
b = b with { X = s };
if (flag) { b.X.ToString(); }
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (7,21): warning CS8602: Dereference of a possibly null reference.
// if (flag) { b.X.ToString(); } // 1
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(7, 21),
// (9,21): warning CS8602: Dereference of a possibly null reference.
// if (flag) { b.X.ToString(); } // 2
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(9, 21),
// (14,21): warning CS8602: Dereference of a possibly null reference.
// if (flag) { b.X.ToString(); } // 3
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(14, 21));
}
[Fact]
public void WithExpr_NullableAnalysis_04()
{
var src = @"
#nullable enable
record B(int X)
{
static void M1(B? b)
{
var b1 = b with { X = 42 }; // 1
_ = b.ToString();
_ = b1.ToString();
}
static void M2(B? b)
{
(b with { X = 42 }).ToString(); // 2
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (7,18): warning CS8602: Dereference of a possibly null reference.
// var b1 = b with { X = 42 }; // 1
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b").WithLocation(7, 18),
// (14,10): warning CS8602: Dereference of a possibly null reference.
// (b with { X = 42 }).ToString(); // 2
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b").WithLocation(14, 10));
}
[Fact, WorkItem(44763, "https://github.com/dotnet/roslyn/issues/44763")]
public void WithExpr_NullableAnalysis_05()
{
var src = @"
#nullable enable
record B(string? X, string? Y)
{
static void M1(bool flag)
{
B b = new B(""hello"", null);
if (flag)
{
b.X.ToString(); // shouldn't warn
b.Y.ToString(); // 1
}
b = b with { Y = ""world"" };
b.X.ToString(); // shouldn't warn
b.Y.ToString();
}
}";
// records should propagate the nullability of the
// constructor arguments to the corresponding properties.
// https://github.com/dotnet/roslyn/issues/44763
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (10,13): warning CS8602: Dereference of a possibly null reference.
// b.X.ToString(); // shouldn't warn
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(10, 13),
// (11,13): warning CS8602: Dereference of a possibly null reference.
// b.Y.ToString(); // 1
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Y").WithLocation(11, 13),
// (15,9): warning CS8602: Dereference of a possibly null reference.
// b.X.ToString(); // shouldn't warn
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(15, 9));
}
[Fact]
public void WithExpr_NullableAnalysis_06()
{
var src = @"
#nullable enable
record B
{
public string? X { get; init; }
public string? Y { get; init; }
static void M1(bool flag)
{
B b = new B { X = ""hello"", Y = null };
if (flag)
{
b.X.ToString();
b.Y.ToString(); // 1
}
b = b with { Y = ""world"" };
b.X.ToString();
b.Y.ToString();
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (14,13): warning CS8602: Dereference of a possibly null reference.
// b.Y.ToString(); // 1
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Y").WithLocation(14, 13)
);
}
[Fact, WorkItem(44691, "https://github.com/dotnet/roslyn/issues/44691")]
public void WithExpr_NullableAnalysis_07()
{
var src = @"
#nullable enable
using System.Diagnostics.CodeAnalysis;
record B([AllowNull] string X) // 1
{
static void M1(B b)
{
b.X.ToString();
b = b with { X = null }; // 2
b.X.ToString(); // 3
b = new B((string?)null);
b.X.ToString();
}
}";
var comp = CreateCompilation(new[] { src, AllowNullAttributeDefinition });
comp.VerifyDiagnostics(
// (5,10): warning CS8601: Possible null reference assignment.
// record B([AllowNull] string X) // 1
Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "[AllowNull] string X").WithLocation(5, 10),
// (10,26): warning CS8625: Cannot convert null literal to non-nullable reference type.
// b = b with { X = null }; // 2
Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 26),
// (11,9): warning CS8602: Dereference of a possibly null reference.
// b.X.ToString(); // 3
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(11, 9));
}
[Fact, WorkItem(44691, "https://github.com/dotnet/roslyn/issues/44691")]
public void WithExpr_NullableAnalysis_08()
{
var src = @"
#nullable enable
using System.Diagnostics.CodeAnalysis;
record B([property: AllowNull][AllowNull] string X)
{
static void M1(B b)
{
b.X.ToString();
b = b with { X = null };
b.X.ToString(); // 1
b = new B((string?)null);
b.X.ToString();
}
}";
var comp = CreateCompilation(new[] { src, AllowNullAttributeDefinition });
comp.VerifyDiagnostics(
// (11,9): warning CS8602: Dereference of a possibly null reference.
// b.X.ToString(); // 1
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(11, 9));
}
[Fact]
public void WithExpr_NullableAnalysis_09()
{
var src = @"
#nullable enable
record B(string? X, string? Y)
{
static void M1(B b1)
{
B b2 = b1 with { X = ""hello"" };
B b3 = b1 with { Y = ""world"" };
B b4 = b2 with { Y = ""world"" };
b1.X.ToString(); // 1
b1.Y.ToString(); // 2
b2.X.ToString();
b2.Y.ToString(); // 3
b3.X.ToString(); // 4
b3.Y.ToString();
b4.X.ToString();
b4.Y.ToString();
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (11,9): warning CS8602: Dereference of a possibly null reference.
// b1.X.ToString(); // 1
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b1.X").WithLocation(11, 9),
// (12,9): warning CS8602: Dereference of a possibly null reference.
// b1.Y.ToString(); // 2
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b1.Y").WithLocation(12, 9),
// (14,9): warning CS8602: Dereference of a possibly null reference.
// b2.Y.ToString(); // 3
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b2.Y").WithLocation(14, 9),
// (15,9): warning CS8602: Dereference of a possibly null reference.
// b3.X.ToString(); // 4
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b3.X").WithLocation(15, 9));
}
[Fact]
public void WithExpr_NullableAnalysis_10()
{
var src = @"
#nullable enable
record B(string? X, string? Y)
{
static void M1(B b1)
{
string? local = ""hello"";
_ = b1 with
{
X = local = null,
Y = local.ToString() // 1
};
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (11,17): warning CS8602: Dereference of a possibly null reference.
// Y = local.ToString() // 1
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "local").WithLocation(11, 17));
}
[Fact]
public void WithExpr_NullableAnalysis_11()
{
var src = @"
#nullable enable
record B(string X, string Y)
{
static string M0(out string? s) { s = null; return ""hello""; }
static void M1(B b1)
{
string? local = ""world"";
_ = b1 with
{
X = M0(out local),
Y = local // 1
};
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (13,17): warning CS8601: Possible null reference assignment.
// Y = local // 1
Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "local").WithLocation(13, 17));
}
[Fact]
public void WithExpr_NullableAnalysis_VariantClone()
{
var src = @"
#nullable enable
record A
{
public string? Y { get; init; }
public string? Z { get; init; }
}
record B(string? X) : A
{
public new string Z { get; init; } = ""zed"";
static void M1(B b1)
{
b1.Z.ToString();
(b1 with { Y = ""hello"" }).Y.ToString();
(b1 with { Y = ""hello"" }).Z.ToString();
}
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")]
[WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")]
public void WithExpr_NullableAnalysis_NullableClone()
{
var src = @"
#nullable enable
record B(string? X)
{
public B? Clone() => new B(X);
static void M1(B b1)
{
_ = b1 with { X = null }; // 1
(b1 with { X = null }).ToString(); // 2
}
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (10,21): warning CS8602: Dereference of a possibly null reference.
// _ = b1 with { X = null }; // 1
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "{ X = null }").WithLocation(10, 21),
// (11,18): warning CS8602: Dereference of a possibly null reference.
// (b1 with { X = null }).ToString(); // 2
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "{ X = null }").WithLocation(11, 18));
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")]
[WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")]
public void WithExpr_NullableAnalysis_MaybeNullClone()
{
var src = @"
#nullable enable
using System.Diagnostics.CodeAnalysis;
record B(string? X)
{
[return: MaybeNull]
public B Clone() => new B(X);
static void M1(B b1)
{
_ = b1 with { };
_ = b1 with { X = null }; // 1
(b1 with { X = null }).ToString(); // 2
}
}
";
var comp = CreateCompilation(new[] { src, MaybeNullAttributeDefinition });
comp.VerifyDiagnostics(
// (13,21): warning CS8602: Dereference of a possibly null reference.
// _ = b1 with { X = null }; // 1
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "{ X = null }").WithLocation(13, 21),
// (14,18): warning CS8602: Dereference of a possibly null reference.
// (b1 with { X = null }).ToString(); // 2
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "{ X = null }").WithLocation(14, 18));
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")]
[WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")]
public void WithExpr_NullableAnalysis_NotNullClone()
{
var src = @"
#nullable enable
using System.Diagnostics.CodeAnalysis;
record B(string? X)
{
[return: NotNull]
public B? Clone() => new B(X);
static void M1(B b1)
{
_ = b1 with { };
_ = b1 with { X = null };
(b1 with { X = null }).ToString();
}
}
";
var comp = CreateCompilation(new[] { src, NotNullAttributeDefinition });
comp.VerifyDiagnostics();
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")]
[WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")]
public void WithExpr_NullableAnalysis_NullableClone_NoInitializers()
{
var src = @"
#nullable enable
record B(string? X)
{
public B? Clone() => new B(X);
static void M1(B b1)
{
_ = b1 with { };
(b1 with { }).ToString(); // 1
}
}
";
var comp = CreateCompilation(src);
// Note: we expect to give a warning on `// 1`, but do not currently
// due to limitations of object initializer analysis.
// Tracking in https://github.com/dotnet/roslyn/issues/44759
comp.VerifyDiagnostics();
}
[Fact]
public void WithExprNominalRecord()
{
var src = @"
using System;
record C
{
public int X { get; set; }
public string Y { get; init; }
public long Z;
public event Action E;
public C() { }
public C(C other)
{
X = other.X;
Y = other.Y;
Z = other.Z;
E = other.E;
}
public static void Main()
{
var c = new C() { X = 1, Y = ""2"", Z = 3, E = () => { } };
var c2 = c with {};
Console.WriteLine(c.Equals(c2));
Console.WriteLine(ReferenceEquals(c, c2));
Console.WriteLine(c2.X);
Console.WriteLine(c2.Y);
Console.WriteLine(c2.Z);
Console.WriteLine(ReferenceEquals(c.E, c2.E));
var c3 = c with { Y = ""3"", X = 2 };
Console.WriteLine(c.Y);
Console.WriteLine(c3.Y);
Console.WriteLine(c.X);
Console.WriteLine(c3.X);
}
}";
var verifier = CompileAndVerify(src, expectedOutput: @"
True
False
1
2
3
True
2
3
1
2").VerifyDiagnostics();
}
[Fact]
public void WithExprNominalRecord2()
{
var comp1 = CreateCompilation(@"
public record C
{
public int X { get; set; }
public string Y { get; init; }
public long Z;
public C() { }
public C(C other)
{
X = other.X;
Y = other.Y;
Z = other.Z;
}
}");
var verifier = CompileAndVerify(@"
class D
{
public C M(C c) => c with
{
X = 5,
Y = ""a"",
Z = 2,
};
}", references: new[] { comp1.EmitToImageReference() }).VerifyDiagnostics();
verifier.VerifyIL("D.M", @"
{
// Code size 33 (0x21)
.maxstack 3
IL_0000: ldarg.1
IL_0001: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()""
IL_0006: dup
IL_0007: ldc.i4.5
IL_0008: callvirt ""void C.X.set""
IL_000d: dup
IL_000e: ldstr ""a""
IL_0013: callvirt ""void C.Y.init""
IL_0018: dup
IL_0019: ldc.i4.2
IL_001a: conv.i8
IL_001b: stfld ""long C.Z""
IL_0020: ret
}");
}
[Fact]
public void WithExprAssignToRef1()
{
var src = @"
using System;
record C(int Y)
{
private readonly int[] _a = new[] { 0 };
public ref int X => ref _a[0];
public static void Main()
{
var c = new C(0) { X = 5 };
Console.WriteLine(c.X);
c = c with { X = 1 };
Console.WriteLine(c.X);
}
}";
var verifier = CompileAndVerify(src, expectedOutput: @"
5
1").VerifyDiagnostics();
verifier.VerifyIL("C.Main", @"
{
// Code size 51 (0x33)
.maxstack 3
IL_0000: ldc.i4.0
IL_0001: newobj ""C..ctor(int)""
IL_0006: dup
IL_0007: callvirt ""ref int C.X.get""
IL_000c: ldc.i4.5
IL_000d: stind.i4
IL_000e: dup
IL_000f: callvirt ""ref int C.X.get""
IL_0014: ldind.i4
IL_0015: call ""void System.Console.WriteLine(int)""
IL_001a: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()""
IL_001f: dup
IL_0020: callvirt ""ref int C.X.get""
IL_0025: ldc.i4.1
IL_0026: stind.i4
IL_0027: callvirt ""ref int C.X.get""
IL_002c: ldind.i4
IL_002d: call ""void System.Console.WriteLine(int)""
IL_0032: ret
}");
}
[Fact]
public void WithExprAssignToRef2()
{
var src = @"
using System;
record C(int Y)
{
private readonly int[] _a = new[] { 0 };
public ref int X
{
get => ref _a[0];
set { }
}
public static void Main()
{
var a = new[] { 0 };
var c = new C(0) { X = ref a[0] };
Console.WriteLine(c.X);
c = c with { X = ref a[0] };
Console.WriteLine(c.X);
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (9,9): error CS8147: Properties which return by reference cannot have set accessors
// set { }
Diagnostic(ErrorCode.ERR_RefPropertyCannotHaveSetAccessor, "set").WithArguments("C.X.set").WithLocation(9, 9),
// (15,32): error CS1525: Invalid expression term 'ref'
// var c = new C(0) { X = ref a[0] };
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "ref a[0]").WithArguments("ref").WithLocation(15, 32),
// (15,32): error CS1073: Unexpected token 'ref'
// var c = new C(0) { X = ref a[0] };
Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(15, 32),
// (17,26): error CS1073: Unexpected token 'ref'
// c = c with { X = ref a[0] };
Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(17, 26)
);
}
[Fact]
public void WithExpressionSameLHS()
{
var comp = CreateCompilation(@"
record C(int X)
{
public static void Main()
{
var c = new C(0);
c = c with { X = 1, X = 2};
}
}");
comp.VerifyDiagnostics(
// (7,29): error CS1912: Duplicate initialization of member 'X'
// c = c with { X = 1, X = 2};
Diagnostic(ErrorCode.ERR_MemberAlreadyInitialized, "X").WithArguments("X").WithLocation(7, 29)
);
}
[Fact]
public void WithExpr_ValEscape()
{
var text = @"
using System;
record R
{
public S1 Property { set { throw null; } }
}
class Program
{
static void Main()
{
var r = new R();
Span<int> local = stackalloc int[1];
_ = r with { Property = MayWrap(ref local) };
_ = new R() { Property = MayWrap(ref local) };
}
static S1 MayWrap(ref Span<int> arg)
{
return default;
}
}
ref struct S1
{
public ref int this[int i] => throw null;
}
";
CreateCompilationWithMscorlibAndSpan(text).VerifyDiagnostics();
}
[WorkItem(44616, "https://github.com/dotnet/roslyn/issues/44616")]
[Fact]
public void Inheritance_01()
{
var source =
@"record A
{
internal A() { }
public object P1 { get; set; }
internal object P2 { get; set; }
protected internal object P3 { get; set; }
protected object P4 { get; set; }
private protected object P5 { get; set; }
private object P6 { get; set; }
}
record B(object P1, object P2, object P3, object P4, object P5, object P6) : A
{
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (11,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(11, 17),
// (11,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(11, 28),
// (11,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(11, 39),
// (11,50): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(11, 50),
// (11,61): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(11, 61)
);
var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type B.EqualityContract { get; }",
"System.Object B.P6 { get; init; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[WorkItem(44616, "https://github.com/dotnet/roslyn/issues/44616")]
[Fact]
public void Inheritance_02()
{
var source =
@"record A
{
internal A() { }
private protected object P1 { get; set; }
private object P2 { get; set; }
private record B(object P1, object P2) : A
{
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,29): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// private record B(object P1, object P2) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(6, 29),
// (6,40): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// private record B(object P1, object P2) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(6, 40)
);
var actualMembers = GetProperties(comp, "A.B").ToTestDisplayStrings();
AssertEx.Equal(new[] { "System.Type A.B.EqualityContract { get; }" }, actualMembers);
}
[WorkItem(44616, "https://github.com/dotnet/roslyn/issues/44616")]
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Inheritance_03(bool useCompilationReference)
{
var sourceA =
@"public record A
{
public A() { }
internal object P { get; set; }
}
public record B(object Q) : A
{
public B() : this(null) { }
}
record C1(object P, object Q) : B
{
}";
var comp = CreateCompilation(sourceA);
AssertEx.Equal(new[] { "System.Type C1.EqualityContract { get; }" }, GetProperties(comp, "C1").ToTestDisplayStrings());
var refA = useCompilationReference ? comp.ToMetadataReference() : comp.EmitToImageReference();
var sourceB =
@"record C2(object P, object Q) : B
{
}";
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (1,28): warning CS8907: Parameter 'Q' is unread. Did you forget to use it to initialize the property with that name?
// record C2(object P, object Q) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Q").WithArguments("Q").WithLocation(1, 28)
);
AssertEx.Equal(new[] { "System.Type C2.EqualityContract { get; }", "System.Object C2.P { get; init; }" }, GetProperties(comp, "C2").ToTestDisplayStrings());
}
[WorkItem(44616, "https://github.com/dotnet/roslyn/issues/44616")]
[Fact]
public void Inheritance_04()
{
var source =
@"record A
{
internal A() { }
public object P1 { get { return null; } set { } }
public object P2 { get; init; }
public object P3 { get; }
public object P4 { set { } }
public virtual object P5 { get; set; }
public static object P6 { get; set; }
public ref object P7 => throw null;
}
record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A
{
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (12,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(12, 17),
// (12,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(12, 28),
// (12,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(12, 39),
// (12,50): error CS8866: Record member 'A.P4' must be a readable instance property or field of type 'object' to match positional parameter 'P4'.
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P4").WithArguments("A.P4", "object", "P4").WithLocation(12, 50),
// (12,50): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(12, 50),
// (12,61): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(12, 61),
// (12,72): error CS8866: Record member 'A.P6' must be a readable instance property or field of type 'object' to match positional parameter 'P6'.
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P6").WithArguments("A.P6", "object", "P6").WithLocation(12, 72),
// (12,72): warning CS8907: Parameter 'P6' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P6").WithArguments("P6").WithLocation(12, 72),
// (12,83): warning CS8907: Parameter 'P7' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P7").WithArguments("P7").WithLocation(12, 83));
var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings();
AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers);
}
[Fact]
public void Inheritance_05()
{
var source =
@"record A
{
internal A() { }
public object P1 { get; set; }
public int P2 { get; set; }
}
record B(int P1, object P2) : A
{
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (7,14): error CS8866: Record member 'A.P1' must be a readable instance property or field of type 'int' to match positional parameter 'P1'.
// record B(int P1, object P2) : A
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("A.P1", "int", "P1").WithLocation(7, 14),
// (7,14): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record B(int P1, object P2) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(7, 14),
// (7,25): error CS8866: Record member 'A.P2' must be a readable instance property or field of type 'object' to match positional parameter 'P2'.
// record B(int P1, object P2) : A
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P2").WithArguments("A.P2", "object", "P2").WithLocation(7, 25),
// (7,25): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record B(int P1, object P2) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(7, 25));
var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings();
AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers);
}
[Fact]
public void Inheritance_06()
{
var source =
@"record A
{
internal int X { get; set; }
internal int Y { set { } }
internal int Z;
}
record B(int X, int Y, int Z) : A
{
}
class Program
{
static void Main()
{
var b = new B(1, 2, 3);
b.X = 4;
b.Y = 5;
b.Z = 6;
((A)b).X = 7;
((A)b).Y = 8;
((A)b).Z = 9;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (7,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record B(int X, int Y, int Z) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(7, 14),
// (7,21): error CS8866: Record member 'A.Y' must be a readable instance property or field of type 'int' to match positional parameter 'Y'.
// record B(int X, int Y, int Z) : A
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Y").WithArguments("A.Y", "int", "Y").WithLocation(7, 21),
// (7,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// record B(int X, int Y, int Z) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(7, 21),
// (7,24): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater.
// record B(int X, int Y, int Z) : A
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int Z").WithArguments("positional fields in records", "10.0").WithLocation(7, 24),
// (7,28): warning CS8907: Parameter 'Z' is unread. Did you forget to use it to initialize the property with that name?
// record B(int X, int Y, int Z) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Z").WithArguments("Z").WithLocation(7, 28));
var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings();
AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers);
}
[WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")]
[Fact]
public void Inheritance_07()
{
var source =
@"abstract record A
{
public abstract int X { get; }
public virtual int Y { get; }
}
abstract record B1(int X, int Y) : A
{
}
record B2(int X, int Y) : A
{
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,24): error CS0546: 'B1.X.init': cannot override because 'A.X' does not have an overridable set accessor
// abstract record B1(int X, int Y) : A
Diagnostic(ErrorCode.ERR_NoSetToOverride, "X").WithArguments("B1.X.init", "A.X").WithLocation(6, 24),
// (6,31): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// abstract record B1(int X, int Y) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(6, 31),
// (9,15): error CS0546: 'B2.X.init': cannot override because 'A.X' does not have an overridable set accessor
// record B2(int X, int Y) : A
Diagnostic(ErrorCode.ERR_NoSetToOverride, "X").WithArguments("B2.X.init", "A.X").WithLocation(9, 15),
// (9,22): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// record B2(int X, int Y) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(9, 22));
AssertEx.Equal(new[] { "System.Type B1.EqualityContract { get; }", "System.Int32 B1.X { get; init; }" }, GetProperties(comp, "B1").ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.Type B2.EqualityContract { get; }", "System.Int32 B2.X { get; init; }" }, GetProperties(comp, "B2").ToTestDisplayStrings());
var b1Ctor = comp.GetTypeByMetadataName("B1")!.GetMembersUnordered().OfType<SynthesizedRecordConstructor>().Single();
Assert.Equal("B1..ctor(System.Int32 X, System.Int32 Y)", b1Ctor.ToTestDisplayString());
Assert.Equal(Accessibility.Protected, b1Ctor.DeclaredAccessibility);
}
[WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")]
[Fact]
public void Inheritance_08()
{
var source =
@"abstract record A
{
public abstract int X { get; }
public virtual int Y { get; }
public virtual int Z { get; }
}
abstract record B : A
{
public override abstract int Y { get; }
}
record C(int X, int Y, int Z) : B
{
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (11,14): error CS0546: 'C.X.init': cannot override because 'A.X' does not have an overridable set accessor
// record C(int X, int Y, int Z) : B
Diagnostic(ErrorCode.ERR_NoSetToOverride, "X").WithArguments("C.X.init", "A.X").WithLocation(11, 14),
// (11,21): error CS0546: 'C.Y.init': cannot override because 'B.Y' does not have an overridable set accessor
// record C(int X, int Y, int Z) : B
Diagnostic(ErrorCode.ERR_NoSetToOverride, "Y").WithArguments("C.Y.init", "B.Y").WithLocation(11, 21),
// (11,28): warning CS8907: Parameter 'Z' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X, int Y, int Z) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Z").WithArguments("Z").WithLocation(11, 28));
var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings();
AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }", "System.Int32 C.X { get; init; }", "System.Int32 C.Y { get; init; }" }, actualMembers);
}
[Fact, WorkItem(48947, "https://github.com/dotnet/roslyn/issues/48947")]
public void Inheritance_09()
{
var source =
@"abstract record C(int X, int Y)
{
public abstract int X { get; }
public virtual int Y { get; }
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (1,23): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// abstract record C(int X, int Y)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(1, 23),
// (1,30): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// abstract record C(int X, int Y)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(1, 30)
);
NamedTypeSymbol c = comp.GetMember<NamedTypeSymbol>("C");
var actualMembers = c.GetMembers().ToTestDisplayStrings();
var expectedMembers = new[]
{
"C..ctor(System.Int32 X, System.Int32 Y)",
"System.Type C.EqualityContract.get",
"System.Type C.EqualityContract { get; }",
"System.Int32 C.X { get; }",
"System.Int32 C.X.get",
"System.Int32 C.<Y>k__BackingField",
"System.Int32 C.Y { get; }",
"System.Int32 C.Y.get",
"System.String C.ToString()",
"System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)",
"System.Boolean C.op_Inequality(C? left, C? right)",
"System.Boolean C.op_Equality(C? left, C? right)",
"System.Int32 C.GetHashCode()",
"System.Boolean C.Equals(System.Object? obj)",
"System.Boolean C.Equals(C? other)",
"C C." + WellKnownMemberNames.CloneMethodName + "()",
"C..ctor(C original)",
"void C.Deconstruct(out System.Int32 X, out System.Int32 Y)"
};
AssertEx.Equal(expectedMembers, actualMembers);
var expectedMemberNames = new[] {
".ctor",
"get_EqualityContract",
"EqualityContract",
"X",
"get_X",
"<Y>k__BackingField",
"Y",
"get_Y",
"ToString",
"PrintMembers",
"op_Inequality",
"op_Equality",
"GetHashCode",
"Equals",
"Equals",
"<Clone>$",
".ctor",
"Deconstruct"
};
AssertEx.Equal(expectedMemberNames, c.GetPublicSymbol().MemberNames);
var expectedCtors = new[]
{
"C..ctor(System.Int32 X, System.Int32 Y)",
"C..ctor(C original)",
};
AssertEx.Equal(expectedCtors, c.GetPublicSymbol().Constructors.ToTestDisplayStrings());
}
[Fact]
public void Inheritance_10()
{
var source =
@"using System;
interface IA
{
int X { get; }
}
interface IB
{
int Y { get; }
}
record C(int X, int Y) : IA, IB
{
}
class Program
{
static void Main()
{
var c = new C(1, 2);
Console.WriteLine(""{0}, {1}"", c.X, c.Y);
Console.WriteLine(""{0}, {1}"", ((IA)c).X, ((IB)c).Y);
}
}";
CompileAndVerify(source, expectedOutput:
@"1, 2
1, 2").VerifyDiagnostics();
}
[Fact]
public void Inheritance_11()
{
var source =
@"interface IA
{
int X { get; }
}
interface IB
{
object Y { get; set; }
}
record C(object X, object Y) : IA, IB
{
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (9,32): error CS0738: 'C' does not implement interface member 'IA.X'. 'C.X' cannot implement 'IA.X' because it does not have the matching return type of 'int'.
// record C(object X, object Y) : IA, IB
Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "IA").WithArguments("C", "IA.X", "C.X", "int").WithLocation(9, 32),
// (9,36): error CS8854: 'C' does not implement interface member 'IB.Y.set'. 'C.Y.init' cannot implement 'IB.Y.set'.
// record C(object X, object Y) : IA, IB
Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "IB").WithArguments("C", "IB.Y.set", "C.Y.init").WithLocation(9, 36)
);
}
[Fact]
public void Inheritance_12()
{
var source =
@"record A
{
public object X { get; }
public object Y { get; }
}
record B(object X, object Y) : A
{
public object X { get; }
public object Y { get; }
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,17): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record B(object X, object Y) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(6, 17),
// (6,27): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// record B(object X, object Y) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(6, 27),
// (8,19): warning CS0108: 'B.X' hides inherited member 'A.X'. Use the new keyword if hiding was intended.
// public object X { get; }
Diagnostic(ErrorCode.WRN_NewRequired, "X").WithArguments("B.X", "A.X").WithLocation(8, 19),
// (9,19): warning CS0108: 'B.Y' hides inherited member 'A.Y'. Use the new keyword if hiding was intended.
// public object Y { get; }
Diagnostic(ErrorCode.WRN_NewRequired, "Y").WithArguments("B.Y", "A.Y").WithLocation(9, 19));
var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type B.EqualityContract { get; }",
"System.Object B.X { get; }",
"System.Object B.Y { get; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void Inheritance_13()
{
var source =
@"record A(object X, object Y)
{
internal A() : this(null, null) { }
}
record B(object X, object Y) : A
{
public object X { get; }
public object Y { get; }
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (5,17): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record B(object X, object Y) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(5, 17),
// (5,27): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// record B(object X, object Y) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(5, 27),
// (7,19): warning CS0108: 'B.X' hides inherited member 'A.X'. Use the new keyword if hiding was intended.
// public object X { get; }
Diagnostic(ErrorCode.WRN_NewRequired, "X").WithArguments("B.X", "A.X").WithLocation(7, 19),
// (8,19): warning CS0108: 'B.Y' hides inherited member 'A.Y'. Use the new keyword if hiding was intended.
// public object Y { get; }
Diagnostic(ErrorCode.WRN_NewRequired, "Y").WithArguments("B.Y", "A.Y").WithLocation(8, 19));
var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type B.EqualityContract { get; }",
"System.Object B.X { get; }",
"System.Object B.Y { get; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void Inheritance_14()
{
var source =
@"record A
{
public object P1 { get; }
public object P2 { get; }
public object P3 { get; }
public object P4 { get; }
}
record B : A
{
public new int P1 { get; }
public new int P2 { get; }
}
record C(object P1, int P2, object P3, int P4) : B
{
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (13,17): error CS8866: Record member 'B.P1' must be a readable instance property or field of type 'object' to match positional parameter 'P1'.
// record C(object P1, int P2, object P3, int P4) : B
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("B.P1", "object", "P1").WithLocation(13, 17),
// (13,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, int P2, object P3, int P4) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(13, 17),
// (13,25): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, int P2, object P3, int P4) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(13, 25),
// (13,36): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, int P2, object P3, int P4) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(13, 36),
// (13,44): error CS8866: Record member 'A.P4' must be a readable instance property or field of type 'int' to match positional parameter 'P4'.
// record C(object P1, int P2, object P3, int P4) : B
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P4").WithArguments("A.P4", "int", "P4").WithLocation(13, 44),
// (13,44): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, int P2, object P3, int P4) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(13, 44));
var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings();
AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }" }, actualMembers);
}
[Fact]
public void Inheritance_15()
{
var source =
@"record C(int P1, object P2)
{
public object P1 { get; set; }
public int P2 { get; set; }
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (1,14): error CS8866: Record member 'C.P1' must be a readable instance property or field of type 'int' to match positional parameter 'P1'.
// record C(int P1, object P2)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("C.P1", "int", "P1").WithLocation(1, 14),
// (1,14): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record C(int P1, object P2)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(1, 14),
// (1,25): error CS8866: Record member 'C.P2' must be a readable instance property or field of type 'object' to match positional parameter 'P2'.
// record C(int P1, object P2)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P2").WithArguments("C.P2", "object", "P2").WithLocation(1, 25),
// (1,25): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record C(int P1, object P2)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 25));
var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type C.EqualityContract { get; }",
"System.Object C.P1 { get; set; }",
"System.Int32 C.P2 { get; set; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void Inheritance_16()
{
var source =
@"record A
{
public int P1 { get; }
public int P2 { get; }
public int P3 { get; }
public int P4 { get; }
}
record B(object P1, int P2, object P3, int P4) : A
{
public new object P1 { get; }
public new object P2 { get; }
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, int P2, object P3, int P4) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(8, 17),
// (8,25): error CS8866: Record member 'B.P2' must be a readable instance property or field of type 'int' to match positional parameter 'P2'.
// record B(object P1, int P2, object P3, int P4) : A
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P2").WithArguments("B.P2", "int", "P2").WithLocation(8, 25),
// (8,25): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, int P2, object P3, int P4) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(8, 25),
// (8,36): error CS8866: Record member 'A.P3' must be a readable instance property or field of type 'object' to match positional parameter 'P3'.
// record B(object P1, int P2, object P3, int P4) : A
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P3").WithArguments("A.P3", "object", "P3").WithLocation(8, 36),
// (8,36): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, int P2, object P3, int P4) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(8, 36),
// (8,44): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, int P2, object P3, int P4) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(8, 44));
var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type B.EqualityContract { get; }",
"System.Object B.P1 { get; }",
"System.Object B.P2 { get; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void Inheritance_17()
{
var source =
@"record A
{
public object P1 { get; }
public object P2 { get; }
public object P3 { get; }
public object P4 { get; }
}
record B(object P1, int P2, object P3, int P4) : A
{
public new int P1 { get; }
public new int P2 { get; }
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,17): error CS8866: Record member 'B.P1' must be a readable instance property or field of type 'object' to match positional parameter 'P1'.
// record B(object P1, int P2, object P3, int P4) : A
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("B.P1", "object", "P1").WithLocation(8, 17),
// (8,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, int P2, object P3, int P4) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(8, 17),
// (8,25): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, int P2, object P3, int P4) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(8, 25),
// (8,36): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, int P2, object P3, int P4) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(8, 36),
// (8,44): error CS8866: Record member 'A.P4' must be a readable instance property or field of type 'int' to match positional parameter 'P4'.
// record B(object P1, int P2, object P3, int P4) : A
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P4").WithArguments("A.P4", "int", "P4").WithLocation(8, 44),
// (8,44): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, int P2, object P3, int P4) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(8, 44));
var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type B.EqualityContract { get; }",
"System.Int32 B.P1 { get; }",
"System.Int32 B.P2 { get; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void Inheritance_18()
{
var source =
@"record C(object P1, object P2, object P3, object P4, object P5)
{
public object P1 { get { return null; } set { } }
public object P2 { get; }
public object P3 { set { } }
public static object P4 { get; set; }
public ref object P5 => throw null;
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (1,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, object P2, object P3, object P4, object P5)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(1, 17),
// (1,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, object P2, object P3, object P4, object P5)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 28),
// (1,39): error CS8866: Record member 'C.P3' must be a readable instance property or field of type 'object' to match positional parameter 'P3'.
// record C(object P1, object P2, object P3, object P4, object P5)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P3").WithArguments("C.P3", "object", "P3").WithLocation(1, 39),
// (1,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, object P2, object P3, object P4, object P5)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(1, 39),
// (1,50): error CS8866: Record member 'C.P4' must be a readable instance property or field of type 'object' to match positional parameter 'P4'.
// record C(object P1, object P2, object P3, object P4, object P5)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P4").WithArguments("C.P4", "object", "P4").WithLocation(1, 50),
// (1,50): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, object P2, object P3, object P4, object P5)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(1, 50),
// (1,61): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, object P2, object P3, object P4, object P5)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(1, 61));
var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type C.EqualityContract { get; }",
"System.Object C.P1 { get; set; }",
"System.Object C.P2 { get; }",
"System.Object C.P3 { set; }",
"System.Object C.P4 { get; set; }",
"ref System.Object C.P5 { get; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void Inheritance_19()
{
var source =
@"#pragma warning disable 8618
#nullable enable
record A
{
internal A() { }
public object P1 { get; }
public dynamic[] P2 { get; }
public object? P3 { get; }
public object[] P4 { get; }
public (int X, int Y) P5 { get; }
public (int, int)[] P6 { get; }
public nint P7 { get; }
public System.UIntPtr[] P8 { get; }
}
record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A
{
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (15,18): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(15, 18),
// (15,31): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(15, 31),
// (15,42): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name?
// record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(15, 42),
// (15,56): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name?
// record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(15, 56),
// (15,71): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name?
// record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(15, 71),
// (15,92): warning CS8907: Parameter 'P6' is unread. Did you forget to use it to initialize the property with that name?
// record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P6").WithArguments("P6").WithLocation(15, 92),
// (15,110): warning CS8907: Parameter 'P7' is unread. Did you forget to use it to initialize the property with that name?
// record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P7").WithArguments("P7").WithLocation(15, 110),
// (15,122): warning CS8907: Parameter 'P8' is unread. Did you forget to use it to initialize the property with that name?
// record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P8").WithArguments("P8").WithLocation(15, 122)
);
var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings();
AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers);
}
[Fact]
public void Inheritance_20()
{
var source =
@"#pragma warning disable 8618
#nullable enable
record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8)
{
public object P1 { get; }
public dynamic[] P2 { get; }
public object? P3 { get; }
public object[] P4 { get; }
public (int X, int Y) P5 { get; }
public (int, int)[] P6 { get; }
public nint P7 { get; }
public System.UIntPtr[] P8 { get; }
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (3,18): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(3, 18),
// (3,31): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(3, 31),
// (3,42): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name?
// record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(3, 42),
// (3,56): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name?
// record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(3, 56),
// (3,71): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name?
// record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(3, 71),
// (3,92): warning CS8907: Parameter 'P6' is unread. Did you forget to use it to initialize the property with that name?
// record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P6").WithArguments("P6").WithLocation(3, 92),
// (3,110): warning CS8907: Parameter 'P7' is unread. Did you forget to use it to initialize the property with that name?
// record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P7").WithArguments("P7").WithLocation(3, 110),
// (3,122): warning CS8907: Parameter 'P8' is unread. Did you forget to use it to initialize the property with that name?
// record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P8").WithArguments("P8").WithLocation(3, 122)
);
var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type C.EqualityContract { get; }",
"System.Object C.P1 { get; }",
"dynamic[] C.P2 { get; }",
"System.Object? C.P3 { get; }",
"System.Object[] C.P4 { get; }",
"(System.Int32 X, System.Int32 Y) C.P5 { get; }",
"(System.Int32, System.Int32)[] C.P6 { get; }",
"nint C.P7 { get; }",
"System.UIntPtr[] C.P8 { get; }"
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Inheritance_21(bool useCompilationReference)
{
var sourceA =
@"public record A
{
public object P1 { get; }
internal object P2 { get; }
}
public record B : A
{
internal new object P1 { get; }
public new object P2 { get; }
}";
var comp = CreateCompilation(sourceA);
var refA = useCompilationReference ? comp.ToMetadataReference() : comp.EmitToImageReference();
var sourceB =
@"record C(object P1, object P2) : B
{
}
class Program
{
static void Main()
{
var c = new C(1, 2);
System.Console.WriteLine(""({0}, {1})"", c.P1, c.P2);
}
}";
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings();
AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }" }, actualMembers);
var verifier = CompileAndVerify(comp, expectedOutput: "(, )").VerifyDiagnostics(
// (1,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, object P2) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(1, 17),
// (1,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, object P2) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 28)
);
verifier.VerifyIL("C..ctor(object, object)",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""B..ctor()""
IL_0006: ret
}");
verifier.VerifyIL("C..ctor(C)", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""B..ctor(B)""
IL_0007: ret
}");
verifier.VerifyIL("Program.Main",
@"{
// Code size 41 (0x29)
.maxstack 3
.locals init (C V_0) //c
IL_0000: ldc.i4.1
IL_0001: box ""int""
IL_0006: ldc.i4.2
IL_0007: box ""int""
IL_000c: newobj ""C..ctor(object, object)""
IL_0011: stloc.0
IL_0012: ldstr ""({0}, {1})""
IL_0017: ldloc.0
IL_0018: callvirt ""object A.P1.get""
IL_001d: ldloc.0
IL_001e: callvirt ""object B.P2.get""
IL_0023: call ""void System.Console.WriteLine(string, object, object)""
IL_0028: ret
}");
}
[Fact]
public void Inheritance_22()
{
var source =
@"record A
{
public ref object P1 => throw null;
public object P2 => throw null;
}
record B : A
{
public new object P1 => throw null;
public new ref object P2 => throw null;
}
record C(object P1, object P2) : B
{
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (11,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, object P2) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(11, 17),
// (11,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, object P2) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(11, 28)
);
var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings();
AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }" }, actualMembers);
}
[Fact]
public void Inheritance_23()
{
var source =
@"record A
{
public static object P1 { get; }
public object P2 { get; }
}
record B : A
{
public new object P1 { get; }
public new static object P2 { get; }
}
record C(object P1, object P2) : B
{
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (11,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, object P2) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(11, 17),
// (11,28): error CS8866: Record member 'B.P2' must be a readable instance property or field of type 'object' to match positional parameter 'P2'.
// record C(object P1, object P2) : B
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P2").WithArguments("B.P2", "object", "P2").WithLocation(11, 28),
// (11,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, object P2) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(11, 28));
var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings();
AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }" }, actualMembers);
}
[Fact]
public void Inheritance_24()
{
var source =
@"record A
{
public object get_P() => null;
public object set_Q() => null;
}
record B(object P, object Q) : A
{
}
record C(object P)
{
public object get_P() => null;
public object set_Q() => null;
}";
var comp = CreateCompilation(RuntimeUtilities.IsCoreClrRuntime ? source : new[] { source, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.StandardLatest);
comp.VerifyDiagnostics(
// (9,17): error CS0082: Type 'C' already reserves a member called 'get_P' with the same parameter types
// record C(object P)
Diagnostic(ErrorCode.ERR_MemberReserved, "P").WithArguments("get_P", "C").WithLocation(9, 17));
Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses);
var expectedClone = comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses
? "B B." + WellKnownMemberNames.CloneMethodName + "()"
: "A B." + WellKnownMemberNames.CloneMethodName + "()";
var expectedMembers = new[]
{
"B..ctor(System.Object P, System.Object Q)",
"System.Type B.EqualityContract.get",
"System.Type B.EqualityContract { get; }",
"System.Object B.<P>k__BackingField",
"System.Object B.P.get",
"void modreq(System.Runtime.CompilerServices.IsExternalInit) B.P.init",
"System.Object B.P { get; init; }",
"System.Object B.<Q>k__BackingField",
"System.Object B.Q.get",
"void modreq(System.Runtime.CompilerServices.IsExternalInit) B.Q.init",
"System.Object B.Q { get; init; }",
"System.String B.ToString()",
"System.Boolean B." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)",
"System.Boolean B.op_Inequality(B? left, B? right)",
"System.Boolean B.op_Equality(B? left, B? right)",
"System.Int32 B.GetHashCode()",
"System.Boolean B.Equals(System.Object? obj)",
"System.Boolean B.Equals(A? other)",
"System.Boolean B.Equals(B? other)",
expectedClone,
"B..ctor(B original)",
"void B.Deconstruct(out System.Object P, out System.Object Q)"
};
AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("B").GetMembers().ToTestDisplayStrings());
expectedMembers = new[]
{
"C..ctor(System.Object P)",
"System.Type C.EqualityContract.get",
"System.Type C.EqualityContract { get; }",
"System.Object C.<P>k__BackingField",
"System.Object C.P.get",
"void modreq(System.Runtime.CompilerServices.IsExternalInit) C.P.init",
"System.Object C.P { get; init; }",
"System.Object C.get_P()",
"System.Object C.set_Q()",
"System.String C.ToString()",
"System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)",
"System.Boolean C.op_Inequality(C? left, C? right)",
"System.Boolean C.op_Equality(C? left, C? right)",
"System.Int32 C.GetHashCode()",
"System.Boolean C.Equals(System.Object? obj)",
"System.Boolean C.Equals(C? other)",
"C C." + WellKnownMemberNames.CloneMethodName + "()",
"C..ctor(C original)",
"void C.Deconstruct(out System.Object P)"
};
AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings());
}
[Fact]
public void Inheritance_25()
{
var sourceA =
@"public record A
{
public class P1 { }
internal object P2 = 2;
public int P3(object o) => 3;
internal int P4<T>(T t) => 4;
}";
var sourceB =
@"record B(object P1, object P2, object P3, object P4) : A
{
}";
var comp = CreateCompilation(new[] { sourceA, sourceB, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (1,17): error CS8866: Record member 'A.P1' must be a readable instance property or field of type 'object' to match positional parameter 'P1'.
// record B(object P1, object P2, object P3, object P4) : A
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("A.P1", "object", "P1").WithLocation(1, 17),
// (1,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(1, 17),
// (1,21): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater.
// record B(object P1, object P2, object P3, object P4) : A
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object P2").WithArguments("positional fields in records", "10.0").WithLocation(1, 21),
// (1,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 28),
// (1,39): error CS8866: Record member 'A.P3' must be a readable instance property or field of type 'object' to match positional parameter 'P3'.
// record B(object P1, object P2, object P3, object P4) : A
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P3").WithArguments("A.P3", "object", "P3").WithLocation(1, 39),
// (1,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(1, 39));
var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type B.EqualityContract { get; }",
"System.Object B.P4 { get; init; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
comp = CreateCompilation(sourceA);
var refA = comp.EmitToImageReference();
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (1,17): error CS8866: Record member 'A.P1' must be a readable instance property or field of type 'object' to match positional parameter 'P1'.
// record B(object P1, object P2, object P3, object P4) : A
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("A.P1", "object", "P1").WithLocation(1, 17),
// (1,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(1, 17),
// (1,39): error CS8866: Record member 'A.P3' must be a readable instance property or field of type 'object' to match positional parameter 'P3'.
// record B(object P1, object P2, object P3, object P4) : A
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P3").WithArguments("A.P3", "object", "P3").WithLocation(1, 39),
// (1,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(1, 39));
actualMembers = GetProperties(comp, "B").ToTestDisplayStrings();
expectedMembers = new[]
{
"System.Type B.EqualityContract { get; }",
"System.Object B.P2 { get; init; }",
"System.Object B.P4 { get; init; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void Inheritance_26()
{
var sourceA =
@"public record A
{
internal const int P = 4;
}";
var sourceB =
@"record B(object P) : A
{
}";
var comp = CreateCompilation(new[] { sourceA, sourceB });
comp.VerifyDiagnostics(
// (1,17): error CS8866: Record member 'A.P' must be a readable instance property or field of type 'object' to match positional parameter 'P'.
// record B(object P) : A
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("A.P", "object", "P").WithLocation(1, 17),
// (1,17): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(1, 17));
AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, GetProperties(comp, "B").ToTestDisplayStrings());
comp = CreateCompilation(sourceA);
var refA = comp.EmitToImageReference();
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }", "System.Object B.P { get; init; }" }, GetProperties(comp, "B").ToTestDisplayStrings());
}
[Fact]
public void Inheritance_27()
{
var source =
@"record A
{
public object P { get; }
public object Q { get; set; }
}
record B(object get_P, object set_Q) : A
{
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type B.EqualityContract { get; }",
"System.Object B.get_P { get; init; }",
"System.Object B.set_Q { get; init; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void Inheritance_28()
{
var source =
@"interface I
{
object P { get; }
}
record A : I
{
object I.P => null;
}
record B(object P) : A
{
}
record C(object P) : I
{
object I.P => null;
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }", "System.Object B.P { get; init; }" }, GetProperties(comp, "B").ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }", "System.Object C.P { get; init; }", "System.Object C.I.P { get; }" }, GetProperties(comp, "C").ToTestDisplayStrings());
}
[Fact]
public void Inheritance_29()
{
var sourceA =
@"Public Class A
Public Property P(o As Object) As Object
Get
Return Nothing
End Get
Set
End Set
End Property
Public Property Q(x As Object, y As Object) As Object
Get
Return Nothing
End Get
Set
End Set
End Property
End Class
";
var compA = CreateVisualBasicCompilation(sourceA);
compA.VerifyDiagnostics();
var refA = compA.EmitToImageReference();
var sourceB =
@"record B(object P, object Q) : A
{
object P { get; }
}";
var compB = CreateCompilation(new[] { sourceB, IsExternalInitTypeDefinition }, references: new[] { refA }, parseOptions: TestOptions.Regular9);
compB.VerifyDiagnostics(
// (1,8): error CS0115: 'B.EqualityContract': no suitable method found to override
// record B(object P, object Q) : A
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.EqualityContract").WithLocation(1, 8),
// (1,8): error CS0115: 'B.Equals(A?)': no suitable method found to override
// record B(object P, object Q) : A
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.Equals(A?)").WithLocation(1, 8),
// (1,8): error CS0115: 'B.PrintMembers(StringBuilder)': no suitable method found to override
// record B(object P, object Q) : A
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)").WithLocation(1, 8),
// (1,8): error CS8867: No accessible copy constructor found in base type 'A'.
// record B(object P, object Q) : A
Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "B").WithArguments("A").WithLocation(1, 8),
// (1,17): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P, object Q) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(1, 17),
// (1,32): error CS8864: Records may only inherit from object or another record
// record B(object P, object Q) : A
Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(1, 32)
);
var actualMembers = GetProperties(compB, "B").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type B.EqualityContract { get; }",
"System.Object B.Q { get; init; }",
"System.Object B.P { get; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void Inheritance_30()
{
var sourceA =
@"Public Class A
Public ReadOnly Overloads Property P() As Object
Get
Return Nothing
End Get
End Property
Public ReadOnly Overloads Property P(o As Object) As Object
Get
Return Nothing
End Get
End Property
Public Overloads Property Q(o As Object) As Object
Get
Return Nothing
End Get
Set
End Set
End Property
Public Overloads Property Q() As Object
Get
Return Nothing
End Get
Set
End Set
End Property
End Class
";
var compA = CreateVisualBasicCompilation(sourceA);
compA.VerifyDiagnostics();
var refA = compA.EmitToImageReference();
var sourceB =
@"record B(object P, object Q) : A
{
}";
var compB = CreateCompilation(new[] { sourceB, IsExternalInitTypeDefinition }, references: new[] { refA }, parseOptions: TestOptions.Regular9);
compB.VerifyDiagnostics(
// (1,8): error CS0115: 'B.EqualityContract': no suitable method found to override
// record B(object P, object Q) : A
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.EqualityContract").WithLocation(1, 8),
// (1,8): error CS0115: 'B.Equals(A?)': no suitable method found to override
// record B(object P, object Q) : A
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.Equals(A?)").WithLocation(1, 8),
// (1,8): error CS0115: 'B.PrintMembers(StringBuilder)': no suitable method found to override
// record B(object P, object Q) : A
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)").WithLocation(1, 8),
// (1,8): error CS8867: No accessible copy constructor found in base type 'A'.
// record B(object P, object Q) : A
Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "B").WithArguments("A").WithLocation(1, 8),
// (1,17): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P, object Q) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(1, 17),
// (1,27): warning CS8907: Parameter 'Q' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P, object Q) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Q").WithArguments("Q").WithLocation(1, 27),
// (1,32): error CS8864: Records may only inherit from object or another record
// record B(object P, object Q) : A
Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(1, 32)
);
var actualMembers = GetProperties(compB, "B").ToTestDisplayStrings();
AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers);
}
[Fact]
public void Inheritance_31()
{
var sourceA =
@"Public Class A
Public ReadOnly Property P() As Object
Get
Return Nothing
End Get
End Property
Public Property Q(o As Object) As Object
Get
Return Nothing
End Get
Set
End Set
End Property
Public Property R(o As Object) As Object
Get
Return Nothing
End Get
Set
End Set
End Property
Public Sub New(a as A)
End Sub
End Class
Public Class B
Inherits A
Public ReadOnly Overloads Property P(o As Object) As Object
Get
Return Nothing
End Get
End Property
Public Overloads Property Q() As Object
Get
Return Nothing
End Get
Set
End Set
End Property
Public Overloads Property R(x As Object, y As Object) As Object
Get
Return Nothing
End Get
Set
End Set
End Property
Public Sub New(b as B)
MyBase.New(b)
End Sub
End Class
";
var compA = CreateVisualBasicCompilation(sourceA);
compA.VerifyDiagnostics();
var refA = compA.EmitToImageReference();
var sourceB =
@"record C(object P, object Q, object R) : B
{
}";
var compB = CreateCompilation(new[] { sourceB, IsExternalInitTypeDefinition }, references: new[] { refA }, parseOptions: TestOptions.Regular9);
compB.VerifyDiagnostics(
// (1,8): error CS0115: 'C.EqualityContract': no suitable method found to override
// record C(object P, object Q, object R) : B
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.EqualityContract").WithLocation(1, 8),
// (1,8): error CS0115: 'C.Equals(B?)': no suitable method found to override
// record C(object P, object Q, object R) : B
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.Equals(B?)").WithLocation(1, 8),
// (1,8): error CS0115: 'C.PrintMembers(StringBuilder)': no suitable method found to override
// record C(object P, object Q, object R) : B
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.PrintMembers(System.Text.StringBuilder)").WithLocation(1, 8),
// (1,8): error CS7036: There is no argument given that corresponds to the required formal parameter 'b' of 'B.B(B)'
// record C(object P, object Q, object R) : B
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("b", "B.B(B)").WithLocation(1, 8),
// (1,17): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P, object Q, object R) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(1, 17),
// (1,27): warning CS8907: Parameter 'Q' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P, object Q, object R) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Q").WithArguments("Q").WithLocation(1, 27),
// (1,42): error CS8864: Records may only inherit from object or another record
// record C(object P, object Q, object R) : B
Diagnostic(ErrorCode.ERR_BadRecordBase, "B").WithLocation(1, 42)
);
var actualMembers = GetProperties(compB, "C").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type C.EqualityContract { get; }",
"System.Object C.R { get; init; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void Inheritance_32()
{
var source =
@"record A
{
public virtual object P1 { get; }
public virtual object P2 { get; set; }
public virtual object P3 { get; protected init; }
public virtual object P4 { protected get; init; }
public virtual object P5 { init { } }
public virtual object P6 { set { } }
public static object P7 { get; set; }
}
record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A;
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (11,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A;
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(11, 17),
// (11,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A;
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(11, 28),
// (11,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A;
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(11, 39),
// (11,50): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A;
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(11, 50),
// (11,61): error CS8866: Record member 'A.P5' must be a readable instance property or field of type 'object' to match positional parameter 'P5'.
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A;
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P5").WithArguments("A.P5", "object", "P5").WithLocation(11, 61),
// (11,61): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A;
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(11, 61),
// (11,72): error CS8866: Record member 'A.P6' must be a readable instance property or field of type 'object' to match positional parameter 'P6'.
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A;
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P6").WithArguments("A.P6", "object", "P6").WithLocation(11, 72),
// (11,72): warning CS8907: Parameter 'P6' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A;
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P6").WithArguments("P6").WithLocation(11, 72),
// (11,83): error CS8866: Record member 'A.P7' must be a readable instance property or field of type 'object' to match positional parameter 'P7'.
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A;
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P7").WithArguments("A.P7", "object", "P7").WithLocation(11, 83),
// (11,83): warning CS8907: Parameter 'P7' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A;
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P7").WithArguments("P7").WithLocation(11, 83));
AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, GetProperties(comp, "B").ToTestDisplayStrings());
}
[WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")]
[Fact]
public void Inheritance_33()
{
var source =
@"abstract record A
{
public abstract object P1 { get; }
public abstract object P2 { get; set; }
public abstract object P3 { get; protected init; }
public abstract object P4 { protected get; init; }
public abstract object P5 { init; }
public abstract object P6 { set; }
}
record B(object P1, object P2, object P3, object P4, object P5, object P6) : A;
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (10,8): error CS0534: 'B' does not implement inherited abstract member 'A.P6.set'
// record B(object P1, object P2, object P3, object P4, object P5, object P6) : A;
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.P6.set").WithLocation(10, 8),
// (10,8): error CS0534: 'B' does not implement inherited abstract member 'A.P5.init'
// record B(object P1, object P2, object P3, object P4, object P5, object P6) : A;
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.P5.init").WithLocation(10, 8),
// (10,17): error CS0546: 'B.P1.init': cannot override because 'A.P1' does not have an overridable set accessor
// record B(object P1, object P2, object P3, object P4, object P5, object P6) : A;
Diagnostic(ErrorCode.ERR_NoSetToOverride, "P1").WithArguments("B.P1.init", "A.P1").WithLocation(10, 17),
// (10,28): error CS8853: 'B.P2' must match by init-only of overridden member 'A.P2'
// record B(object P1, object P2, object P3, object P4, object P5, object P6) : A;
Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "P2").WithArguments("B.P2", "A.P2").WithLocation(10, 28),
// (10,39): error CS0507: 'B.P3.init': cannot change access modifiers when overriding 'protected' inherited member 'A.P3.init'
// record B(object P1, object P2, object P3, object P4, object P5, object P6) : A;
Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "P3").WithArguments("B.P3.init", "protected", "A.P3.init").WithLocation(10, 39),
// (10,50): error CS0507: 'B.P4.get': cannot change access modifiers when overriding 'protected' inherited member 'A.P4.get'
// record B(object P1, object P2, object P3, object P4, object P5, object P6) : A;
Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "P4").WithArguments("B.P4.get", "protected", "A.P4.get").WithLocation(10, 50),
// (10,61): error CS8866: Record member 'A.P5' must be a readable instance property or field of type 'object' to match positional parameter 'P5'.
// record B(object P1, object P2, object P3, object P4, object P5, object P6) : A;
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P5").WithArguments("A.P5", "object", "P5").WithLocation(10, 61),
// (10,61): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6) : A;
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(10, 61),
// (10,72): error CS8866: Record member 'A.P6' must be a readable instance property or field of type 'object' to match positional parameter 'P6'.
// record B(object P1, object P2, object P3, object P4, object P5, object P6) : A;
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P6").WithArguments("A.P6", "object", "P6").WithLocation(10, 72),
// (10,72): warning CS8907: Parameter 'P6' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6) : A;
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P6").WithArguments("P6").WithLocation(10, 72));
var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type B.EqualityContract { get; }",
"System.Object B.P1 { get; init; }",
"System.Object B.P2 { get; init; }",
"System.Object B.P3 { get; init; }",
"System.Object B.P4 { get; init; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")]
[Fact]
public void Inheritance_34()
{
var source =
@"abstract record A
{
public abstract object P1 { get; init; }
public virtual object P2 { get; init; }
}
record B(string P1, string P2) : A;
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,8): error CS0534: 'B' does not implement inherited abstract member 'A.P1.init'
// record B(string P1, string P2) : A;
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.P1.init").WithLocation(6, 8),
// (6,8): error CS0534: 'B' does not implement inherited abstract member 'A.P1.get'
// record B(string P1, string P2) : A;
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.P1.get").WithLocation(6, 8),
// (6,17): error CS8866: Record member 'A.P1' must be a readable instance property or field of type 'string' to match positional parameter 'P1'.
// record B(string P1, string P2) : A;
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("A.P1", "string", "P1").WithLocation(6, 17),
// (6,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record B(string P1, string P2) : A;
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(6, 17),
// (6,28): error CS8866: Record member 'A.P2' must be a readable instance property or field of type 'string' to match positional parameter 'P2'.
// record B(string P1, string P2) : A;
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P2").WithArguments("A.P2", "string", "P2").WithLocation(6, 28),
// (6,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record B(string P1, string P2) : A;
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(6, 28));
AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, GetProperties(comp, "B").ToTestDisplayStrings());
}
[WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")]
[Fact]
public void Inheritance_35()
{
var source =
@"using static System.Console;
abstract record A(object X, object Y)
{
public abstract object X { get; }
public abstract object Y { get; init; }
}
record B(object X, object Y) : A(X, Y)
{
public override object X { get; } = X;
}
class Program
{
static void Main()
{
B b = new B(1, 2);
A a = b;
WriteLine((b.X, b.Y));
WriteLine((a.X, a.Y));
var (x, y) = b;
WriteLine((x, y));
(x, y) = a;
WriteLine((x, y));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type B.EqualityContract { get; }",
"System.Object B.Y { get; init; }",
"System.Object B.X { get; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
var verifier = CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput:
@"(1, 2)
(1, 2)
(1, 2)
(1, 2)").VerifyDiagnostics(
// (2,26): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// abstract record A(object X, object Y)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 26),
// (2,36): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// abstract record A(object X, object Y)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(2, 36)
);
verifier.VerifyIL("A..ctor(object, object)",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ret
}");
verifier.VerifyIL("A..ctor(A)",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ret
}");
verifier.VerifyIL("A.Deconstruct",
@"{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: callvirt ""object A.X.get""
IL_0007: stind.ref
IL_0008: ldarg.2
IL_0009: ldarg.0
IL_000a: callvirt ""object A.Y.get""
IL_000f: stind.ref
IL_0010: ret
}");
verifier.VerifyIL("A.Equals(A)",
@"{
// Code size 29 (0x1d)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_001b
IL_0004: ldarg.1
IL_0005: brfalse.s IL_0019
IL_0007: ldarg.0
IL_0008: callvirt ""System.Type A.EqualityContract.get""
IL_000d: ldarg.1
IL_000e: callvirt ""System.Type A.EqualityContract.get""
IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)""
IL_0018: ret
IL_0019: ldc.i4.0
IL_001a: ret
IL_001b: ldc.i4.1
IL_001c: ret
}");
verifier.VerifyIL("A.GetHashCode()",
@"{
// Code size 17 (0x11)
.maxstack 2
IL_0000: call ""System.Collections.Generic.EqualityComparer<System.Type> System.Collections.Generic.EqualityComparer<System.Type>.Default.get""
IL_0005: ldarg.0
IL_0006: callvirt ""System.Type A.EqualityContract.get""
IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<System.Type>.GetHashCode(System.Type)""
IL_0010: ret
}");
verifier.VerifyIL("B..ctor(object, object)",
@"{
// Code size 23 (0x17)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.2
IL_0002: stfld ""object B.<Y>k__BackingField""
IL_0007: ldarg.0
IL_0008: ldarg.1
IL_0009: stfld ""object B.<X>k__BackingField""
IL_000e: ldarg.0
IL_000f: ldarg.1
IL_0010: ldarg.2
IL_0011: call ""A..ctor(object, object)""
IL_0016: ret
}");
verifier.VerifyIL("B..ctor(B)",
@"{
// Code size 32 (0x20)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""A..ctor(A)""
IL_0007: ldarg.0
IL_0008: ldarg.1
IL_0009: ldfld ""object B.<Y>k__BackingField""
IL_000e: stfld ""object B.<Y>k__BackingField""
IL_0013: ldarg.0
IL_0014: ldarg.1
IL_0015: ldfld ""object B.<X>k__BackingField""
IL_001a: stfld ""object B.<X>k__BackingField""
IL_001f: ret
}");
verifier.VerifyIL("B.Deconstruct",
@"{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: callvirt ""object A.X.get""
IL_0007: stind.ref
IL_0008: ldarg.2
IL_0009: ldarg.0
IL_000a: callvirt ""object A.Y.get""
IL_000f: stind.ref
IL_0010: ret
}");
verifier.VerifyIL("B.Equals(B)",
@"{
// Code size 64 (0x40)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_003e
IL_0004: ldarg.0
IL_0005: ldarg.1
IL_0006: call ""bool A.Equals(A)""
IL_000b: brfalse.s IL_003c
IL_000d: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get""
IL_0012: ldarg.0
IL_0013: ldfld ""object B.<Y>k__BackingField""
IL_0018: ldarg.1
IL_0019: ldfld ""object B.<Y>k__BackingField""
IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)""
IL_0023: brfalse.s IL_003c
IL_0025: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get""
IL_002a: ldarg.0
IL_002b: ldfld ""object B.<X>k__BackingField""
IL_0030: ldarg.1
IL_0031: ldfld ""object B.<X>k__BackingField""
IL_0036: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)""
IL_003b: ret
IL_003c: ldc.i4.0
IL_003d: ret
IL_003e: ldc.i4.1
IL_003f: ret
}");
verifier.VerifyIL("B.GetHashCode()",
@"{
// Code size 53 (0x35)
.maxstack 3
IL_0000: ldarg.0
IL_0001: call ""int A.GetHashCode()""
IL_0006: ldc.i4 0xa5555529
IL_000b: mul
IL_000c: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get""
IL_0011: ldarg.0
IL_0012: ldfld ""object B.<Y>k__BackingField""
IL_0017: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)""
IL_001c: add
IL_001d: ldc.i4 0xa5555529
IL_0022: mul
IL_0023: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get""
IL_0028: ldarg.0
IL_0029: ldfld ""object B.<X>k__BackingField""
IL_002e: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)""
IL_0033: add
IL_0034: ret
}");
}
[WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")]
[Fact]
public void Inheritance_36()
{
var source =
@"using static System.Console;
abstract record A
{
public abstract object X { get; init; }
}
abstract record B : A
{
public abstract object Y { get; init; }
}
record C(object X, object Y) : B;
class Program
{
static void Main()
{
C c = new C(1, 2);
B b = c;
A a = c;
WriteLine((c.X, c.Y));
WriteLine((b.X, b.Y));
WriteLine(a.X);
var (x, y) = c;
WriteLine((x, y));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type C.EqualityContract { get; }",
"System.Object C.X { get; init; }",
"System.Object C.Y { get; init; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
var verifier = CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput:
@"(1, 2)
(1, 2)
1
(1, 2)").VerifyDiagnostics();
verifier.VerifyIL("A..ctor()",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ret
}");
verifier.VerifyIL("A..ctor(A)",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ret
}");
verifier.VerifyIL("A.Equals(A)",
@"{
// Code size 29 (0x1d)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_001b
IL_0004: ldarg.1
IL_0005: brfalse.s IL_0019
IL_0007: ldarg.0
IL_0008: callvirt ""System.Type A.EqualityContract.get""
IL_000d: ldarg.1
IL_000e: callvirt ""System.Type A.EqualityContract.get""
IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)""
IL_0018: ret
IL_0019: ldc.i4.0
IL_001a: ret
IL_001b: ldc.i4.1
IL_001c: ret
}");
verifier.VerifyIL("A.GetHashCode()",
@"{
// Code size 17 (0x11)
.maxstack 2
IL_0000: call ""System.Collections.Generic.EqualityComparer<System.Type> System.Collections.Generic.EqualityComparer<System.Type>.Default.get""
IL_0005: ldarg.0
IL_0006: callvirt ""System.Type A.EqualityContract.get""
IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<System.Type>.GetHashCode(System.Type)""
IL_0010: ret
}");
verifier.VerifyIL("B..ctor()",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""A..ctor()""
IL_0006: ret
}");
verifier.VerifyIL("B..ctor(B)",
@"{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""A..ctor(A)""
IL_0007: ret
}");
verifier.VerifyIL("B.Equals(B)",
@"{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_000c
IL_0004: ldarg.0
IL_0005: ldarg.1
IL_0006: call ""bool A.Equals(A)""
IL_000b: ret
IL_000c: ldc.i4.1
IL_000d: ret
}");
verifier.VerifyIL("B.GetHashCode()",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""int A.GetHashCode()""
IL_0006: ret
}");
verifier.VerifyIL("C..ctor(object, object)",
@"{
// Code size 21 (0x15)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld ""object C.<X>k__BackingField""
IL_0007: ldarg.0
IL_0008: ldarg.2
IL_0009: stfld ""object C.<Y>k__BackingField""
IL_000e: ldarg.0
IL_000f: call ""B..ctor()""
IL_0014: ret
}");
verifier.VerifyIL("C..ctor(C)",
@"{
// Code size 32 (0x20)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""B..ctor(B)""
IL_0007: ldarg.0
IL_0008: ldarg.1
IL_0009: ldfld ""object C.<X>k__BackingField""
IL_000e: stfld ""object C.<X>k__BackingField""
IL_0013: ldarg.0
IL_0014: ldarg.1
IL_0015: ldfld ""object C.<Y>k__BackingField""
IL_001a: stfld ""object C.<Y>k__BackingField""
IL_001f: ret
}");
verifier.VerifyIL("C.Deconstruct",
@"{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: callvirt ""object A.X.get""
IL_0007: stind.ref
IL_0008: ldarg.2
IL_0009: ldarg.0
IL_000a: callvirt ""object B.Y.get""
IL_000f: stind.ref
IL_0010: ret
}");
verifier.VerifyIL("C.Equals(C)",
@"{
// Code size 64 (0x40)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_003e
IL_0004: ldarg.0
IL_0005: ldarg.1
IL_0006: call ""bool B.Equals(B)""
IL_000b: brfalse.s IL_003c
IL_000d: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get""
IL_0012: ldarg.0
IL_0013: ldfld ""object C.<X>k__BackingField""
IL_0018: ldarg.1
IL_0019: ldfld ""object C.<X>k__BackingField""
IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)""
IL_0023: brfalse.s IL_003c
IL_0025: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get""
IL_002a: ldarg.0
IL_002b: ldfld ""object C.<Y>k__BackingField""
IL_0030: ldarg.1
IL_0031: ldfld ""object C.<Y>k__BackingField""
IL_0036: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)""
IL_003b: ret
IL_003c: ldc.i4.0
IL_003d: ret
IL_003e: ldc.i4.1
IL_003f: ret
}");
verifier.VerifyIL("C.GetHashCode()",
@"{
// Code size 53 (0x35)
.maxstack 3
IL_0000: ldarg.0
IL_0001: call ""int B.GetHashCode()""
IL_0006: ldc.i4 0xa5555529
IL_000b: mul
IL_000c: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get""
IL_0011: ldarg.0
IL_0012: ldfld ""object C.<X>k__BackingField""
IL_0017: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)""
IL_001c: add
IL_001d: ldc.i4 0xa5555529
IL_0022: mul
IL_0023: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get""
IL_0028: ldarg.0
IL_0029: ldfld ""object C.<Y>k__BackingField""
IL_002e: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)""
IL_0033: add
IL_0034: ret
}");
}
[WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")]
[Fact]
public void Inheritance_37()
{
var source =
@"using static System.Console;
abstract record A(object X, object Y)
{
public abstract object X { get; init; }
public virtual object Y { get; init; }
}
abstract record B(object X, object Y) : A(X, Y)
{
public override abstract object X { get; init; }
public override abstract object Y { get; init; }
}
record C(object X, object Y) : B(X, Y);
class Program
{
static void Main()
{
C c = new C(1, 2);
B b = c;
A a = c;
WriteLine((c.X, c.Y));
WriteLine((b.X, b.Y));
WriteLine((a.X, a.Y));
var (x, y) = c;
WriteLine((x, y));
(x, y) = b;
WriteLine((x, y));
(x, y) = a;
WriteLine((x, y));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type C.EqualityContract { get; }",
"System.Object C.X { get; init; }",
"System.Object C.Y { get; init; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
var verifier = CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput:
@"(1, 2)
(1, 2)
(1, 2)
(1, 2)
(1, 2)
(1, 2)").VerifyDiagnostics(
// (2,26): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// abstract record A(object X, object Y)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 26),
// (2,36): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// abstract record A(object X, object Y)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(2, 36)
);
verifier.VerifyIL("A..ctor(object, object)",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ret
}");
verifier.VerifyIL("A..ctor(A)",
@"{
// Code size 19 (0x13)
.maxstack 2
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ldarg.0
IL_0007: ldarg.1
IL_0008: ldfld ""object A.<Y>k__BackingField""
IL_000d: stfld ""object A.<Y>k__BackingField""
IL_0012: ret
}");
verifier.VerifyIL("A.Deconstruct",
@"{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: callvirt ""object A.X.get""
IL_0007: stind.ref
IL_0008: ldarg.2
IL_0009: ldarg.0
IL_000a: callvirt ""object A.Y.get""
IL_000f: stind.ref
IL_0010: ret
}");
verifier.VerifyIL("A.Equals(A)",
@"{
// Code size 53 (0x35)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_0033
IL_0004: ldarg.1
IL_0005: brfalse.s IL_0031
IL_0007: ldarg.0
IL_0008: callvirt ""System.Type A.EqualityContract.get""
IL_000d: ldarg.1
IL_000e: callvirt ""System.Type A.EqualityContract.get""
IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)""
IL_0018: brfalse.s IL_0031
IL_001a: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get""
IL_001f: ldarg.0
IL_0020: ldfld ""object A.<Y>k__BackingField""
IL_0025: ldarg.1
IL_0026: ldfld ""object A.<Y>k__BackingField""
IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)""
IL_0030: ret
IL_0031: ldc.i4.0
IL_0032: ret
IL_0033: ldc.i4.1
IL_0034: ret
}");
verifier.VerifyIL("A.GetHashCode()",
@"{
// Code size 40 (0x28)
.maxstack 3
IL_0000: call ""System.Collections.Generic.EqualityComparer<System.Type> System.Collections.Generic.EqualityComparer<System.Type>.Default.get""
IL_0005: ldarg.0
IL_0006: callvirt ""System.Type A.EqualityContract.get""
IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<System.Type>.GetHashCode(System.Type)""
IL_0010: ldc.i4 0xa5555529
IL_0015: mul
IL_0016: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get""
IL_001b: ldarg.0
IL_001c: ldfld ""object A.<Y>k__BackingField""
IL_0021: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)""
IL_0026: add
IL_0027: ret
}");
verifier.VerifyIL("B..ctor(object, object)",
@"{
// Code size 9 (0x9)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: ldarg.2
IL_0003: call ""A..ctor(object, object)""
IL_0008: ret
}");
verifier.VerifyIL("B..ctor(B)",
@"{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""A..ctor(A)""
IL_0007: ret
}");
verifier.VerifyIL("B.Deconstruct",
@"{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: callvirt ""object A.X.get""
IL_0007: stind.ref
IL_0008: ldarg.2
IL_0009: ldarg.0
IL_000a: callvirt ""object A.Y.get""
IL_000f: stind.ref
IL_0010: ret
}");
verifier.VerifyIL("B.Equals(B)",
@"{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_000c
IL_0004: ldarg.0
IL_0005: ldarg.1
IL_0006: call ""bool A.Equals(A)""
IL_000b: ret
IL_000c: ldc.i4.1
IL_000d: ret
}");
verifier.VerifyIL("B.GetHashCode()",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""int A.GetHashCode()""
IL_0006: ret
}");
verifier.VerifyIL("C..ctor(object, object)",
@"{
// Code size 23 (0x17)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld ""object C.<X>k__BackingField""
IL_0007: ldarg.0
IL_0008: ldarg.2
IL_0009: stfld ""object C.<Y>k__BackingField""
IL_000e: ldarg.0
IL_000f: ldarg.1
IL_0010: ldarg.2
IL_0011: call ""B..ctor(object, object)""
IL_0016: ret
}");
verifier.VerifyIL("C..ctor(C)",
@"{
// Code size 32 (0x20)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""B..ctor(B)""
IL_0007: ldarg.0
IL_0008: ldarg.1
IL_0009: ldfld ""object C.<X>k__BackingField""
IL_000e: stfld ""object C.<X>k__BackingField""
IL_0013: ldarg.0
IL_0014: ldarg.1
IL_0015: ldfld ""object C.<Y>k__BackingField""
IL_001a: stfld ""object C.<Y>k__BackingField""
IL_001f: ret
}");
verifier.VerifyIL("C.Deconstruct",
@"{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: callvirt ""object A.X.get""
IL_0007: stind.ref
IL_0008: ldarg.2
IL_0009: ldarg.0
IL_000a: callvirt ""object A.Y.get""
IL_000f: stind.ref
IL_0010: ret
}");
verifier.VerifyIL("C.Equals(C)",
@"{
// Code size 64 (0x40)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_003e
IL_0004: ldarg.0
IL_0005: ldarg.1
IL_0006: call ""bool B.Equals(B)""
IL_000b: brfalse.s IL_003c
IL_000d: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get""
IL_0012: ldarg.0
IL_0013: ldfld ""object C.<X>k__BackingField""
IL_0018: ldarg.1
IL_0019: ldfld ""object C.<X>k__BackingField""
IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)""
IL_0023: brfalse.s IL_003c
IL_0025: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get""
IL_002a: ldarg.0
IL_002b: ldfld ""object C.<Y>k__BackingField""
IL_0030: ldarg.1
IL_0031: ldfld ""object C.<Y>k__BackingField""
IL_0036: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)""
IL_003b: ret
IL_003c: ldc.i4.0
IL_003d: ret
IL_003e: ldc.i4.1
IL_003f: ret
}");
verifier.VerifyIL("C.GetHashCode()",
@"{
// Code size 53 (0x35)
.maxstack 3
IL_0000: ldarg.0
IL_0001: call ""int B.GetHashCode()""
IL_0006: ldc.i4 0xa5555529
IL_000b: mul
IL_000c: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get""
IL_0011: ldarg.0
IL_0012: ldfld ""object C.<X>k__BackingField""
IL_0017: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)""
IL_001c: add
IL_001d: ldc.i4 0xa5555529
IL_0022: mul
IL_0023: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get""
IL_0028: ldarg.0
IL_0029: ldfld ""object C.<Y>k__BackingField""
IL_002e: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)""
IL_0033: add
IL_0034: ret
}");
}
// Member in intermediate base that hides abstract property. Not supported.
[WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")]
[Fact]
public void Inheritance_38()
{
var source =
@"using static System.Console;
abstract record A
{
public abstract object X { get; init; }
public abstract object Y { get; init; }
}
abstract record B : A
{
public new void X() { }
public new struct Y { }
}
record C(object X, object Y) : B;
class Program
{
static void Main()
{
C c = new C(1, 2);
A a = c;
WriteLine((a.X, a.Y));
var (x, y) = c;
WriteLine((x, y));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics(
// (9,21): error CS0533: 'B.X()' hides inherited abstract member 'A.X'
// public new void X() { }
Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "X").WithArguments("B.X()", "A.X").WithLocation(9, 21),
// (10,23): error CS0533: 'B.Y' hides inherited abstract member 'A.Y'
// public new struct Y { }
Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "Y").WithArguments("B.Y", "A.Y").WithLocation(10, 23),
// (12,8): error CS0534: 'C' does not implement inherited abstract member 'A.Y.get'
// record C(object X, object Y) : B;
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "C").WithArguments("C", "A.Y.get").WithLocation(12, 8),
// (12,8): error CS0534: 'C' does not implement inherited abstract member 'A.X.get'
// record C(object X, object Y) : B;
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "C").WithArguments("C", "A.X.get").WithLocation(12, 8),
// (12,8): error CS0534: 'C' does not implement inherited abstract member 'A.X.init'
// record C(object X, object Y) : B;
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "C").WithArguments("C", "A.X.init").WithLocation(12, 8),
// (12,8): error CS0534: 'C' does not implement inherited abstract member 'A.Y.init'
// record C(object X, object Y) : B;
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "C").WithArguments("C", "A.Y.init").WithLocation(12, 8),
// (12,17): error CS8866: Record member 'B.X' must be a readable instance property or field of type 'object' to match positional parameter 'X'.
// record C(object X, object Y) : B;
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("B.X", "object", "X").WithLocation(12, 17),
// (12,17): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record C(object X, object Y) : B;
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(12, 17),
// (12,27): error CS8866: Record member 'B.Y' must be a readable instance property or field of type 'object' to match positional parameter 'Y'.
// record C(object X, object Y) : B;
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Y").WithArguments("B.Y", "object", "Y").WithLocation(12, 27),
// (12,27): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// record C(object X, object Y) : B;
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(12, 27));
AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }", }, GetProperties(comp, "C").ToTestDisplayStrings());
}
// Member in intermediate base that hides abstract property. Not supported.
[WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")]
[Fact]
public void Inheritance_39()
{
var sourceA =
@".class public System.Runtime.CompilerServices.IsExternalInit
{
.method public hidebysig specialname rtspecialname instance void .ctor() { ldnull throw }
}
.class public abstract A
{
.method family hidebysig specialname rtspecialname instance void .ctor()
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.method family hidebysig specialname rtspecialname instance void .ctor(class A A_1) { ldnull throw }
.method public hidebysig newslot specialname abstract virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { }
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.property instance object P()
{
.get instance object A::get_P()
.set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) A::set_P(object)
}
.method family virtual instance class [mscorlib]System.Type get_EqualityContract() { ldnull ret }
.method public abstract virtual instance object get_P() { }
.method public abstract virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(object 'value') { }
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}
.class public abstract B extends A
{
.method family hidebysig specialname rtspecialname instance void .ctor()
{
ldarg.0
call instance void A::.ctor()
ret
}
.method family hidebysig specialname rtspecialname instance void .ctor(class B A_1) { ldnull throw }
.method public hidebysig specialname abstract virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { }
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type B::get_EqualityContract()
}
.method family virtual instance class [mscorlib]System.Type get_EqualityContract() { ldnull ret }
.method public hidebysig instance object P() { ldnull ret }
.method public newslot virtual
instance bool Equals (
class B ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method B::Equals
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}";
var refA = CompileIL(sourceA);
var sourceB =
@"record CA(object P) : A;
record CB(object P) : B;
";
var comp = CreateCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (2,8): error CS0534: 'CB' does not implement inherited abstract member 'A.P.get'
// record CB(object P) : B;
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "CB").WithArguments("CB", "A.P.get").WithLocation(2, 8),
// (2,8): error CS0534: 'CB' does not implement inherited abstract member 'A.P.init'
// record CB(object P) : B;
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "CB").WithArguments("CB", "A.P.init").WithLocation(2, 8),
// (2,18): error CS8866: Record member 'B.P' must be a readable instance property or field of type 'object' to match positional parameter 'P'.
// record CB(object P) : B;
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("B.P", "object", "P").WithLocation(2, 18),
// (2,18): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name?
// record CB(object P) : B;
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 18));
AssertEx.Equal(new[] { "System.Type CA.EqualityContract { get; }", "System.Object CA.P { get; init; }" }, GetProperties(comp, "CA").ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.Type CB.EqualityContract { get; }" }, GetProperties(comp, "CB").ToTestDisplayStrings());
}
// Accessor names that do not match the property name.
[WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")]
[Fact]
public void Inheritance_40()
{
var sourceA =
@".class public System.Runtime.CompilerServices.IsExternalInit
{
.method public hidebysig specialname rtspecialname instance void .ctor() { ldnull throw }
}
.class public abstract A
{
.method family hidebysig specialname rtspecialname instance void .ctor()
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.method family hidebysig specialname rtspecialname instance void .ctor(class A A_1) { ldnull throw }
.method public hidebysig newslot specialname abstract virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { }
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::GetProperty1()
}
.property instance object P()
{
.get instance object A::GetProperty2()
.set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) A::SetProperty2(object)
}
.method family virtual instance class [mscorlib]System.Type GetProperty1() { ldnull ret }
.method public abstract virtual instance object GetProperty2() { }
.method public abstract virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) SetProperty2(object 'value') { }
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}";
var refA = CompileIL(sourceA);
var sourceB =
@"using static System.Console;
record B(object P) : A
{
static void Main()
{
B b = new B(3);
WriteLine(b.P);
WriteLine(((A)b).P);
b = new B(1) { P = 2 };
WriteLine(b.P);
WriteLine(b.EqualityContract.Name);
}
}";
var comp = CreateCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput:
@"3
3
2
B").VerifyDiagnostics();
var actualMembers = GetProperties(comp, "B");
Assert.Equal(2, actualMembers.Length);
VerifyProperty(actualMembers[0], "System.Type B.EqualityContract { get; }", "GetProperty1", null);
VerifyProperty(actualMembers[1], "System.Object B.P { get; init; }", "GetProperty2", "SetProperty2");
}
// Accessor names that do not match the property name and are not valid C# names.
[WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")]
[Fact]
public void Inheritance_41()
{
var sourceA =
@".class public System.Runtime.CompilerServices.IsExternalInit
{
.method public hidebysig specialname rtspecialname instance void .ctor() { ldnull throw }
}
.class public abstract A
{
.method family hidebysig specialname rtspecialname instance void .ctor()
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.method family hidebysig specialname rtspecialname instance void .ctor(class A A_1) { ldnull throw }
.method public hidebysig newslot specialname abstract virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { }
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::'EqualityContract<>get'()
}
.property instance object P()
{
.get instance object A::'P<>get'()
.set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) A::'P<>set'(object)
}
.method family virtual instance class [mscorlib]System.Type 'EqualityContract<>get'() { ldnull ret }
.method public abstract virtual instance object 'P<>get'() { }
.method public abstract virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) 'P<>set'(object 'value') { }
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}";
var refA = CompileIL(sourceA);
var sourceB =
@"using static System.Console;
record B(object P) : A
{
static void Main()
{
B b = new B(3);
WriteLine(b.P);
WriteLine(((A)b).P);
b = new B(1) { P = 2 };
WriteLine(b.P);
WriteLine(b.EqualityContract.Name);
}
}";
var comp = CreateCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput:
@"3
3
2
B").VerifyDiagnostics();
var actualMembers = GetProperties(comp, "B");
Assert.Equal(2, actualMembers.Length);
VerifyProperty(actualMembers[0], "System.Type B.EqualityContract { get; }", "EqualityContract<>get", null);
VerifyProperty(actualMembers[1], "System.Object B.P { get; init; }", "P<>get", "P<>set");
}
private static void VerifyProperty(Symbol symbol, string propertyDescription, string? getterName, string? setterName)
{
var property = (PropertySymbol)symbol;
Assert.Equal(propertyDescription, symbol.ToTestDisplayString());
VerifyAccessor(property.GetMethod, getterName);
VerifyAccessor(property.SetMethod, setterName);
}
private static void VerifyAccessor(MethodSymbol? accessor, string? name)
{
Assert.Equal(name, accessor?.Name);
if (accessor is object)
{
Assert.True(accessor.HasSpecialName);
foreach (var parameter in accessor.Parameters)
{
Assert.Same(accessor, parameter.ContainingSymbol);
}
}
}
[WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")]
[Fact]
public void Inheritance_42()
{
var sourceA =
@".class public System.Runtime.CompilerServices.IsExternalInit
{
.method public hidebysig specialname rtspecialname instance void .ctor() { ldnull throw }
}
.class public abstract A
{
.method family hidebysig specialname rtspecialname instance void .ctor()
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.method family hidebysig specialname rtspecialname instance void .ctor(class A A_1) { ldnull throw }
.method public hidebysig newslot specialname abstract virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { }
.property instance class [mscorlib]System.Type modopt(int32) EqualityContract()
{
.get instance class [mscorlib]System.Type modopt(int32) A::get_EqualityContract()
}
.property instance object modopt(uint16) P()
{
.get instance object modopt(uint16) A::get_P()
.set instance void modopt(uint8) modreq(System.Runtime.CompilerServices.IsExternalInit) A::set_P(object modopt(uint16))
}
.method family virtual instance class [mscorlib]System.Type modopt(int32) get_EqualityContract() { ldnull ret }
.method public abstract virtual instance object modopt(uint16) get_P() { }
.method public abstract virtual instance void modopt(uint8) modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(object modopt(uint16) 'value') { }
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance string ToString () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}";
var refA = CompileIL(sourceA);
var sourceB =
@"using static System.Console;
record B(object P) : A
{
static void Main()
{
B b = new B(3);
WriteLine(b.P);
WriteLine(((A)b).P);
b = new B(1) { P = 2 };
WriteLine(b.P);
WriteLine(b.EqualityContract.Name);
}
}";
var comp = CreateCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput:
@"3
3
2
B").VerifyDiagnostics();
var actualMembers = GetProperties(comp, "B");
Assert.Equal(2, actualMembers.Length);
var property = (PropertySymbol)actualMembers[0];
Assert.Equal("System.Type modopt(System.Int32) B.EqualityContract { get; }", property.ToTestDisplayString());
verifyReturnType(property.GetMethod, CSharpCustomModifier.CreateOptional(comp.GetSpecialType(SpecialType.System_Int32)));
property = (PropertySymbol)actualMembers[1];
Assert.Equal("System.Object modopt(System.UInt16) B.P { get; init; }", property.ToTestDisplayString());
verifyReturnType(property.GetMethod,
CSharpCustomModifier.CreateOptional(comp.GetSpecialType(SpecialType.System_UInt16)));
verifyReturnType(property.SetMethod,
CSharpCustomModifier.CreateRequired(comp.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_IsExternalInit)),
CSharpCustomModifier.CreateOptional(comp.GetSpecialType(SpecialType.System_Byte)));
verifyParameterType(property.SetMethod,
CSharpCustomModifier.CreateOptional(comp.GetSpecialType(SpecialType.System_UInt16)));
static void verifyReturnType(MethodSymbol method, params CustomModifier[] expectedModifiers)
{
var returnType = method.ReturnTypeWithAnnotations;
Assert.True(method.OverriddenMethod.ReturnTypeWithAnnotations.Equals(returnType, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes));
AssertEx.Equal(expectedModifiers, returnType.CustomModifiers);
}
static void verifyParameterType(MethodSymbol method, params CustomModifier[] expectedModifiers)
{
var parameterType = method.Parameters[0].TypeWithAnnotations;
Assert.True(method.OverriddenMethod.Parameters[0].TypeWithAnnotations.Equals(parameterType, TypeCompareKind.ConsiderEverything));
AssertEx.Equal(expectedModifiers, parameterType.CustomModifiers);
}
}
[WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")]
[Fact]
public void Inheritance_43()
{
var source =
@"#nullable enable
record A
{
protected virtual System.Type? EqualityContract => null;
}
record B : A
{
static void Main()
{
var b = new B();
_ = b.EqualityContract.ToString();
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
Assert.Equal("System.Type! B.EqualityContract { get; }", GetProperties(comp, "B").Single().ToTestDisplayString(includeNonNullable: true));
}
// No EqualityContract property on base.
[Fact]
public void Inheritance_44()
{
var sourceA =
@".class public System.Runtime.CompilerServices.IsExternalInit
{
.method public hidebysig specialname rtspecialname instance void .ctor() { ldnull throw }
}
.class public A
{
.method family hidebysig specialname rtspecialname instance void .ctor()
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.method family hidebysig specialname rtspecialname instance void .ctor(class A A_1) { ldnull throw }
.method public hidebysig newslot specialname virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { ldnull throw }
.property instance object P()
{
.get instance object A::get_P()
.set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) A::set_P(object)
}
.method public instance object get_P() { ldnull ret }
.method public instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(object 'value') { ret }
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}";
var refA = CompileIL(sourceA);
var sourceB =
@"record B : A;
";
var comp = CreateCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (1,8): error CS0115: 'B.EqualityContract': no suitable method found to override
// record B : A;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.EqualityContract").WithLocation(1, 8));
AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, GetProperties(comp, "B").ToTestDisplayStrings());
}
[Theory, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
[InlineData(false)]
[InlineData(true)]
public void CopyCtor(bool useCompilationReference)
{
var sourceA =
@"public record B(object N1, object N2)
{
}";
var compA = CreateCompilation(RuntimeUtilities.IsCoreClrRuntime ? sourceA : new[] { sourceA, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.StandardLatest);
var verifierA = CompileAndVerify(compA, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics();
verifierA.VerifyIL("B..ctor(B)", @"
{
// Code size 31 (0x1f)
.maxstack 2
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ldarg.0
IL_0007: ldarg.1
IL_0008: ldfld ""object B.<N1>k__BackingField""
IL_000d: stfld ""object B.<N1>k__BackingField""
IL_0012: ldarg.0
IL_0013: ldarg.1
IL_0014: ldfld ""object B.<N2>k__BackingField""
IL_0019: stfld ""object B.<N2>k__BackingField""
IL_001e: ret
}");
var refA = useCompilationReference ? compA.ToMetadataReference() : compA.EmitToImageReference();
var sourceB =
@"record C(object P1, object P2) : B(3, 4)
{
static void Main()
{
var c1 = new C(1, 2);
System.Console.Write((c1.P1, c1.P2, c1.N1, c1.N2));
System.Console.Write("" "");
var c2 = new C(c1);
System.Console.Write((c2.P1, c2.P2, c2.N1, c2.N2));
System.Console.Write("" "");
var c3 = c1 with { P1 = 10, N1 = 30 };
System.Console.Write((c3.P1, c3.P2, c3.N1, c3.N2));
}
}";
var compB = CreateCompilation(RuntimeUtilities.IsCoreClrRuntime ? sourceB : new[] { sourceB, IsExternalInitTypeDefinition }, references: new[] { refA }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, targetFramework: TargetFramework.StandardLatest);
var verifierB = CompileAndVerify(compB, expectedOutput: "(1, 2, 3, 4) (1, 2, 3, 4) (10, 2, 30, 4)", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics();
// call base copy constructor B..ctor(B)
verifierB.VerifyIL("C..ctor(C)", @"
{
// Code size 32 (0x20)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""B..ctor(B)""
IL_0007: ldarg.0
IL_0008: ldarg.1
IL_0009: ldfld ""object C.<P1>k__BackingField""
IL_000e: stfld ""object C.<P1>k__BackingField""
IL_0013: ldarg.0
IL_0014: ldarg.1
IL_0015: ldfld ""object C.<P2>k__BackingField""
IL_001a: stfld ""object C.<P2>k__BackingField""
IL_001f: ret
}");
verifierA.VerifyIL($"B.{WellKnownMemberNames.CloneMethodName}()", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: newobj ""B..ctor(B)""
IL_0006: ret
}");
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_WithOtherOverload()
{
var source =
@"public record B(object N1, object N2)
{
public B(C c) : this(30, 40) => throw null;
}
public record C(object P1, object P2) : B(3, 4)
{
static void Main()
{
var c1 = new C(1, 2);
System.Console.Write((c1.P1, c1.P2, c1.N1, c1.N2));
System.Console.Write("" "");
var c2 = c1 with { P1 = 10, P2 = 20, N1 = 30, N2 = 40 };
System.Console.Write((c2.P1, c2.P2, c2.N1, c2.N2));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
var verifier = CompileAndVerify(comp, expectedOutput: "(1, 2, 3, 4) (10, 20, 30, 40)", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics();
// call base copy constructor B..ctor(B)
verifier.VerifyIL("C..ctor(C)", @"
{
// Code size 32 (0x20)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""B..ctor(B)""
IL_0007: ldarg.0
IL_0008: ldarg.1
IL_0009: ldfld ""object C.<P1>k__BackingField""
IL_000e: stfld ""object C.<P1>k__BackingField""
IL_0013: ldarg.0
IL_0014: ldarg.1
IL_0015: ldfld ""object C.<P2>k__BackingField""
IL_001a: stfld ""object C.<P2>k__BackingField""
IL_001f: ret
}");
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_WithObsoleteCopyConstructor()
{
var source =
@"public record B(object N1, object N2)
{
[System.Obsolete(""Obsolete"", true)]
public B(B b) { }
}
public record C(object P1, object P2) : B(3, 4) { }
";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_WithParamsCopyConstructor()
{
var source =
@"public record B(object N1, object N2)
{
public B(B b, params int[] i) : this(30, 40) { }
}
public record C(object P1, object P2) : B(3, 4) { }
";
var comp = CreateCompilation(source);
var actualMembers = comp.GetMember<NamedTypeSymbol>("B").GetMembers().Where(m => m.Name == ".ctor").ToTestDisplayStrings();
var expectedMembers = new[]
{
"B..ctor(System.Object N1, System.Object N2)",
"B..ctor(B b, params System.Int32[] i)",
"B..ctor(B original)"
};
AssertEx.Equal(expectedMembers, actualMembers);
var verifier = CompileAndVerify(comp, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics();
verifier.VerifyIL("C..ctor(C)", @"
{
// Code size 32 (0x20)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""B..ctor(B)""
IL_0007: ldarg.0
IL_0008: ldarg.1
IL_0009: ldfld ""object C.<P1>k__BackingField""
IL_000e: stfld ""object C.<P1>k__BackingField""
IL_0013: ldarg.0
IL_0014: ldarg.1
IL_0015: ldfld ""object C.<P2>k__BackingField""
IL_001a: stfld ""object C.<P2>k__BackingField""
IL_001f: ret
}
");
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_WithInitializers()
{
var source =
@"public record C(object N1, object N2)
{
private int field = 42;
public int Property = 43;
}";
var comp = CreateCompilation(source);
var verifier = CompileAndVerify(comp, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(
// (3,17): warning CS0414: The field 'C.field' is assigned but its value is never used
// private int field = 42;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field").WithArguments("C.field").WithLocation(3, 17)
);
verifier.VerifyIL("C..ctor(C)", @"
{
// Code size 55 (0x37)
.maxstack 2
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ldarg.0
IL_0007: ldarg.1
IL_0008: ldfld ""object C.<N1>k__BackingField""
IL_000d: stfld ""object C.<N1>k__BackingField""
IL_0012: ldarg.0
IL_0013: ldarg.1
IL_0014: ldfld ""object C.<N2>k__BackingField""
IL_0019: stfld ""object C.<N2>k__BackingField""
IL_001e: ldarg.0
IL_001f: ldarg.1
IL_0020: ldfld ""int C.field""
IL_0025: stfld ""int C.field""
IL_002a: ldarg.0
IL_002b: ldarg.1
IL_002c: ldfld ""int C.Property""
IL_0031: stfld ""int C.Property""
IL_0036: ret
}");
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_NotInRecordType()
{
var source =
@"public class C
{
public object Property { get; set; }
public int field = 42;
public C(C c)
{
}
}
public class D : C
{
public int field2 = 43;
public D(D d) : base(d)
{
}
}
";
var comp = CreateCompilation(source);
var verifier = CompileAndVerify(comp).VerifyDiagnostics();
verifier.VerifyIL("C..ctor(C)", @"
{
// Code size 15 (0xf)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 42
IL_0003: stfld ""int C.field""
IL_0008: ldarg.0
IL_0009: call ""object..ctor()""
IL_000e: ret
}");
verifier.VerifyIL("D..ctor(D)", @"
{
// Code size 16 (0x10)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 43
IL_0003: stfld ""int D.field2""
IL_0008: ldarg.0
IL_0009: ldarg.1
IL_000a: call ""C..ctor(C)""
IL_000f: ret
}");
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor()
{
var source =
@"public record B(object N1, object N2)
{
}
public record C(object P1, object P2) : B(0, 1)
{
public C(C c) // 1, 2
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,12): error CS1729: 'B' does not contain a constructor that takes 0 arguments
// public C(C c) // 1, 2
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("B", "0").WithLocation(6, 12),
// (6,12): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object.
// public C(C c) // 1, 2
Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "C").WithLocation(6, 12)
);
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_DerivesFromObject()
{
var source =
@"public record C(int I)
{
public int I { get; set; } = 42;
public C(C c)
{
}
public static void Main()
{
var c = new C(1);
c.I = 2;
var c2 = new C(c);
System.Console.Write((c.I, c2.I));
}
}
";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
var verifier = CompileAndVerify(comp, expectedOutput: "(2, 0)").VerifyDiagnostics(
// (1,21): warning CS8907: Parameter 'I' is unread. Did you forget to use it to initialize the property with that name?
// public record C(int I)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "I").WithArguments("I").WithLocation(1, 21)
);
verifier.VerifyIL("C..ctor(C)", @"
{
// Code size 9 (0x9)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: nop
IL_0007: nop
IL_0008: ret
}
");
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_DerivesFromObject_WithFieldInitializer()
{
var source =
@"public record C(int I)
{
public int I { get; set; } = 42;
public int field = 43;
public C(C c)
{
System.Console.Write("" RAN "");
}
public static void Main()
{
var c = new C(1);
c.I = 2;
c.field = 100;
System.Console.Write((c.I, c.field));
var c2 = new C(c);
System.Console.Write((c2.I, c2.field));
}
}
";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
var verifier = CompileAndVerify(comp, expectedOutput: "(2, 100) RAN (0, 0)").VerifyDiagnostics(
// (1,21): warning CS8907: Parameter 'I' is unread. Did you forget to use it to initialize the property with that name?
// public record C(int I)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "I").WithArguments("I").WithLocation(1, 21)
);
verifier.VerifyIL("C..ctor(C)", @"
{
// Code size 20 (0x14)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: nop
IL_0007: nop
IL_0008: ldstr "" RAN ""
IL_000d: call ""void System.Console.Write(string)""
IL_0012: nop
IL_0013: ret
}
");
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_DerivesFromObject_GivesParameterToBase()
{
var source = @"
public record C(object I)
{
public C(C c) : base(1) { }
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,21): error CS1729: 'object' does not contain a constructor that takes 1 arguments
// public C(C c) : base(1) { }
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "base").WithArguments("object", "1").WithLocation(4, 21),
// (4,21): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object.
// public C(C c) : base(1) { }
Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "base").WithLocation(4, 21)
);
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_DerivesFromObject_WithSomeOtherConstructor()
{
var source = @"
public record C(object I)
{
public C(int i) : this((object)null) { }
public static void Main()
{
var c = new C((object)null);
var c2 = new C(1);
var c3 = new C(c);
System.Console.Write(""RAN"");
}
}
";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
var verifier = CompileAndVerify(comp, expectedOutput: "RAN", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics();
verifier.VerifyIL("C..ctor(int)", @"
{
// Code size 10 (0xa)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldnull
IL_0002: call ""C..ctor(object)""
IL_0007: nop
IL_0008: nop
IL_0009: ret
}
");
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_DerivesFromObject_UsesThis()
{
var source =
@"public record C(int I)
{
public C(C c) : this(c.I)
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (3,21): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object.
// public C(C c) : this(c.I)
Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "this").WithLocation(3, 21)
);
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_UserDefined_DerivesFromObject_UsesBase()
{
var source =
@"public record C(int I)
{
public C(C c) : base()
{
System.Console.Write(""RAN "");
}
public static void Main()
{
var c = new C(1);
System.Console.Write(c.I);
System.Console.Write("" "");
var c2 = c with { I = 2 };
System.Console.Write(c2.I);
}
}
";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
var verifier = CompileAndVerify(comp, expectedOutput: "1 RAN 2", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics();
verifier.VerifyIL("C..ctor(C)", @"
{
// Code size 20 (0x14)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: nop
IL_0007: nop
IL_0008: ldstr ""RAN ""
IL_000d: call ""void System.Console.Write(string)""
IL_0012: nop
IL_0013: ret
}
");
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_NoPositionalMembers()
{
var source =
@"public record B(object N1, object N2)
{
}
public record C(object P1) : B(0, 1)
{
public C(C c) // 1, 2
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,12): error CS1729: 'B' does not contain a constructor that takes 0 arguments
// public C(C c) // 1, 2
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("B", "0").WithLocation(6, 12),
// (6,12): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object.
// public C(C c) // 1, 2
Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "C").WithLocation(6, 12)
);
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_UsesThis()
{
var source =
@"public record B(object N1, object N2)
{
}
public record C(object P1, object P2) : B(0, 1)
{
public C(C c) : this(1, 2) // 1
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,21): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object.
// public C(C c) : this(1, 2) // 1
Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "this").WithLocation(6, 21)
);
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_UsesBase()
{
var source =
@"public record B(int i)
{
}
public record C(int j) : B(0)
{
public C(C c) : base(1) // 1
{
}
}
#nullable enable
public record D(int j) : B(0)
{
public D(D? d) : base(1) // 2
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,21): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object.
// public C(C c) : base(1) // 1
Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "base").WithLocation(6, 21),
// (13,22): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object.
// public D(D? d) : base(1) // 2
Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "base").WithLocation(13, 22)
);
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_UserDefined_WithFieldInitializers()
{
var source =
@"public record C(int I)
{
}
public record D(int J) : C(1)
{
public int field = 42;
public D(D d) : base(d)
{
System.Console.Write(""RAN "");
}
public static void Main()
{
var d = new D(2);
System.Console.Write((d.I, d.J, d.field));
System.Console.Write("" "");
var d2 = d with { I = 10, J = 20 };
System.Console.Write((d2.I, d2.J, d.field));
}
}
";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
var verifier = CompileAndVerify(comp, expectedOutput: "(1, 2, 42) RAN (10, 20, 42)", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics();
verifier.VerifyIL("D..ctor(D)", @"
{
// Code size 21 (0x15)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""C..ctor(C)""
IL_0007: nop
IL_0008: nop
IL_0009: ldstr ""RAN ""
IL_000e: call ""void System.Console.Write(string)""
IL_0013: nop
IL_0014: ret
}
");
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_Synthesized_WithFieldInitializers()
{
var source =
@"public record C(int I)
{
}
public record D(int J) : C(1)
{
public int field = 42;
public static void Main()
{
var d = new D(2);
System.Console.Write((d.I, d.J, d.field));
System.Console.Write("" "");
var d2 = d with { I = 10, J = 20 };
System.Console.Write((d2.I, d2.J, d.field));
}
}
";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
var verifier = CompileAndVerify(comp, expectedOutput: "(1, 2, 42) (10, 20, 42)", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics();
verifier.VerifyIL("D..ctor(D)", @"
{
// Code size 33 (0x21)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""C..ctor(C)""
IL_0007: nop
IL_0008: ldarg.0
IL_0009: ldarg.1
IL_000a: ldfld ""int D.<J>k__BackingField""
IL_000f: stfld ""int D.<J>k__BackingField""
IL_0014: ldarg.0
IL_0015: ldarg.1
IL_0016: ldfld ""int D.field""
IL_001b: stfld ""int D.field""
IL_0020: ret
}
");
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_UserDefinedButPrivate()
{
var source =
@"public record B(object N1, object N2)
{
private B(B b) { }
}
public record C(object P1, object P2) : B(0, 1)
{
private C(C c) : base(2, 3) { } // 1
}
public record D(object P1, object P2) : B(0, 1)
{
private D(D d) : base(d) { } // 2
}
public record E(object P1, object P2) : B(0, 1); // 3
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (3,13): error CS8878: A copy constructor 'B.B(B)' must be public or protected because the record is not sealed.
// private B(B b) { }
Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "B").WithArguments("B.B(B)").WithLocation(3, 13),
// (7,13): error CS8878: A copy constructor 'C.C(C)' must be public or protected because the record is not sealed.
// private C(C c) : base(2, 3) { } // 1
Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "C").WithArguments("C.C(C)").WithLocation(7, 13),
// (7,22): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object.
// private C(C c) : base(2, 3) { } // 1
Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "base").WithLocation(7, 22),
// (11,13): error CS8878: A copy constructor 'D.D(D)' must be public or protected because the record is not sealed.
// private D(D d) : base(d) { } // 2
Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "D").WithArguments("D.D(D)").WithLocation(11, 13),
// (11,22): error CS0122: 'B.B(B)' is inaccessible due to its protection level
// private D(D d) : base(d) { } // 2
Diagnostic(ErrorCode.ERR_BadAccess, "base").WithArguments("B.B(B)").WithLocation(11, 22),
// (13,15): error CS8867: No accessible copy constructor found in base type 'B'.
// public record E(object P1, object P2) : B(0, 1); // 3
Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "E").WithArguments("B").WithLocation(13, 15)
);
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_InaccessibleToCaller()
{
var sourceA =
@"public record B(object N1, object N2)
{
internal B(B b) { }
}";
var compA = CreateCompilation(sourceA);
compA.VerifyDiagnostics(
// (3,14): error CS8878: A copy constructor 'B.B(B)' must be public or protected because the record is not sealed.
// internal B(B b) { }
Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "B").WithArguments("B.B(B)").WithLocation(3, 14)
);
var refA = compA.ToMetadataReference();
var sourceB = @"
record C(object P1, object P2) : B(3, 4); // 1
";
var compB = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9);
compB.VerifyDiagnostics(
// (2,8): error CS8867: No accessible copy constructor found in base type 'B'.
// record C(object P1, object P2) : B(3, 4); // 1
Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "C").WithArguments("B").WithLocation(2, 8)
);
var sourceC = @"
record C(object P1, object P2) : B(3, 4)
{
protected C(C c) : base(c) { } // 1, 2
}
";
var compC = CreateCompilation(sourceC, references: new[] { refA }, parseOptions: TestOptions.Regular9);
compC.VerifyDiagnostics(
// (4,24): error CS0122: 'B.B(B)' is inaccessible due to its protection level
// protected C(C c) : base(c) { } // 1, 2
Diagnostic(ErrorCode.ERR_BadAccess, "base").WithArguments("B.B(B)").WithLocation(4, 24)
);
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_InaccessibleToCallerFromPE_WithIVT()
{
var sourceA = @"
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo(""AssemblyB"")]
internal record B(object N1, object N2)
{
public B(B b) { }
}";
var compA = CreateCompilation(new[] { sourceA, IsExternalInitTypeDefinition }, assemblyName: "AssemblyA", parseOptions: TestOptions.Regular9);
var refA = compA.EmitToImageReference();
var sourceB = @"
record C(int j) : B(3, 4);
";
var compB = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9, assemblyName: "AssemblyB");
compB.VerifyDiagnostics();
var sourceC = @"
record C(int j) : B(3, 4)
{
protected C(C c) : base(c) { }
}
";
var compC = CreateCompilation(sourceC, references: new[] { refA }, parseOptions: TestOptions.Regular9, assemblyName: "AssemblyB");
compC.VerifyDiagnostics();
var compB2 = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9, assemblyName: "AssemblyB2");
compB2.VerifyEmitDiagnostics(
// (2,8): error CS0115: 'C.ToString()': no suitable method found to override
// record C(int j) : B(3, 4);
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.ToString()").WithLocation(2, 8),
// (2,8): error CS0115: 'C.GetHashCode()': no suitable method found to override
// record C(int j) : B(3, 4);
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.GetHashCode()").WithLocation(2, 8),
// (2,8): error CS0115: 'C.EqualityContract': no suitable method found to override
// record C(int j) : B(3, 4);
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.EqualityContract").WithLocation(2, 8),
// (2,8): error CS0115: 'C.Equals(object?)': no suitable method found to override
// record C(int j) : B(3, 4);
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.Equals(object?)").WithLocation(2, 8),
// (2,8): error CS0115: 'C.PrintMembers(StringBuilder)': no suitable method found to override
// record C(int j) : B(3, 4);
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8),
// (2,19): error CS0122: 'B' is inaccessible due to its protection level
// record C(int j) : B(3, 4);
Diagnostic(ErrorCode.ERR_BadAccess, "B").WithArguments("B").WithLocation(2, 19),
// (2,20): error CS0122: 'B.B(object, object)' is inaccessible due to its protection level
// record C(int j) : B(3, 4);
Diagnostic(ErrorCode.ERR_BadAccess, "(3, 4)").WithArguments("B.B(object, object)").WithLocation(2, 20)
);
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
[WorkItem(45012, "https://github.com/dotnet/roslyn/issues/45012")]
public void CopyCtor_UserDefinedButPrivate_InSealedType()
{
var source =
@"public record B(int i)
{
}
public sealed record C(int j) : B(0)
{
private C(C c) : base(c)
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var copyCtor = comp.GetMembers("C..ctor")[1];
Assert.Equal("C..ctor(C c)", copyCtor.ToTestDisplayString());
Assert.True(copyCtor.DeclaredAccessibility == Accessibility.Private);
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
[WorkItem(45012, "https://github.com/dotnet/roslyn/issues/45012")]
public void CopyCtor_UserDefinedButInternal()
{
var source =
@"public record B(object N1, object N2)
{
}
public sealed record Sealed(object P1, object P2) : B(0, 1)
{
internal Sealed(Sealed s) : base(s)
{
}
}
public record Unsealed(object P1, object P2) : B(0, 1)
{
internal Unsealed(Unsealed s) : base(s)
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (12,14): error CS8878: A copy constructor 'Unsealed.Unsealed(Unsealed)' must be public or protected because the record is not sealed.
// internal Unsealed(Unsealed s) : base(s)
Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "Unsealed").WithArguments("Unsealed.Unsealed(Unsealed)").WithLocation(12, 14)
);
var sealedCopyCtor = comp.GetMembers("Sealed..ctor")[1];
Assert.Equal("Sealed..ctor(Sealed s)", sealedCopyCtor.ToTestDisplayString());
Assert.True(sealedCopyCtor.DeclaredAccessibility == Accessibility.Internal);
var unsealedCopyCtor = comp.GetMembers("Unsealed..ctor")[1];
Assert.Equal("Unsealed..ctor(Unsealed s)", unsealedCopyCtor.ToTestDisplayString());
Assert.True(unsealedCopyCtor.DeclaredAccessibility == Accessibility.Internal);
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_BaseHasRefKind()
{
var source =
@"public record B(int i)
{
public B(ref B b) => throw null; // 1, not recognized as copy constructor
}
public record C(int j) : B(1)
{
protected C(C c) : base(c)
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (3,12): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer.
// public B(ref B b) => throw null; // 1, not recognized as copy constructor
Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "B").WithLocation(3, 12)
);
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_BaseHasRefKind_WithThisInitializer()
{
var source =
@"public record B(int i)
{
public B(ref B b) : this(0) => throw null; // 1, not recognized as copy constructor
}
public record C(int j) : B(1)
{
protected C(C c) : base(c)
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var actualMembers = comp.GetMember<NamedTypeSymbol>("B").GetMembers().Where(m => m.Name == ".ctor").ToTestDisplayStrings();
var expectedMembers = new[]
{
"B..ctor(System.Int32 i)",
"B..ctor(ref B b)",
"B..ctor(B original)"
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_WithPrivateField()
{
var source =
@"public record B(object N1, object N2)
{
private int field1 = 100;
public int GetField1() => field1;
}
public record C(object P1, object P2) : B(3, 4)
{
private int field2 = 200;
public int GetField2() => field2;
static void Main()
{
var c1 = new C(1, 2);
var c2 = new C(c1);
System.Console.Write((c2.P1, c2.P2, c2.N1, c2.N2, c2.GetField1(), c2.GetField2()));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
var verifier = CompileAndVerify(comp, expectedOutput: "(1, 2, 3, 4, 100, 200)", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics();
verifier.VerifyIL("C..ctor(C)", @"
{
// Code size 44 (0x2c)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""B..ctor(B)""
IL_0007: ldarg.0
IL_0008: ldarg.1
IL_0009: ldfld ""object C.<P1>k__BackingField""
IL_000e: stfld ""object C.<P1>k__BackingField""
IL_0013: ldarg.0
IL_0014: ldarg.1
IL_0015: ldfld ""object C.<P2>k__BackingField""
IL_001a: stfld ""object C.<P2>k__BackingField""
IL_001f: ldarg.0
IL_0020: ldarg.1
IL_0021: ldfld ""int C.field2""
IL_0026: stfld ""int C.field2""
IL_002b: ret
}");
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_MissingInMetadata()
{
// IL for `public record B { }`
var ilSource = @"
.class public auto ansi beforefieldinit B extends [mscorlib]System.Object
{
.method public hidebysig specialname newslot virtual instance class B '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals ( object '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public newslot virtual instance bool Equals ( class B '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
// Removed copy constructor
//.method public hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type B::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}
";
var source = @"
public record C : B {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (2,15): error CS8867: No accessible copy constructor found in base type 'B'.
// public record C : B {
Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "C").WithArguments("B").WithLocation(2, 15)
);
var source2 = @"
public record C : B
{
public C(C c) { }
}";
var comp2 = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp2.VerifyDiagnostics(
// (4,12): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object.
// public C(C c) { }
Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "C").WithLocation(4, 12)
);
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_InaccessibleInMetadata()
{
// IL for `public record B { }`
var ilSource = @"
.class public auto ansi beforefieldinit B extends [mscorlib]System.Object
{
.method public hidebysig specialname newslot virtual instance class B '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals ( object '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public newslot virtual instance bool Equals ( class B '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
// Inaccessible copy constructor
.method private hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type B::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}
";
var source = @"
public record C : B {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (2,15): error CS8867: No accessible copy constructor found in base type 'B'.
// public record C : B {
Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "C").WithArguments("B").WithLocation(2, 15)
);
}
[Fact, WorkItem(45077, "https://github.com/dotnet/roslyn/issues/45077")]
public void CopyCtor_AmbiguitiesInMetadata()
{
// IL for a minimal `public record B { }` with injected copy constructors
var ilSource_template = @"
.class public auto ansi beforefieldinit B extends [mscorlib]System.Object
{
INJECT
.method public hidebysig specialname newslot virtual instance class B '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldarg.0
IL_0001: newobj instance void B::.ctor(class B)
IL_0006: ret
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
}
.method public newslot virtual
instance bool Equals (
class B ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
}
.method family virtual instance class [mscorlib]System.Type get_EqualityContract() { ldnull ret }
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type B::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}
";
var source = @"
public record C : B
{
public static void Main()
{
var c = new C();
_ = c with { };
}
}";
// We're going to inject various copy constructors into record B (at INJECT marker), and check which one is used
// by derived record C
// The RAN and THROW markers are shorthands for method bodies that print "RAN" and throw, respectively.
// .ctor(B) vs. .ctor(modopt B)
verifyBoth(@"
.method public hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed
RAN
",
@"
.method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed
THROW
");
// .ctor(modopt B) alone
verify(@"
.method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed
RAN
");
// .ctor(B) vs. .ctor(modreq B)
verifyBoth(@"
.method public hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed
RAN
",
@"
.method public hidebysig specialname rtspecialname instance void .ctor ( class B modreq(int64) '' ) cil managed
THROW
");
// .ctor(modopt B) vs. .ctor(modreq B)
verifyBoth(@"
.method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed
RAN
",
@"
.method public hidebysig specialname rtspecialname instance void .ctor ( class B modreq(int64) '' ) cil managed
THROW
");
// .ctor(B) vs. .ctor(modopt1 B) and .ctor(modopt2 B)
verifyBoth(@"
.method public hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed
RAN
",
@"
.method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed
THROW
.method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int32) '' ) cil managed
THROW
");
// .ctor(B) vs. .ctor(modopt1 B) and .ctor(modreq B)
verifyBoth(@"
.method public hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed
RAN
",
@"
.method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed
THROW
.method public hidebysig specialname rtspecialname instance void .ctor ( class B modreq(int32) '' ) cil managed
THROW
");
// .ctor(modeopt1 B) vs. .ctor(modopt2 B)
verifyBoth(@"
.method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed
THROW
",
@"
.method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int32) '' ) cil managed
THROW
", isError: true);
// private .ctor(B) vs. .ctor(modopt1 B) and .ctor(modopt B)
verifyBoth(@"
.method private hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed
RAN
",
@"
.method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed
THROW
.method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int32) '' ) cil managed
THROW
", isError: true);
void verifyBoth(string inject1, string inject2, bool isError = false)
{
verify(inject1 + inject2, isError);
verify(inject2 + inject1, isError);
}
void verify(string inject, bool isError = false)
{
var ranBody = @"
{
IL_0000: ldstr ""RAN""
IL_0005: call void [mscorlib]System.Console::WriteLine(string)
IL_000a: ret
}
";
var throwBody = @"
{
IL_0000: ldnull
IL_0001: throw
}
";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition },
ilSource: ilSource_template.Replace("INJECT", inject).Replace("RAN", ranBody).Replace("THROW", throwBody),
parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
var expectedDiagnostics = isError ? new[] {
// (2,15): error CS8867: No accessible copy constructor found in base type 'B'.
// public record C : B
Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "C").WithArguments("B").WithLocation(2, 15)
} : new DiagnosticDescription[] { };
comp.VerifyDiagnostics(expectedDiagnostics);
if (expectedDiagnostics is null)
{
CompileAndVerify(comp, expectedOutput: "RAN").VerifyDiagnostics();
}
}
}
[Fact, WorkItem(45077, "https://github.com/dotnet/roslyn/issues/45077")]
public void CopyCtor_AmbiguitiesInMetadata_GenericType()
{
// IL for a minimal `public record B<T> { }` with modopt in nested position of parameter type
var ilSource = @"
.class public auto ansi beforefieldinit B`1<T> extends [mscorlib]System.Object implements class [mscorlib]System.IEquatable`1<class B`1<!T>>
{
.method family hidebysig specialname rtspecialname instance void .ctor ( class B`1<!T modopt(int64)> '' ) cil managed
{
IL_0000: ldstr ""RAN""
IL_0005: call void [mscorlib]System.Console::WriteLine(string)
IL_000a: ret
}
.method public hidebysig specialname newslot virtual instance class B`1<!T> '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldarg.0
IL_0001: newobj instance void class B`1<!T>::.ctor(class B`1<!0>)
IL_0006: ret
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
}
.method public newslot virtual instance bool Equals ( class B`1<!T> '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family virtual instance class [mscorlib]System.Type get_EqualityContract() { ldnull ret }
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type B`1::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}
";
var source = @"
public record C<T> : B<T> { }
public class Program
{
public static void Main()
{
var c = new C<string>();
_ = c with { };
}
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition },
ilSource: ilSource,
parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "RAN").VerifyDiagnostics();
}
[Theory]
[InlineData("")]
[InlineData("private")]
[InlineData("internal")]
[InlineData("private protected")]
[InlineData("internal protected")]
public void CopyCtor_Accessibility_01(string accessibility)
{
var source =
$@"
record A(int X)
{{
{ accessibility } A(A a)
=> throw null;
}}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (4,6): error CS8878: A copy constructor 'A.A(A)' must be public or protected because the record is not sealed.
// A(A a)
Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "A").WithArguments("A.A(A)").WithLocation(4, 6 + accessibility.Length)
);
}
[Theory]
[InlineData("public")]
[InlineData("protected")]
public void CopyCtor_Accessibility_02(string accessibility)
{
var source =
$@"
record A(int X)
{{
{ accessibility } A(A a)
=> System.Console.Write(""RAN"");
public static void Main()
{{
var a = new A(123);
_ = a with {{}};
}}
}}
";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: "RAN").VerifyDiagnostics();
}
[Theory]
[InlineData("")]
[InlineData("private")]
[InlineData("internal")]
[InlineData("public")]
public void CopyCtor_Accessibility_03(string accessibility)
{
var source =
$@"
sealed record A(int X)
{{
{ accessibility } A(A a)
=> System.Console.Write(""RAN"");
public static void Main()
{{
var a = new A(123);
_ = a with {{}};
}}
}}
";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: "RAN").VerifyDiagnostics();
var clone = comp.GetMember<MethodSymbol>("A." + WellKnownMemberNames.CloneMethodName);
Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility);
Assert.False(clone.IsOverride);
Assert.False(clone.IsVirtual);
Assert.False(clone.IsAbstract);
Assert.False(clone.IsSealed);
Assert.True(clone.IsImplicitlyDeclared);
}
[Theory]
[InlineData("private protected")]
[InlineData("internal protected")]
[InlineData("protected")]
public void CopyCtor_Accessibility_04(string accessibility)
{
var source =
$@"
sealed record A(int X)
{{
{ accessibility } A(A a)
=> System.Console.Write(""RAN"");
public static void Main()
{{
var a = new A(123);
_ = a with {{}};
}}
}}
";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: "RAN").VerifyDiagnostics(
// (4,15): warning CS0628: 'A.A(A)': new protected member declared in sealed type
// protected A(A a)
Diagnostic(ErrorCode.WRN_ProtectedInSealed, "A").WithArguments("A.A(A)").WithLocation(4, 6 + accessibility.Length)
);
var clone = comp.GetMember<MethodSymbol>("A." + WellKnownMemberNames.CloneMethodName);
Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility);
Assert.False(clone.IsOverride);
Assert.False(clone.IsVirtual);
Assert.False(clone.IsAbstract);
Assert.False(clone.IsSealed);
Assert.True(clone.IsImplicitlyDeclared);
}
[Fact]
public void CopyCtor_Signature_01()
{
var source =
@"
record A(int X)
{
public A(in A a) : this(-15)
=> System.Console.Write(""RAN"");
public static void Main()
{
var a = new A(123);
System.Console.Write((a with { }).X);
}
}
";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: "123").VerifyDiagnostics();
}
[Fact]
public void Deconstruct_Simple()
{
var source =
@"using System;
record B(int X, int Y)
{
public static void Main()
{
M(new B(1, 2));
}
static void M(B b)
{
switch (b)
{
case B(int x, int y):
Console.Write(x);
Console.Write(y);
break;
}
}
}";
var verifier = CompileAndVerify(source, expectedOutput: "12");
verifier.VerifyDiagnostics();
verifier.VerifyIL("B.Deconstruct", @"
{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: call ""int B.X.get""
IL_0007: stind.i4
IL_0008: ldarg.2
IL_0009: ldarg.0
IL_000a: call ""int B.Y.get""
IL_000f: stind.i4
IL_0010: ret
}");
var deconstruct = ((CSharpCompilation)verifier.Compilation).GetMember<MethodSymbol>("B.Deconstruct");
Assert.Equal(2, deconstruct.ParameterCount);
Assert.Equal(RefKind.Out, deconstruct.Parameters[0].RefKind);
Assert.Equal("X", deconstruct.Parameters[0].Name);
Assert.Equal(RefKind.Out, deconstruct.Parameters[1].RefKind);
Assert.Equal("Y", deconstruct.Parameters[1].Name);
Assert.True(deconstruct.ReturnsVoid);
Assert.False(deconstruct.IsVirtual);
Assert.False(deconstruct.IsStatic);
Assert.Equal(Accessibility.Public, deconstruct.DeclaredAccessibility);
}
[Fact]
public void Deconstruct_PositionalAndNominalProperty()
{
var source =
@"using System;
record B(int X)
{
public int Y { get; init; }
public static void Main()
{
M(new B(1));
}
static void M(B b)
{
switch (b)
{
case B(int x):
Console.Write(x);
break;
}
}
}";
var verifier = CompileAndVerify(source, expectedOutput: "1");
verifier.VerifyDiagnostics();
Assert.Equal(
"void B.Deconstruct(out System.Int32 X)",
verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_Nested()
{
var source =
@"using System;
record B(int X, int Y);
record C(B B, int Z)
{
public static void Main()
{
M(new C(new B(1, 2), 3));
}
static void M(C c)
{
switch (c)
{
case C(B(int x, int y), int z):
Console.Write(x);
Console.Write(y);
Console.Write(z);
break;
}
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "123");
verifier.VerifyDiagnostics();
verifier.VerifyIL("B.Deconstruct", @"
{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: call ""int B.X.get""
IL_0007: stind.i4
IL_0008: ldarg.2
IL_0009: ldarg.0
IL_000a: call ""int B.Y.get""
IL_000f: stind.i4
IL_0010: ret
}");
verifier.VerifyIL("C.Deconstruct", @"
{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: call ""B C.B.get""
IL_0007: stind.ref
IL_0008: ldarg.2
IL_0009: ldarg.0
IL_000a: call ""int C.Z.get""
IL_000f: stind.i4
IL_0010: ret
}");
}
[Fact]
public void Deconstruct_PropertyCollision()
{
var source =
@"using System;
record B(int X, int Y)
{
public int X => 3;
static void M(B b)
{
switch (b)
{
case B(int x, int y):
Console.Write(x);
Console.Write(y);
break;
}
}
static void Main()
{
M(new B(1, 2));
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "32");
verifier.VerifyDiagnostics(
// (3,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record B(int X, int Y)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 14)
);
Assert.Equal(
"void B.Deconstruct(out System.Int32 X, out System.Int32 Y)",
verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_MethodCollision_01()
{
var source = @"
record B(int X, int Y)
{
public int X() => 3;
static void M(B b)
{
switch (b)
{
case B(int x, int y):
break;
}
}
static void Main()
{
M(new B(1, 2));
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,16): error CS0102: The type 'B' already contains a definition for 'X'
// public int X() => 3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("B", "X").WithLocation(4, 16)
);
Assert.Equal(
"void B.Deconstruct(out System.Int32 X, out System.Int32 Y)",
comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_MethodCollision_02()
{
var source = @"
record B
{
public int X(int y) => y;
}
record C(int X, int Y) : B
{
static void M(C c)
{
switch (c)
{
case C(int x, int y):
break;
}
}
static void Main()
{
M(new C(1, 2));
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (7,14): error CS8866: Record member 'B.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'.
// record C(int X, int Y) : B
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("B.X", "int", "X").WithLocation(7, 14),
// (7,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X, int Y) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(7, 14)
);
Assert.Equal(
"void C.Deconstruct(out System.Int32 X, out System.Int32 Y)",
comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_MethodCollision_03()
{
var source = @"
using System;
record B
{
public int X() => 3;
}
record C(int X, int Y) : B
{
public new int X { get; }
static void M(C c)
{
switch (c)
{
case C(int x, int y):
Console.Write(x);
Console.Write(y);
break;
}
}
static void Main()
{
M(new C(1, 2));
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "02");
verifier.VerifyDiagnostics(
// (9,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X, int Y) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(9, 14)
);
Assert.Equal(
"void C.Deconstruct(out System.Int32 X, out System.Int32 Y)",
verifier.Compilation.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_MethodCollision_04()
{
var source = @"
record C(int X, int Y)
{
public int X(int arg) => 3;
static void M(C c)
{
switch (c)
{
case C(int x, int y):
break;
}
}
static void Main()
{
M(new C(1, 2));
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,16): error CS0102: The type 'C' already contains a definition for 'X'
// public int X(int arg) => 3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("C", "X").WithLocation(4, 16)
);
Assert.Equal(
"void C.Deconstruct(out System.Int32 X, out System.Int32 Y)",
comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_FieldCollision()
{
var source = @"
using System;
record C(int X)
{
int X;
static void M(C c)
{
switch (c)
{
case C(int x):
Console.Write(x);
break;
}
}
static void Main()
{
M(new C(0));
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (4,10): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater.
// record C(int X)
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int X").WithArguments("positional fields in records", "10.0").WithLocation(4, 10),
// (4,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(4, 14),
// (6,9): warning CS0169: The field 'C.X' is never used
// int X;
Diagnostic(ErrorCode.WRN_UnreferencedField, "X").WithArguments("C.X").WithLocation(6, 9)
);
comp = CreateCompilation(source, parseOptions: TestOptions.Regular10);
comp.VerifyDiagnostics(
// (4,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(4, 14),
// (6,9): warning CS0169: The field 'C.X' is never used
// int X;
Diagnostic(ErrorCode.WRN_UnreferencedField, "X").WithArguments("C.X").WithLocation(6, 9)
);
Assert.Equal(
"void C.Deconstruct(out System.Int32 X)",
comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_EventCollision()
{
var source = @"
using System;
record C(Action X)
{
event Action X;
static void M(C c)
{
switch (c)
{
case C(Action x):
Console.Write(x);
break;
}
}
static void Main()
{
M(new C(() => { }));
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,18): error CS0102: The type 'C' already contains a definition for 'X'
// event Action X;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("C", "X").WithLocation(6, 18),
// (6,18): warning CS0067: The event 'C.X' is never used
// event Action X;
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "X").WithArguments("C.X").WithLocation(6, 18)
);
Assert.Equal(
"void C.Deconstruct(out System.Action X)",
comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_WriteOnlyPropertyInBase()
{
var source = @"
using System;
record B
{
public int X { set { } }
}
record C(int X) : B
{
static void M(C c)
{
switch (c)
{
case C(int x):
Console.Write(x);
break;
}
}
static void Main()
{
M(new C(1));
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (9,14): error CS8866: Record member 'B.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'.
// record C(int X) : B
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("B.X", "int", "X").WithLocation(9, 14),
// (9,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(9, 14));
Assert.Equal(
"void C.Deconstruct(out System.Int32 X)",
comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_PrivateWriteOnlyPropertyInBase()
{
var source = @"
using System;
record B
{
private int X { set { } }
}
record C(int X) : B
{
static void M(C c)
{
switch (c)
{
case C(int x):
Console.Write(x);
break;
}
}
static void Main()
{
M(new C(1));
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "1");
verifier.VerifyDiagnostics();
Assert.Equal(
"void C.Deconstruct(out System.Int32 X)",
verifier.Compilation.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_Empty()
{
var source = @"
record C
{
static void M(C c)
{
switch (c)
{
case C():
break;
}
}
static void Main()
{
M(new C());
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,19): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?)
// case C():
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "()").WithArguments("C", "Deconstruct").WithLocation(8, 19),
// (8,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 0 out parameters and a void return type.
// case C():
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("C", "0").WithLocation(8, 19));
Assert.Null(comp.GetMember("C.Deconstruct"));
}
[Fact]
public void Deconstruct_Inheritance_01()
{
var source = @"
using System;
record B(int X, int Y)
{
internal B() : this(0, 1) { }
}
record C : B
{
static void M(C c)
{
switch (c)
{
case C(int x, int y):
Console.Write(x);
Console.Write(y);
break;
}
switch (c)
{
case B(int x, int y):
Console.Write(x);
Console.Write(y);
break;
}
}
static void Main()
{
M(new C());
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "0101");
verifier.VerifyDiagnostics();
var comp = verifier.Compilation;
Assert.Null(comp.GetMember("C.Deconstruct"));
Assert.Equal(
"void B.Deconstruct(out System.Int32 X, out System.Int32 Y)",
comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_Inheritance_02()
{
var source = @"
using System;
record B(int X, int Y)
{
// https://github.com/dotnet/roslyn/issues/44902
internal B() : this(0, 1) { }
}
record C(int X, int Y, int Z) : B(X, Y)
{
static void M(C c)
{
switch (c)
{
case C(int x, int y, int z):
Console.Write(x);
Console.Write(y);
Console.Write(z);
break;
}
switch (c)
{
case B(int x, int y):
Console.Write(x);
Console.Write(y);
break;
}
}
static void Main()
{
M(new C(0, 1, 2));
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "01201");
verifier.VerifyDiagnostics();
var comp = verifier.Compilation;
Assert.Equal(
"void C.Deconstruct(out System.Int32 X, out System.Int32 Y, out System.Int32 Z)",
comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false));
Assert.Equal(
"void B.Deconstruct(out System.Int32 X, out System.Int32 Y)",
comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_Inheritance_03()
{
var source = @"
using System;
record B(int X, int Y)
{
internal B() : this(0, 1) { }
}
record C(int X, int Y) : B
{
static void M(C c)
{
switch (c)
{
case C(int x, int y):
Console.Write(x);
Console.Write(y);
break;
}
switch (c)
{
case B(int x, int y):
Console.Write(x);
Console.Write(y);
break;
}
}
static void Main()
{
M(new C(0, 1));
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "0101");
verifier.VerifyDiagnostics(
// (9,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X, int Y) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(9, 14),
// (9,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X, int Y) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(9, 21)
);
var comp = verifier.Compilation;
Assert.Equal(
"void C.Deconstruct(out System.Int32 X, out System.Int32 Y)",
comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false));
Assert.Equal(
"void B.Deconstruct(out System.Int32 X, out System.Int32 Y)",
comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_Inheritance_04()
{
var source = @"
using System;
record A<T>(T P) { internal A() : this(default(T)) { } }
record B1(int P, object Q) : A<int>(P) { internal B1() : this(0, null) { } }
record B2(object P, object Q) : A<object>(P) { internal B2() : this(null, null) { } }
record B3<T>(T P, object Q) : A<T>(P) { internal B3() : this(default, 0) { } }
class C
{
static void M0(A<int> arg)
{
switch (arg)
{
case A<int>(int x):
Console.Write(x);
break;
}
}
static void M1(B1 arg)
{
switch (arg)
{
case B1(int p, object q):
Console.Write(p);
Console.Write(q);
break;
}
}
static void M2(B2 arg)
{
switch (arg)
{
case B2(object p, object q):
Console.Write(p);
Console.Write(q);
break;
}
}
static void M3(B3<int> arg)
{
switch (arg)
{
case B3<int>(int p, object q):
Console.Write(p);
Console.Write(q);
break;
}
}
static void Main()
{
M0(new A<int>(0));
M1(new B1(1, 2));
M2(new B2(3, 4));
M3(new B3<int>(5, 6));
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "0123456");
verifier.VerifyDiagnostics();
var comp = verifier.Compilation;
Assert.Equal(
"void A<T>.Deconstruct(out T P)",
comp.GetMember("A.Deconstruct").ToTestDisplayString(includeNonNullable: false));
Assert.Equal(
"void B1.Deconstruct(out System.Int32 P, out System.Object Q)",
comp.GetMember("B1.Deconstruct").ToTestDisplayString(includeNonNullable: false));
Assert.Equal(
"void B2.Deconstruct(out System.Object P, out System.Object Q)",
comp.GetMember("B2.Deconstruct").ToTestDisplayString(includeNonNullable: false));
Assert.Equal(
"void B3<T>.Deconstruct(out T P, out System.Object Q)",
comp.GetMember("B3.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_Conversion_01()
{
var source = @"
using System;
record C(int X, int Y)
{
public long X { get; init; }
public long Y { get; init; }
static void M(C c)
{
switch (c)
{
case C(int x, int y):
Console.Write(x);
Console.Write(y);
break;
}
}
static void Main()
{
M(new C(0, 1));
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,14): error CS8866: Record member 'C.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'.
// record C(int X, int Y)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("C.X", "int", "X").WithLocation(4, 14),
// (4,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X, int Y)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(4, 14),
// (4,21): error CS8866: Record member 'C.Y' must be a readable instance property or field of type 'int' to match positional parameter 'Y'.
// record C(int X, int Y)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Y").WithArguments("C.Y", "int", "Y").WithLocation(4, 21),
// (4,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X, int Y)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(4, 21));
Assert.Equal(
"void C.Deconstruct(out System.Int32 X, out System.Int32 Y)",
comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_Conversion_02()
{
var source = @"
#nullable enable
using System;
record C(string? X, string Y)
{
public string X { get; init; } = null!;
public string? Y { get; init; }
static void M(C c)
{
switch (c)
{
case C(var x, string y):
Console.Write(x);
Console.Write(y);
break;
}
}
static void Main()
{
M(new C(""a"", ""b""));
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (5,18): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record C(string? X, string Y)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(5, 18),
// (5,28): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// record C(string? X, string Y)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(5, 28)
);
Assert.Equal(
"void C.Deconstruct(out System.String? X, out System.String Y)",
comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_Conversion_03()
{
var source = @"
using System;
class Base { }
class Derived : Base { }
record C(Derived X, Base Y)
{
public Base X { get; init; }
public Derived Y { get; init; }
static void M(C c)
{
switch (c)
{
case C(Derived x, Base y):
Console.Write(x);
Console.Write(y);
break;
}
}
static void Main()
{
M(new C(new Derived(), new Base()));
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (7,18): error CS8866: Record member 'C.X' must be a readable instance property or field of type 'Derived' to match positional parameter 'X'.
// record C(Derived X, Base Y)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("C.X", "Derived", "X").WithLocation(7, 18),
// (7,18): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record C(Derived X, Base Y)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(7, 18),
// (7,26): error CS8866: Record member 'C.Y' must be a readable instance property or field of type 'Base' to match positional parameter 'Y'.
// record C(Derived X, Base Y)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Y").WithArguments("C.Y", "Base", "Y").WithLocation(7, 26),
// (7,26): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// record C(Derived X, Base Y)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(7, 26));
Assert.Equal(
"void C.Deconstruct(out Derived X, out Base Y)",
comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_Empty_WithParameterList()
{
var source = @"
record C()
{
static void M(C c)
{
switch (c)
{
case C():
break;
}
}
static void Main()
{
M(new C());
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,19): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?)
// case C():
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "()").WithArguments("C", "Deconstruct").WithLocation(8, 19),
// (8,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 0 out parameters and a void return type.
// case C():
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("C", "0").WithLocation(8, 19));
Assert.Null(comp.GetMember("C.Deconstruct"));
}
[Fact]
public void Deconstruct_Empty_WithParameterList_UserDefined_01()
{
var source =
@"using System;
record C()
{
public void Deconstruct()
{
}
static void M(C c)
{
switch (c)
{
case C():
Console.Write(12);
break;
}
}
public static void Main()
{
M(new C());
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "12");
verifier.VerifyDiagnostics();
}
[Fact]
public void Deconstruct_Empty_WithParameterList_UserDefined_02()
{
var source =
@"using System;
record C()
{
public void Deconstruct(out int X, out int Y)
{
X = 1;
Y = 2;
}
static void M(C c)
{
switch (c)
{
case C(int x, int y):
Console.Write(x);
Console.Write(y);
break;
}
}
public static void Main()
{
M(new C());
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "12");
verifier.VerifyDiagnostics();
}
[Fact]
public void Deconstruct_Empty_WithParameterList_UserDefined_03()
{
var source =
@"using System;
record C()
{
private void Deconstruct()
{
}
static void M(C c)
{
switch (c)
{
case C():
Console.Write(12);
break;
}
}
public static void Main()
{
M(new C());
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "12");
verifier.VerifyDiagnostics();
}
[Fact]
public void Deconstruct_Empty_WithParameterList_UserDefined_04()
{
var source = @"
record C()
{
static void M(C c)
{
switch (c)
{
case C():
break;
}
}
static void Main()
{
M(new C());
}
public static void Deconstruct()
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,19): error CS0176: Member 'C.Deconstruct()' cannot be accessed with an instance reference; qualify it with a type name instead
// case C():
Diagnostic(ErrorCode.ERR_ObjectProhibited, "()", isSuppressed: false).WithArguments("C.Deconstruct()").WithLocation(8, 19),
// (8,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 0 out parameters and a void return type.
// case C():
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("C", "0").WithLocation(8, 19));
}
[Fact]
public void Deconstruct_Empty_WithParameterList_UserDefined_05()
{
var source = @"
record C()
{
static void M(C c)
{
switch (c)
{
case C():
break;
}
}
static void Main()
{
M(new C());
}
public int Deconstruct()
{
return 1;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 0 out parameters and a void return type.
// case C():
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("C", "0").WithLocation(8, 19));
}
[Fact]
public void Deconstruct_UserDefined()
{
var source =
@"using System;
record B(int X, int Y)
{
public void Deconstruct(out int X, out int Y)
{
X = this.X + 1;
Y = this.Y + 2;
}
static void M(B b)
{
switch (b)
{
case B(int x, int y):
Console.Write(x);
Console.Write(y);
break;
}
}
public static void Main()
{
M(new B(0, 0));
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "12");
verifier.VerifyDiagnostics();
}
[Fact]
public void Deconstruct_UserDefined_DifferentSignature_01()
{
var source =
@"using System;
record B(int X, int Y)
{
public void Deconstruct(out int Z)
{
Z = X + Y;
}
static void M(B b)
{
switch (b)
{
case B(int x, int y):
Console.Write(x);
Console.Write(y);
break;
}
switch (b)
{
case B(int z):
Console.Write(z);
break;
}
}
public static void Main()
{
M(new B(1, 2));
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "123");
verifier.VerifyDiagnostics();
var expectedSymbols = new[]
{
"void B.Deconstruct(out System.Int32 X, out System.Int32 Y)",
"void B.Deconstruct(out System.Int32 Z)",
};
Assert.Equal(expectedSymbols, verifier.Compilation.GetMembers("B.Deconstruct").Select(s => s.ToTestDisplayString(includeNonNullable: false)));
}
[Fact]
public void Deconstruct_UserDefined_DifferentSignature_02()
{
var source =
@"using System;
record B(int X)
{
public int Deconstruct(out int a) => throw null;
static void M(B b)
{
switch (b)
{
case B(int x):
Console.Write(x);
break;
}
}
public static void Main()
{
M(new B(1));
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (5,16): error CS8874: Record member 'B.Deconstruct(out int)' must return 'void'.
// public int Deconstruct(out int a) => throw null;
Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "Deconstruct").WithArguments("B.Deconstruct(out int)", "void").WithLocation(5, 16),
// (11,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'B', with 1 out parameters and a void return type.
// case B(int x):
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(int x)").WithArguments("B", "1").WithLocation(11, 19));
Assert.Equal("System.Int32 B.Deconstruct(out System.Int32 a)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_UserDefined_DifferentSignature_03()
{
var source =
@"using System;
record B(int X)
{
public void Deconstruct(int X)
{
}
static void M(B b)
{
switch (b)
{
case B(int x):
Console.Write(x);
break;
}
}
public static void Main()
{
M(new B(1));
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "1");
verifier.VerifyDiagnostics();
var expectedSymbols = new[]
{
"void B.Deconstruct(out System.Int32 X)",
"void B.Deconstruct(System.Int32 X)",
};
Assert.Equal(expectedSymbols, verifier.Compilation.GetMembers("B.Deconstruct").Select(s => s.ToTestDisplayString(includeNonNullable: false)));
}
[Fact]
public void Deconstruct_UserDefined_DifferentSignature_04()
{
var source =
@"using System;
record B(int X)
{
public void Deconstruct(ref int X)
{
}
static void M(B b)
{
switch (b)
{
case B(int x):
Console.Write(x);
break;
}
}
public static void Main()
{
M(new B(1));
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (5,17): error CS0663: 'B' cannot define an overloaded method that differs only on parameter modifiers 'ref' and 'out'
// public void Deconstruct(ref int X)
Diagnostic(ErrorCode.ERR_OverloadRefKind, "Deconstruct").WithArguments("B", "method", "ref", "out").WithLocation(5, 17)
);
Assert.Equal(2, comp.GetMembers("B.Deconstruct").Length);
}
[Fact]
public void Deconstruct_UserDefined_DifferentSignature_05()
{
var source =
@"using System;
record A(int X)
{
public A() : this(0) { }
public int Deconstruct(out int a, out int b) => throw null;
}
record B(int X, int Y) : A(X)
{
static void M(B b)
{
switch (b)
{
case B(int x, int y):
Console.Write(x);
Console.Write(y);
break;
}
}
public static void Main()
{
M(new B(1, 2));
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "12");
verifier.VerifyDiagnostics();
Assert.Equal("void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_UserDefined_DifferentSignature_06()
{
var source =
@"using System;
record A(int X)
{
public A() : this(0) { }
public virtual int Deconstruct(out int a, out int b) => throw null;
}
record B(int X, int Y) : A(X)
{
static void M(B b)
{
switch (b)
{
case B(int x, int y):
Console.Write(x);
Console.Write(y);
break;
}
}
public static void Main()
{
M(new B(1, 2));
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "12");
verifier.VerifyDiagnostics();
Assert.Equal("void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Theory]
[InlineData("")]
[InlineData("private")]
[InlineData("protected")]
[InlineData("internal")]
[InlineData("private protected")]
[InlineData("internal protected")]
public void Deconstruct_UserDefined_Accessibility_07(string accessibility)
{
var source =
$@"
record A(int X)
{{
{ accessibility } void Deconstruct(out int a)
=> throw null;
}}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (4,11): error CS8873: Record member 'A.Deconstruct(out int)' must be public.
// void Deconstruct(out int a)
Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Deconstruct").WithArguments("A.Deconstruct(out int)").WithLocation(4, 11 + accessibility.Length)
);
}
[Fact]
public void Deconstruct_UserDefined_Static_08()
{
var source =
@"
record A(int X)
{
public static void Deconstruct(out int a)
=> throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (4,24): error CS8877: Record member 'A.Deconstruct(out int)' may not be static.
// public static void Deconstruct(out int a)
Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "Deconstruct").WithArguments("A.Deconstruct(out int)").WithLocation(4, 24)
);
}
[Fact]
public void Deconstruct_Shadowing_01()
{
var source =
@"
abstract record A(int X)
{
public abstract int Deconstruct(out int a, out int b);
}
abstract record B(int X, int Y) : A(X)
{
public static void Main()
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (6,17): error CS0533: 'B.Deconstruct(out int, out int)' hides inherited abstract member 'A.Deconstruct(out int, out int)'
// abstract record B(int X, int Y) : A(X)
Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "B").WithArguments("B.Deconstruct(out int, out int)", "A.Deconstruct(out int, out int)").WithLocation(6, 17)
);
}
[Fact]
public void Deconstruct_TypeMismatch_01()
{
var source =
@"
record A(int X)
{
public System.Type X => throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (2,14): error CS8866: Record member 'A.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'.
// record A(int X)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("A.X", "int", "X").WithLocation(2, 14),
// (2,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record A(int X)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 14)
);
}
[Fact]
public void Deconstruct_TypeMismatch_02()
{
var source =
@"
record A
{
public System.Type X => throw null;
}
record B(int X) : A;
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (7,14): error CS8866: Record member 'A.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'.
// record B(int X) : A;
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("A.X", "int", "X").WithLocation(7, 14),
// (7,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record B(int X) : A;
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(7, 14)
);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/45010")]
[WorkItem(45010, "https://github.com/dotnet/roslyn/issues/45010")]
public void Deconstruct_ObsoleteProperty()
{
var source =
@"using System;
record B(int X)
{
[Obsolete] int X { get; } = X;
static void M(B b)
{
switch (b)
{
case B(int x):
Console.Write(x);
break;
}
}
public static void Main()
{
M(new B(1));
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "1");
verifier.VerifyDiagnostics();
Assert.Equal("void B.Deconstruct(out System.Int32 X)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/45009")]
[WorkItem(45009, "https://github.com/dotnet/roslyn/issues/45009")]
public void Deconstruct_RefProperty()
{
var source =
@"using System;
record B(int X)
{
static int _x = 2;
ref int X => ref _x;
static void M(B b)
{
switch (b)
{
case B(int x):
Console.Write(x);
break;
}
}
public static void Main()
{
M(new B(1));
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "2");
verifier.VerifyDiagnostics();
var deconstruct = verifier.Compilation.GetMember("B.Deconstruct");
Assert.Equal("void B.Deconstruct(out System.Int32 X)", deconstruct.ToTestDisplayString(includeNonNullable: false));
Assert.Equal(Accessibility.Public, deconstruct.DeclaredAccessibility);
Assert.False(deconstruct.IsAbstract);
Assert.False(deconstruct.IsVirtual);
Assert.False(deconstruct.IsOverride);
Assert.False(deconstruct.IsSealed);
Assert.True(deconstruct.IsImplicitlyDeclared);
}
[Fact]
public void Deconstruct_Static()
{
var source = @"
using System;
record B(int X, int Y)
{
static int Y { get; }
static void M(B b)
{
switch (b)
{
case B(int x, int y):
Console.Write(x);
Console.Write(y);
break;
}
}
public static void Main()
{
M(new B(1, 2));
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,21): error CS8866: Record member 'B.Y' must be a readable instance property or field of type 'int' to match positional parameter 'Y'.
// record B(int X, int Y)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Y").WithArguments("B.Y", "int", "Y").WithLocation(4, 21),
// (4,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// record B(int X, int Y)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(4, 21));
Assert.Equal(
"void B.Deconstruct(out System.Int32 X, out System.Int32 Y)",
comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Overrides_01(bool usePreview)
{
var source =
@"record A
{
public sealed override bool Equals(object other) => false;
public sealed override int GetHashCode() => 0;
public sealed override string ToString() => null;
}
record B(int X, int Y) : A
{
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: usePreview ? TestOptions.Regular10 : TestOptions.Regular9);
if (usePreview)
{
comp.VerifyDiagnostics(
// (3,33): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types
// public sealed override bool Equals(object other) => false;
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(3, 33),
// (4,32): error CS8870: 'A.GetHashCode()' cannot be sealed because containing record is not sealed.
// public sealed override int GetHashCode() => 0;
Diagnostic(ErrorCode.ERR_SealedAPIInRecord, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(4, 32),
// (7,8): error CS0239: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is sealed
// record B(int X, int Y) : A
Diagnostic(ErrorCode.ERR_CantOverrideSealed, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(7, 8)
);
}
else
{
comp.VerifyDiagnostics(
// (4,32): error CS8870: 'A.GetHashCode()' cannot be sealed because containing record is not sealed.
// public sealed override int GetHashCode() => 0;
Diagnostic(ErrorCode.ERR_SealedAPIInRecord, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(4, 32),
// (5,35): error CS8773: Feature 'sealed ToString in record' is not available in C# 9.0. Please use language version 10.0 or greater.
// public sealed override string ToString() => null;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "ToString").WithArguments("sealed ToString in record", "10.0").WithLocation(5, 35),
// (3,33): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types
// public sealed override bool Equals(object other) => false;
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(3, 33),
// (7,8): error CS0239: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is sealed
// record B(int X, int Y) : A
Diagnostic(ErrorCode.ERR_CantOverrideSealed, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(7, 8)
);
}
var actualMembers = comp.GetMember<NamedTypeSymbol>("B").GetMembers().ToTestDisplayStrings();
var expectedMembers = new[]
{
"B..ctor(System.Int32 X, System.Int32 Y)",
"System.Type B.EqualityContract.get",
"System.Type B.EqualityContract { get; }",
"System.Int32 B.<X>k__BackingField",
"System.Int32 B.X.get",
"void modreq(System.Runtime.CompilerServices.IsExternalInit) B.X.init",
"System.Int32 B.X { get; init; }",
"System.Int32 B.<Y>k__BackingField",
"System.Int32 B.Y.get",
"void modreq(System.Runtime.CompilerServices.IsExternalInit) B.Y.init",
"System.Int32 B.Y { get; init; }",
"System.Boolean B." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)",
"System.Boolean B.op_Inequality(B? left, B? right)",
"System.Boolean B.op_Equality(B? left, B? right)",
"System.Int32 B.GetHashCode()",
"System.Boolean B.Equals(System.Object? obj)",
"System.Boolean B.Equals(A? other)",
"System.Boolean B.Equals(B? other)",
"A B." + WellKnownMemberNames.CloneMethodName + "()",
"B..ctor(B original)",
"void B.Deconstruct(out System.Int32 X, out System.Int32 Y)"
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void Overrides_02()
{
var source =
@"abstract record A
{
public abstract override bool Equals(object other);
public abstract override int GetHashCode();
public abstract override string ToString();
}
record B(int X, int Y) : A
{
}";
var comp = CreateCompilation(RuntimeUtilities.IsCoreClrRuntime ? source : new[] { source, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.StandardLatest);
comp.VerifyDiagnostics(
// (3,35): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types
// public abstract override bool Equals(object other);
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(3, 35),
// (7,8): error CS0534: 'B' does not implement inherited abstract member 'A.Equals(object)'
// record B(int X, int Y) : A
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.Equals(object)").WithLocation(7, 8)
);
Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses);
string expectedClone = comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses
? "B B." + WellKnownMemberNames.CloneMethodName + "()"
: "A B." + WellKnownMemberNames.CloneMethodName + "()";
var actualMembers = comp.GetMember<NamedTypeSymbol>("B").GetMembers().ToTestDisplayStrings();
var expectedMembers = new[]
{
"B..ctor(System.Int32 X, System.Int32 Y)",
"System.Type B.EqualityContract.get",
"System.Type B.EqualityContract { get; }",
"System.Int32 B.<X>k__BackingField",
"System.Int32 B.X.get",
"void modreq(System.Runtime.CompilerServices.IsExternalInit) B.X.init",
"System.Int32 B.X { get; init; }",
"System.Int32 B.<Y>k__BackingField",
"System.Int32 B.Y.get",
"void modreq(System.Runtime.CompilerServices.IsExternalInit) B.Y.init",
"System.Int32 B.Y { get; init; }",
"System.String B.ToString()",
"System.Boolean B." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)",
"System.Boolean B.op_Inequality(B? left, B? right)",
"System.Boolean B.op_Equality(B? left, B? right)",
"System.Int32 B.GetHashCode()",
"System.Boolean B.Equals(System.Object? obj)",
"System.Boolean B.Equals(A? other)",
"System.Boolean B.Equals(B? other)",
expectedClone,
"B..ctor(B original)",
"void B.Deconstruct(out System.Int32 X, out System.Int32 Y)"
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void ObjectEquals_01()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public final hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0239: 'B.Equals(object?)': cannot override inherited member 'A.Equals(object)' because it is sealed
// public record B : A {
Diagnostic(ErrorCode.ERR_CantOverrideSealed, "B").WithArguments("B.Equals(object?)", "A.Equals(object)").WithLocation(2, 15)
);
}
[Fact]
public void ObjectEquals_02()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public newslot hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance string ToString () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS8869: 'B.Equals(object?)' does not override expected method from 'object'.
// public record B : A {
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "B").WithArguments("B.Equals(object?)").WithLocation(2, 15)
);
}
[Fact]
public void ObjectEquals_03()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public newslot hidebysig
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0506: 'B.Equals(object?)': cannot override inherited member 'A.Equals(object)' because it is not marked virtual, abstract, or override
// public record B : A {
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.Equals(object?)", "A.Equals(object)").WithLocation(2, 15)
);
}
[Fact]
public void ObjectEquals_04()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public newslot hidebysig virtual
instance int32 Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0508: 'B.Equals(object?)': return type must be 'int' to match overridden member 'A.Equals(object)'
// public record B : A {
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "B").WithArguments("B.Equals(object?)", "A.Equals(object)", "int").WithLocation(2, 15)
);
}
[Fact]
public void ObjectEquals_05()
{
var source0 =
@"namespace System
{
public class Object
{
public virtual int Equals(object other) => default;
public virtual int GetHashCode() => default;
public virtual string ToString() => """";
}
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Char { }
public struct Int32 { }
public interface IEquatable<T>
{
bool Equals(T other);
}
}
namespace System.Text
{
public class StringBuilder
{
public StringBuilder Append(string s) => null;
public StringBuilder Append(char c) => null;
public StringBuilder Append(object o) => null;
}
}
";
var comp = CreateEmptyCompilation(source0);
comp.VerifyDiagnostics();
var ref0 = comp.EmitToImageReference();
var source1 =
@"
public record A {
}
";
comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0508: 'A.Equals(object?)': return type must be 'int' to match overridden member 'object.Equals(object)'
// public record A {
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "A").WithArguments("A.Equals(object?)", "object.Equals(object)", "int").WithLocation(2, 15),
// (2,15): error CS0518: Predefined type 'System.Type' is not defined or imported
// public record A {
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 15),
// (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported
// public record A {
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A {
}").WithArguments("System.Exception").WithLocation(2, 1),
// (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported
// public record A {
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A {
}").WithArguments("System.Exception").WithLocation(2, 1),
// (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported
// public record A {
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A {
}").WithArguments("System.Exception").WithLocation(2, 1),
// error CS0518: Predefined type 'System.Attribute' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Attribute' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Byte' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Attribute' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Byte' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1),
// (2,1): error CS0656: Missing compiler required member 'System.Type.GetTypeFromHandle'
// public record A {
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A {
}").WithArguments("System.Type", "GetTypeFromHandle").WithLocation(2, 1),
// (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.GetHashCode'
// public record A {
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A {
}").WithArguments("System.Collections.Generic.EqualityComparer`1", "GetHashCode").WithLocation(2, 1),
// (2,1): error CS0656: Missing compiler required member 'System.Type.op_Equality'
// public record A {
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A {
}").WithArguments("System.Type", "op_Equality").WithLocation(2, 1)
);
}
[Fact]
public void ObjectEquals_06()
{
var source =
@"record A
{
public static new bool Equals(object obj) => throw null;
}
record B : A;
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (3,28): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types
// public static new bool Equals(object obj) => throw null;
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(3, 28)
);
}
[Fact]
public void ObjectGetHashCode_01()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public newslot hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source1 = @"
public record B : A {
}";
var source2 = @"
public record B : A {
public override int GetHashCode() => 0;
}";
var source3 = @"
public record C : B {
}
";
var source4 = @"
public record C : B {
public override int GetHashCode() => 0;
}
";
var comp = CreateCompilationWithIL(new[] { source1, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'.
// public record B : A {
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "B").WithArguments("B.GetHashCode()").WithLocation(2, 15)
);
comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (3,25): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'.
// public override int GetHashCode() => 0;
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("B.GetHashCode()").WithLocation(3, 25)
);
comp = CreateCompilationWithIL(new[] { source1 + source3, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'.
// public record B : A {
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "B").WithArguments("B.GetHashCode()").WithLocation(2, 15)
);
comp = CreateCompilationWithIL(new[] { source1 + source4, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'.
// public record B : A {
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "B").WithArguments("B.GetHashCode()").WithLocation(2, 15)
);
comp = CreateCompilationWithIL(new[] { source2 + source3, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (3,25): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'.
// public override int GetHashCode() => 0;
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("B.GetHashCode()").WithLocation(3, 25)
);
comp = CreateCompilationWithIL(new[] { source2 + source4, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (3,25): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'.
// public override int GetHashCode() => 0;
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("B.GetHashCode()").WithLocation(3, 25)
);
}
[Fact]
public void ObjectGetHashCode_02()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public newslot hidebysig
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source1 = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source1, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0506: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is not marked virtual, abstract, or override
// public record B : A {
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(2, 15)
);
var source2 = @"
public record B : A {
public override int GetHashCode() => throw null;
}";
comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (3,25): error CS0506: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is not marked virtual, abstract, or override
// public override int GetHashCode() => throw null;
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "GetHashCode").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(3, 25)
);
}
[Fact]
public void ObjectGetHashCode_03()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public newslot hidebysig virtual
instance bool GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0508: 'B.GetHashCode()': return type must be 'bool' to match overridden member 'A.GetHashCode()'
// public record B : A {
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()", "bool").WithLocation(2, 15)
);
var source2 = @"
public record B : A {
public override int GetHashCode() => throw null;
}";
comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (3,25): error CS0508: 'B.GetHashCode()': return type must be 'bool' to match overridden member 'A.GetHashCode()'
// public override int GetHashCode() => throw null;
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "GetHashCode").WithArguments("B.GetHashCode()", "A.GetHashCode()", "bool").WithLocation(3, 25)
);
}
[Fact]
public void ObjectGetHashCode_04()
{
var source =
@"record A
{
public override bool GetHashCode() => throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (3,26): error CS0508: 'A.GetHashCode()': return type must be 'int' to match overridden member 'object.GetHashCode()'
// public override bool GetHashCode() => throw null;
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "GetHashCode").WithArguments("A.GetHashCode()", "object.GetHashCode()", "int").WithLocation(3, 26)
);
}
[Fact]
public void ObjectGetHashCode_05()
{
var source =
@"record A
{
public new int GetHashCode() => throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (3,20): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'.
// public new int GetHashCode() => throw null;
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(3, 20)
);
}
[Fact]
public void ObjectGetHashCode_06()
{
var source =
@"record A
{
public static new int GetHashCode() => throw null;
}
record B : A;
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (3,27): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'.
// public static new int GetHashCode() => throw null;
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(3, 27),
// (6,8): error CS0506: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is not marked virtual, abstract, or override
// record B : A;
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(6, 8)
);
}
[Fact]
public void ObjectGetHashCode_07()
{
var source =
@"record A
{
public new int GetHashCode => throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (3,20): error CS0102: The type 'A' already contains a definition for 'GetHashCode'
// public new int GetHashCode => throw null;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "GetHashCode").WithArguments("A", "GetHashCode").WithLocation(3, 20)
);
}
[Fact]
public void ObjectGetHashCode_08()
{
var source =
@"record A
{
public new void GetHashCode() => throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (3,21): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'.
// public new void GetHashCode() => throw null;
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(3, 21)
);
}
[Fact]
public void ObjectGetHashCode_09()
{
var source =
@"record A
{
public void GetHashCode(int x) => throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics();
Assert.Equal("System.Int32 A.GetHashCode()", comp.GetMembers("A.GetHashCode").First().ToTestDisplayString());
}
[Fact]
public void ObjectGetHashCode_10()
{
var source =
@"
record A
{
public sealed override int GetHashCode() => throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (4,32): error CS8870: 'A.GetHashCode()' cannot be sealed because containing record is not sealed.
// public sealed override int GetHashCode() => throw null;
Diagnostic(ErrorCode.ERR_SealedAPIInRecord, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(4, 32)
);
}
[Fact]
public void ObjectGetHashCode_11()
{
var source =
@"
sealed record A
{
public sealed override int GetHashCode() => throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics();
}
[Fact]
public void ObjectGetHashCode_12()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public final hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0239: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is sealed
// public record B : A {
Diagnostic(ErrorCode.ERR_CantOverrideSealed, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(2, 15)
);
var source2 = @"
public record B : A {
public override int GetHashCode() => throw null;
}";
comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (3,25): error CS0239: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is sealed
// public override int GetHashCode() => throw null;
Diagnostic(ErrorCode.ERR_CantOverrideSealed, "GetHashCode").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(3, 25)
);
}
[Fact]
public void ObjectGetHashCode_13()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public newslot hidebysig virtual
instance class A GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source2 = @"
public record B : A {
public override A GetHashCode() => default;
}";
var comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (3,23): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'.
// public override A GetHashCode() => default;
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("B.GetHashCode()").WithLocation(3, 23)
);
}
[Fact]
public void ObjectGetHashCode_14()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public newslot hidebysig virtual
instance class A GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance string ToString () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source2 = @"
public record B : A {
public override B GetHashCode() => default;
}";
var comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (3,23): error CS8830: 'B.GetHashCode()': Target runtime doesn't support covariant return types in overrides. Return type must be 'A' to match overridden member 'A.GetHashCode()'
// public override B GetHashCode() => default;
Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportCovariantReturnsOfClasses, "GetHashCode").WithArguments("B.GetHashCode()", "A.GetHashCode()", "A").WithLocation(3, 23)
);
}
[Fact]
public void ObjectGetHashCode_15()
{
var source0 =
@"namespace System
{
public class Object
{
public virtual bool Equals(object other) => false;
public virtual Something GetHashCode() => default;
public virtual string ToString() => """";
}
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Char { }
public struct Int32 { }
public interface IEquatable<T>
{
bool Equals(T other);
}
}
namespace System.Text
{
public class StringBuilder
{
public StringBuilder Append(string s) => null;
public StringBuilder Append(char c) => null;
public StringBuilder Append(object o) => null;
}
}
public class Something
{
}
";
var comp = CreateEmptyCompilation(source0);
comp.VerifyDiagnostics();
var ref0 = comp.EmitToImageReference();
var source1 =
@"
public record A {
public override Something GetHashCode() => default;
}
";
comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (3,31): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'.
// public override Something GetHashCode() => default;
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(3, 31),
// (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported
// public record A {
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A {
public override Something GetHashCode() => default;
}").WithArguments("System.Exception").WithLocation(2, 1),
// (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported
// public record A {
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A {
public override Something GetHashCode() => default;
}").WithArguments("System.Exception").WithLocation(2, 1),
// (2,15): error CS0518: Predefined type 'System.Type' is not defined or imported
// public record A {
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 15),
// error CS0518: Predefined type 'System.Attribute' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Attribute' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Byte' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Attribute' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Byte' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1),
// (2,1): error CS0656: Missing compiler required member 'System.Type.GetTypeFromHandle'
// public record A {
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A {
public override Something GetHashCode() => default;
}").WithArguments("System.Type", "GetTypeFromHandle").WithLocation(2, 1),
// (2,1): error CS0656: Missing compiler required member 'System.Type.op_Equality'
// public record A {
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A {
public override Something GetHashCode() => default;
}").WithArguments("System.Type", "op_Equality").WithLocation(2, 1)
);
}
[Fact]
public void ObjectGetHashCode_16()
{
var source0 =
@"namespace System
{
public class Object
{
public virtual bool Equals(object other) => false;
public virtual bool GetHashCode() => default;
public virtual string ToString() => """";
}
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Char { }
public struct Int32 { }
public interface IEquatable<T>
{
bool Equals(T other);
}
}
namespace System.Text
{
public class StringBuilder
{
public StringBuilder Append(string s) => null;
public StringBuilder Append(char c) => null;
public StringBuilder Append(object o) => null;
}
}
";
var comp = CreateEmptyCompilation(source0);
comp.VerifyDiagnostics();
var ref0 = comp.EmitToImageReference();
var source1 =
@"
public record A {
public override bool GetHashCode() => default;
}
";
comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (3,26): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'.
// public override bool GetHashCode() => default;
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(3, 26),
// (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported
// public record A {
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A {
public override bool GetHashCode() => default;
}").WithArguments("System.Exception").WithLocation(2, 1),
// (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported
// public record A {
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A {
public override bool GetHashCode() => default;
}").WithArguments("System.Exception").WithLocation(2, 1),
// (2,15): error CS0518: Predefined type 'System.Type' is not defined or imported
// public record A {
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 15),
// error CS0518: Predefined type 'System.Attribute' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Attribute' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Byte' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Attribute' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Byte' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1),
// (2,1): error CS0656: Missing compiler required member 'System.Type.GetTypeFromHandle'
// public record A {
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A {
public override bool GetHashCode() => default;
}").WithArguments("System.Type", "GetTypeFromHandle").WithLocation(2, 1),
// (2,1): error CS0656: Missing compiler required member 'System.Type.op_Equality'
// public record A {
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A {
public override bool GetHashCode() => default;
}").WithArguments("System.Type", "op_Equality").WithLocation(2, 1)
);
}
[Fact]
public void ObjectGetHashCode_17()
{
var source0 =
@"namespace System
{
public class Object
{
public virtual bool Equals(object other) => false;
public virtual bool GetHashCode() => default;
public virtual string ToString() => """";
}
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Char { }
public struct Int32 { }
public interface IEquatable<T>
{
bool Equals(T other);
}
}
namespace System.Text
{
public class StringBuilder
{
public StringBuilder Append(string s) => null;
public StringBuilder Append(char c) => null;
public StringBuilder Append(object o) => null;
}
}
";
var comp = CreateEmptyCompilation(source0);
comp.VerifyDiagnostics();
var ref0 = comp.EmitToImageReference();
var source1 =
@"
public record A {
}
";
comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0508: 'A.GetHashCode()': return type must be 'bool' to match overridden member 'object.GetHashCode()'
// public record A {
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "A").WithArguments("A.GetHashCode()", "object.GetHashCode()", "bool").WithLocation(2, 15),
// (2,15): error CS0518: Predefined type 'System.Type' is not defined or imported
// public record A {
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 15),
// (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported
// public record A {
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A {
}").WithArguments("System.Exception").WithLocation(2, 1),
// (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported
// public record A {
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A {
}").WithArguments("System.Exception").WithLocation(2, 1),
// (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported
// public record A {
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A {
}").WithArguments("System.Exception").WithLocation(2, 1),
// error CS0518: Predefined type 'System.Attribute' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Attribute' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Byte' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Attribute' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Byte' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1),
// (2,1): error CS0656: Missing compiler required member 'System.Type.GetTypeFromHandle'
// public record A {
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A {
}").WithArguments("System.Type", "GetTypeFromHandle").WithLocation(2, 1),
// (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.GetHashCode'
// public record A {
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A {
}").WithArguments("System.Collections.Generic.EqualityComparer`1", "GetHashCode").WithLocation(2, 1),
// (2,1): error CS0656: Missing compiler required member 'System.Type.op_Equality'
// public record A {
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A {
}").WithArguments("System.Type", "op_Equality").WithLocation(2, 1)
);
}
[Fact]
public void BaseEquals_01()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0506: 'B.Equals(A?)': cannot override inherited member 'A.Equals(A)' because it is not marked virtual, abstract, or override
// public record B : A {
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.Equals(A?)", "A.Equals(A)").WithLocation(2, 15)
);
}
[Fact]
public void BaseEquals_02()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot final virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0506: 'B.Equals(A?)': cannot override inherited member 'A.Equals(A)' because it is not marked virtual, abstract, or override
// public record B : A {
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.Equals(A?)", "A.Equals(A)").WithLocation(2, 15)
);
}
[Fact]
public void BaseEquals_03()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance int32 Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance string ToString () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0508: 'B.Equals(A?)': return type must be 'int' to match overridden member 'A.Equals(A)'
// public record B : A {
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "B").WithArguments("B.Equals(A?)", "A.Equals(A)", "int").WithLocation(2, 15)
);
}
[Fact]
public void BaseEquals_04()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public newslot virtual
instance bool Equals (
class B ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
.class public auto ansi beforefieldinit B
extends A
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public final virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class B ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method B::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type B::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class B
";
var source = @"
public record C : B {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS8871: 'C.Equals(B?)' does not override expected method from 'B'.
// public record C : B {
Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseMethod, "C").WithArguments("C.Equals(B?)", "B").WithLocation(2, 15)
);
}
[Fact]
public void BaseEquals_05()
{
var source =
@"
record A
{
}
record B : A
{
public override bool Equals(A x) => throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (8,26): error CS0111: Type 'B' already defines a member called 'Equals' with the same parameter types
// public override bool Equals(A x) => throw null;
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "B").WithLocation(8, 26)
);
}
[Fact]
public void RecordEquals_01()
{
var source =
@"
abstract record A
{
internal static bool Report(string s) { System.Console.WriteLine(s); return false; }
public abstract bool Equals(A x);
}
record B : A
{
public virtual bool Equals(B other) => Report(""B.Equals(B)"");
}
class Program
{
static void Main()
{
A a1 = new B();
A a2 = new B();
System.Console.WriteLine(a1.Equals(a2));
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"
B.Equals(B)
False
").VerifyDiagnostics(
// (5,26): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode'
// public abstract bool Equals(A x);
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(5, 26),
// (9,25): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode'
// public virtual bool Equals(B other) => Report("B.Equals(B)");
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 25)
);
}
[Fact]
public void RecordEquals_02()
{
var source =
@"
abstract record A
{
internal static bool Report(string s) { System.Console.WriteLine(s); return false; }
public abstract bool Equals(B x);
}
record B : A
{
public override bool Equals(B other) => Report(""B.Equals(B)"");
}
class Program
{
static void Main()
{
A a1 = new B();
B b2 = new B();
System.Console.WriteLine(a1.Equals(b2));
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"
B.Equals(B)
False
").VerifyDiagnostics(
// (9,26): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode'
// public override bool Equals(B other) => Report("B.Equals(B)");
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 26)
);
var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single();
Assert.Equal("System.Boolean A.Equals(A? other)", recordEquals.ToTestDisplayString());
Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility);
Assert.False(recordEquals.IsAbstract);
Assert.True(recordEquals.IsVirtual);
Assert.False(recordEquals.IsOverride);
Assert.False(recordEquals.IsSealed);
Assert.True(recordEquals.IsImplicitlyDeclared);
}
[Fact]
public void RecordEquals_03()
{
var source =
@"
abstract record A
{
internal static bool Report(string s) { System.Console.WriteLine(s); return false; }
public abstract bool Equals(B x);
}
record B : A
{
public sealed override bool Equals(B other) => Report(""B.Equals(B)"");
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (9,33): error CS8872: 'B.Equals(B)' must allow overriding because the containing record is not sealed.
// public sealed override bool Equals(B other) => Report("B.Equals(B)");
Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "Equals").WithArguments("B.Equals(B)").WithLocation(9, 33),
// (9,33): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode'
// public sealed override bool Equals(B other) => Report("B.Equals(B)");
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 33)
);
}
[Fact]
public void RecordEquals_04()
{
var source =
@"
abstract record A
{
internal static bool Report(string s) { System.Console.WriteLine(s); return false; }
public abstract bool Equals(B x);
}
sealed record B : A
{
public sealed override bool Equals(B other) => Report(""B.Equals(B)"");
}
class Program
{
static void Main()
{
A a1 = new B();
B b2 = new B();
System.Console.WriteLine(a1.Equals(b2));
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"
B.Equals(B)
False
").VerifyDiagnostics(
// (9,33): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode'
// public sealed override bool Equals(B other) => Report("B.Equals(B)");
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 33)
);
var copyCtor = comp.GetMember<NamedTypeSymbol>("A").InstanceConstructors.Where(c => c.ParameterCount == 1).Single();
Assert.Equal(Accessibility.Protected, copyCtor.DeclaredAccessibility);
Assert.False(copyCtor.IsOverride);
Assert.False(copyCtor.IsVirtual);
Assert.False(copyCtor.IsAbstract);
Assert.False(copyCtor.IsSealed);
Assert.True(copyCtor.IsImplicitlyDeclared);
copyCtor = comp.GetMember<NamedTypeSymbol>("B").InstanceConstructors.Where(c => c.ParameterCount == 1).Single();
Assert.Equal(Accessibility.Private, copyCtor.DeclaredAccessibility);
Assert.False(copyCtor.IsOverride);
Assert.False(copyCtor.IsVirtual);
Assert.False(copyCtor.IsAbstract);
Assert.False(copyCtor.IsSealed);
Assert.True(copyCtor.IsImplicitlyDeclared);
}
[Fact]
public void RecordEquals_05()
{
var source =
@"
abstract record A
{
internal static bool Report(string s) { System.Console.WriteLine(s); return false; }
public abstract bool Equals(B x);
}
abstract record B : A
{
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (7,17): error CS0533: 'B.Equals(B?)' hides inherited abstract member 'A.Equals(B)'
// abstract record B : A
Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "B").WithArguments("B.Equals(B?)", "A.Equals(B)").WithLocation(7, 17)
);
var recordEquals = comp.GetMembers("B.Equals").OfType<SynthesizedRecordEquals>().Single();
Assert.Equal("System.Boolean B.Equals(B? other)", recordEquals.ToTestDisplayString());
Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility);
Assert.False(recordEquals.IsAbstract);
Assert.True(recordEquals.IsVirtual);
Assert.False(recordEquals.IsOverride);
Assert.False(recordEquals.IsSealed);
Assert.True(recordEquals.IsImplicitlyDeclared);
}
[Theory]
[InlineData("")]
[InlineData("sealed ")]
public void RecordEquals_06(string modifiers)
{
var source =
@"
abstract record A
{
internal static bool Report(string s) { System.Console.WriteLine(s); return false; }
public abstract bool Equals(B x);
}
" + modifiers + @"
record B : A
{
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (8,8): error CS0534: 'B' does not implement inherited abstract member 'A.Equals(B)'
// record B : A
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.Equals(B)").WithLocation(8, 8)
);
}
[Theory]
[InlineData("")]
[InlineData("sealed ")]
public void RecordEquals_07(string modifiers)
{
var source =
@"
abstract record A
{
internal static bool Report(string s) { System.Console.WriteLine(s); return false; }
public virtual bool Equals(B x) => Report(""A.Equals(B)"");
}
" + modifiers + @"
record B : A
{
}
class Program
{
static void Main()
{
A a1 = new B();
B b2 = new B();
System.Console.WriteLine(a1.Equals(b2));
System.Console.WriteLine(b2.Equals(a1));
System.Console.WriteLine(b2.Equals((B)a1));
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"
A.Equals(B)
False
True
True
").VerifyDiagnostics();
}
[Theory]
[InlineData("")]
[InlineData("sealed ")]
public void RecordEquals_08(string modifiers)
{
var source =
@"
abstract record A
{
internal static bool Report(string s) { System.Console.WriteLine(s); return false; }
public abstract bool Equals(C x);
}
abstract record B : A
{
public override bool Equals(C x) => Report(""B.Equals(C)"");
}
" + modifiers + @"
record C : B
{
}
class Program
{
static void Main()
{
A a1 = new C();
C c2 = new C();
System.Console.WriteLine(a1.Equals(c2));
System.Console.WriteLine(c2.Equals(a1));
System.Console.WriteLine(c2.Equals((C)a1));
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"
B.Equals(C)
False
True
True
").VerifyDiagnostics();
var clone = comp.GetMember<MethodSymbol>("A." + WellKnownMemberNames.CloneMethodName);
Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility);
Assert.False(clone.IsOverride);
Assert.False(clone.IsVirtual);
Assert.True(clone.IsAbstract);
Assert.False(clone.IsSealed);
Assert.True(clone.IsImplicitlyDeclared);
clone = comp.GetMember<MethodSymbol>("B." + WellKnownMemberNames.CloneMethodName);
Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility);
Assert.True(clone.IsOverride);
Assert.False(clone.IsVirtual);
Assert.True(clone.IsAbstract);
Assert.False(clone.IsSealed);
Assert.True(clone.IsImplicitlyDeclared);
clone = comp.GetMember<MethodSymbol>("C." + WellKnownMemberNames.CloneMethodName);
Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility);
Assert.True(clone.IsOverride);
Assert.False(clone.IsVirtual);
Assert.False(clone.IsAbstract);
Assert.False(clone.IsSealed);
Assert.True(clone.IsImplicitlyDeclared);
}
[Theory]
[InlineData("")]
[InlineData("sealed ")]
public void RecordEquals_09(string modifiers)
{
var source =
@"
abstract record A
{
internal static bool Report(string s) { System.Console.WriteLine(s); return false; }
public bool Equals(B x) => Report(""A.Equals(B)"");
}
" + modifiers + @"
record B : A
{
}
class Program
{
static void Main()
{
A a1 = new B();
B b2 = new B();
System.Console.WriteLine(a1.Equals(b2));
System.Console.WriteLine(b2.Equals(a1));
System.Console.WriteLine(b2.Equals((B)a1));
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"
A.Equals(B)
False
True
True
").VerifyDiagnostics();
}
[Theory]
[InlineData("protected")]
[InlineData("internal")]
[InlineData("private protected")]
[InlineData("internal protected")]
public void RecordEquals_10(string accessibility)
{
var source =
$@"
record A
{{
{ accessibility } virtual bool Equals(A x)
=> throw null;
bool System.IEquatable<A>.Equals(A x) => throw null;
}}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (4,...): error CS8873: Record member 'A.Equals(A)' must be public.
// { accessibility } virtual bool Equals(A x)
Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 19 + accessibility.Length),
// (4,...): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode'
// { accessibility } virtual bool Equals(A x)
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 19 + accessibility.Length)
);
}
[Theory]
[InlineData("")]
[InlineData("private")]
public void RecordEquals_11(string accessibility)
{
var source =
$@"
record A
{{
{ accessibility } virtual bool Equals(A x)
=> throw null;
bool System.IEquatable<A>.Equals(A x) => throw null;
}}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (4,...): error CS0621: 'A.Equals(A)': virtual or abstract members cannot be private
// virtual bool Equals(A x)
Diagnostic(ErrorCode.ERR_VirtualPrivate, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 19 + accessibility.Length),
// (4,...): error CS8873: Record member 'A.Equals(A)' must be public.
// { accessibility } virtual bool Equals(A x)
Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 19 + accessibility.Length),
// (4,...): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode'
// virtual bool Equals(A x)
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 19 + accessibility.Length)
);
}
[Fact]
public void RecordEquals_12()
{
var source =
@"
record A
{
internal static bool Report(string s) { System.Console.WriteLine(s); return false; }
public virtual bool Equals(B other) => Report(""A.Equals(B)"");
}
class B
{
}
class Program
{
static void Main()
{
A a1 = new A();
A a2 = new A();
System.Console.WriteLine(a1.Equals(a2));
System.Console.WriteLine(a1.Equals((object)a2));
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"
True
True
").VerifyDiagnostics();
var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single();
Assert.Equal("System.Boolean A.Equals(A? other)", recordEquals.ToTestDisplayString());
Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility);
Assert.False(recordEquals.IsAbstract);
Assert.True(recordEquals.IsVirtual);
Assert.False(recordEquals.IsOverride);
Assert.False(recordEquals.IsSealed);
Assert.True(recordEquals.IsImplicitlyDeclared);
}
[Fact]
public void RecordEquals_13()
{
var source =
@"
record A
{
public virtual int Equals(A other)
=> throw null;
bool System.IEquatable<A>.Equals(A x) => throw null;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (4,24): error CS8874: Record member 'A.Equals(A)' must return 'bool'.
// public virtual int Equals(A other)
Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "Equals").WithArguments("A.Equals(A)", "bool").WithLocation(4, 24),
// (4,24): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode'
// public virtual int Equals(A other)
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24)
);
}
[Fact]
public void RecordEquals_14()
{
var source =
@"
record A
{
public virtual bool Equals(A other)
=> throw null;
System.Boolean System.IEquatable<A>.Equals(A x) => throw null;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.MakeTypeMissing(SpecialType.System_Boolean);
comp.VerifyEmitDiagnostics(
// (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported
// record A
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record A
{
public virtual bool Equals(A other)
=> throw null;
System.Boolean System.IEquatable<A>.Equals(A x) => throw null;
}").WithArguments("System.Boolean").WithLocation(2, 1),
// (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported
// record A
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record A
{
public virtual bool Equals(A other)
=> throw null;
System.Boolean System.IEquatable<A>.Equals(A x) => throw null;
}").WithArguments("System.Boolean").WithLocation(2, 1),
// (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported
// record A
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record A
{
public virtual bool Equals(A other)
=> throw null;
System.Boolean System.IEquatable<A>.Equals(A x) => throw null;
}").WithArguments("System.Boolean").WithLocation(2, 1),
// (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported
// record A
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record A
{
public virtual bool Equals(A other)
=> throw null;
System.Boolean System.IEquatable<A>.Equals(A x) => throw null;
}").WithArguments("System.Boolean").WithLocation(2, 1),
// (2,8): error CS0518: Predefined type 'System.Boolean' is not defined or imported
// record A
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 8),
// (2,8): error CS0518: Predefined type 'System.Boolean' is not defined or imported
// record A
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 8),
// (2,8): error CS0518: Predefined type 'System.Boolean' is not defined or imported
// record A
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 8),
// (2,8): error CS0518: Predefined type 'System.Boolean' is not defined or imported
// record A
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 8),
// (4,20): error CS0518: Predefined type 'System.Boolean' is not defined or imported
// public virtual bool Equals(A other)
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "bool").WithArguments("System.Boolean").WithLocation(4, 20),
// (4,25): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode'
// public virtual bool Equals(A other)
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 25)
);
}
[Fact]
public void RecordEquals_15()
{
var source =
@"
record A
{
public virtual Boolean Equals(A other)
=> throw null;
bool System.IEquatable<A>.Equals(A x) => throw null;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (4,20): error CS0246: The type or namespace name 'Boolean' could not be found (are you missing a using directive or an assembly reference?)
// public virtual Boolean Equals(A other)
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Boolean").WithArguments("Boolean").WithLocation(4, 20),
// (4,28): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode'
// public virtual Boolean Equals(A other)
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 28)
);
}
[Fact]
public void RecordEquals_16()
{
var source =
@"
abstract record A
{
}
record B : A
{
}
class Program
{
static void Main()
{
A a1 = new B();
B b2 = new B();
System.Console.WriteLine(a1.Equals(b2));
System.Console.WriteLine(b2.Equals(a1));
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"
True
True
").VerifyDiagnostics();
var recordEquals = comp.GetMembers("B.Equals").OfType<SynthesizedRecordEquals>().Single();
Assert.Equal("System.Boolean B.Equals(B? other)", recordEquals.ToTestDisplayString());
Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility);
Assert.False(recordEquals.IsAbstract);
Assert.True(recordEquals.IsVirtual);
Assert.False(recordEquals.IsOverride);
Assert.False(recordEquals.IsSealed);
Assert.True(recordEquals.IsImplicitlyDeclared);
}
[Fact]
public void RecordEquals_17()
{
var source =
@"
abstract record A
{
}
sealed record B : A
{
}
class Program
{
static void Main()
{
A a1 = new B();
B b2 = new B();
System.Console.WriteLine(a1.Equals(b2));
System.Console.WriteLine(b2.Equals(a1));
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"
True
True
").VerifyDiagnostics();
var recordEquals = comp.GetMembers("B.Equals").OfType<SynthesizedRecordEquals>().Single();
Assert.Equal("System.Boolean B.Equals(B? other)", recordEquals.ToTestDisplayString());
Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility);
Assert.False(recordEquals.IsAbstract);
Assert.False(recordEquals.IsVirtual);
Assert.False(recordEquals.IsOverride);
Assert.False(recordEquals.IsSealed);
Assert.True(recordEquals.IsImplicitlyDeclared);
}
[Fact]
public void RecordEquals_18()
{
var source =
@"
sealed record A
{
}
class Program
{
static void Main()
{
A a1 = new A();
A a2 = new A();
System.Console.WriteLine(a1.Equals(a2));
System.Console.WriteLine(a2.Equals(a1));
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"
True
True
").VerifyDiagnostics();
var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single();
Assert.Equal("System.Boolean A.Equals(A? other)", recordEquals.ToTestDisplayString());
Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility);
Assert.False(recordEquals.IsAbstract);
Assert.False(recordEquals.IsVirtual);
Assert.False(recordEquals.IsOverride);
Assert.False(recordEquals.IsSealed);
Assert.True(recordEquals.IsImplicitlyDeclared);
}
[Fact]
public void RecordEquals_19()
{
var source =
@"
record A
{
public static bool Equals(A x) => throw null;
}
record B : A;
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (2,8): error CS0736: 'A' does not implement instance interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement the interface member because it is static.
// record A
Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)").WithLocation(2, 8),
// (4,24): error CS8872: 'A.Equals(A)' must allow overriding because the containing record is not sealed.
// public static bool Equals(A x) => throw null;
Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 24),
// (4,24): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode'
// public static bool Equals(A x) => throw null;
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24),
// (7,8): error CS0506: 'B.Equals(A?)': cannot override inherited member 'A.Equals(A)' because it is not marked virtual, abstract, or override
// record B : A;
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.Equals(A?)", "A.Equals(A)").WithLocation(7, 8)
);
}
[Fact]
public void RecordEquals_20()
{
var source =
@"
sealed record A
{
public static bool Equals(A x) => throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0736: 'A' does not implement instance interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement the interface member because it is static.
// sealed record A
Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)").WithLocation(2, 15),
// (4,24): error CS8877: Record member 'A.Equals(A)' may not be static.
// public static bool Equals(A x) => throw null;
Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 24),
// (4,24): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode'
// public static bool Equals(A x) => throw null;
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24)
);
}
[Fact]
public void EqualityContract_01()
{
var source =
@"
abstract record A
{
internal static bool Report(string s) { System.Console.WriteLine(s); return false; }
protected abstract System.Type EqualityContract { get; }
}
record B : A
{
protected override System.Type EqualityContract
{
get
{
Report(""B.EqualityContract"");
return typeof(B);
}
}
}
class Program
{
static void Main()
{
A a1 = new B();
A a2 = new B();
System.Console.WriteLine(a1.Equals(a2));
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"
B.EqualityContract
B.EqualityContract
True
").VerifyDiagnostics();
}
[Fact]
public void EqualityContract_02()
{
var source =
@"
abstract record A
{
internal static bool Report(string s) { System.Console.WriteLine(s); return false; }
protected abstract System.Type EqualityContract { get; }
}
record B : A
{
protected sealed override System.Type EqualityContract
{
get
{
Report(""B.EqualityContract"");
return typeof(B);
}
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (9,43): error CS8872: 'B.EqualityContract' must allow overriding because the containing record is not sealed.
// protected sealed override System.Type EqualityContract
Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("B.EqualityContract").WithLocation(9, 43)
);
}
[Fact]
public void EqualityContract_03()
{
var source =
@"
abstract record A
{
internal static bool Report(string s) { System.Console.WriteLine(s); return false; }
protected abstract System.Type EqualityContract { get; }
}
sealed record B : A
{
protected sealed override System.Type EqualityContract
{
get
{
Report(""B.EqualityContract"");
return typeof(B);
}
}
}
class Program
{
static void Main()
{
A a1 = new B();
A a2 = new B();
System.Console.WriteLine(a1.Equals(a2));
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"
B.EqualityContract
B.EqualityContract
True
").VerifyDiagnostics();
}
[Theory]
[InlineData("")]
[InlineData("sealed ")]
public void EqualityContract_04(string modifiers)
{
var source =
@"
abstract record A
{
internal static bool Report(string s) { System.Console.WriteLine(s); return false; }
protected virtual System.Type EqualityContract
{
get
{
Report(""A.EqualityContract"");
return typeof(B);
}
}
}
" + modifiers + @"
record B : A
{
}
class Program
{
static void Main()
{
A a1 = new B();
B b2 = new B();
System.Console.WriteLine(a1.Equals(b2));
System.Console.WriteLine(b2.Equals(a1));
System.Console.WriteLine(b2.Equals((B)a1));
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"
True
True
True
").VerifyDiagnostics();
var equalityContract = comp.GetMembers("B.EqualityContract").OfType<SynthesizedRecordEqualityContractProperty>().Single();
Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString());
Assert.Equal(Accessibility.Protected, equalityContract.DeclaredAccessibility);
Assert.False(equalityContract.IsAbstract);
Assert.False(equalityContract.IsVirtual);
Assert.True(equalityContract.IsOverride);
Assert.False(equalityContract.IsSealed);
Assert.True(equalityContract.IsImplicitlyDeclared);
Assert.Empty(equalityContract.DeclaringSyntaxReferences);
var equalityContractGet = equalityContract.GetMethod;
Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString());
Assert.Equal(Accessibility.Protected, equalityContractGet!.DeclaredAccessibility);
Assert.False(equalityContractGet.IsAbstract);
Assert.False(equalityContractGet.IsVirtual);
Assert.True(equalityContractGet.IsOverride);
Assert.False(equalityContractGet.IsSealed);
Assert.True(equalityContractGet.IsImplicitlyDeclared);
Assert.Empty(equalityContractGet.DeclaringSyntaxReferences);
}
[Theory]
[InlineData("public")]
[InlineData("internal")]
[InlineData("private protected")]
[InlineData("internal protected")]
public void EqualityContract_05(string accessibility)
{
var source =
$@"
record A
{{
{ accessibility } virtual System.Type EqualityContract
=> throw null;
}}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (4,...): error CS8875: Record member 'A.EqualityContract' must be protected.
// { accessibility } virtual System.Type EqualityContract
Diagnostic(ErrorCode.ERR_NonProtectedAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(4, 26 + accessibility.Length)
);
}
[Theory]
[InlineData("")]
[InlineData("private")]
public void EqualityContract_06(string accessibility)
{
var source =
$@"
record A
{{
{ accessibility } virtual System.Type EqualityContract
=> throw null;
bool System.IEquatable<A>.Equals(A x) => throw null;
}}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (4,...): error CS0621: 'A.EqualityContract': virtual or abstract members cannot be private
// { accessibility } virtual System.Type EqualityContract
Diagnostic(ErrorCode.ERR_VirtualPrivate, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(4, 26 + accessibility.Length),
// (4,...): error CS8875: Record member 'A.EqualityContract' must be protected.
// { accessibility } virtual System.Type EqualityContract
Diagnostic(ErrorCode.ERR_NonProtectedAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(4, 26 + accessibility.Length)
);
}
[Theory]
[InlineData("")]
[InlineData("abstract ")]
[InlineData("sealed ")]
public void EqualityContract_07(string modifiers)
{
var source =
@"
record A
{
}
" + modifiers + @"
record B : A
{
public void PrintEqualityContract() => System.Console.WriteLine(EqualityContract);
}
";
if (modifiers != "abstract ")
{
source +=
@"
class Program
{
static void Main()
{
A a1 = new B();
B b2 = new B();
System.Console.WriteLine(a1.Equals(b2));
System.Console.WriteLine(b2.Equals(a1));
System.Console.WriteLine(b2.Equals((B)a1));
b2.PrintEqualityContract();
}
}";
}
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: modifiers == "abstract " ? TestOptions.ReleaseDll : TestOptions.ReleaseExe);
var verifier = CompileAndVerify(comp, expectedOutput: modifiers == "abstract " ? null :
@"
True
True
True
B
").VerifyDiagnostics();
var equalityContract = comp.GetMembers("B.EqualityContract").OfType<SynthesizedRecordEqualityContractProperty>().Single();
Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString());
Assert.Equal(Accessibility.Protected, equalityContract.DeclaredAccessibility);
Assert.False(equalityContract.IsAbstract);
Assert.False(equalityContract.IsVirtual);
Assert.True(equalityContract.IsOverride);
Assert.False(equalityContract.IsSealed);
Assert.True(equalityContract.IsImplicitlyDeclared);
Assert.Empty(equalityContract.DeclaringSyntaxReferences);
var equalityContractGet = equalityContract.GetMethod;
Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString());
Assert.Equal(Accessibility.Protected, equalityContractGet!.DeclaredAccessibility);
Assert.False(equalityContractGet.IsAbstract);
Assert.False(equalityContractGet.IsVirtual);
Assert.True(equalityContractGet.IsOverride);
Assert.False(equalityContractGet.IsSealed);
Assert.True(equalityContractGet.IsImplicitlyDeclared);
Assert.Empty(equalityContractGet.DeclaringSyntaxReferences);
verifier.VerifyIL("B.EqualityContract.get", @"
{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldtoken ""B""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ret
}
");
}
[Theory]
[InlineData("")]
[InlineData("abstract ")]
[InlineData("sealed ")]
public void EqualityContract_08(string modifiers)
{
var source =
modifiers + @"
record B
{
public void PrintEqualityContract() => System.Console.WriteLine(EqualityContract);
}
";
if (modifiers != "abstract ")
{
source +=
@"
class Program
{
static void Main()
{
B a1 = new B();
B b2 = new B();
System.Console.WriteLine(a1.Equals(b2));
System.Console.WriteLine(b2.Equals(a1));
System.Console.WriteLine(b2.Equals((B)a1));
b2.PrintEqualityContract();
}
}";
}
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: modifiers == "abstract " ? TestOptions.ReleaseDll : TestOptions.ReleaseExe);
var verifier = CompileAndVerify(comp, expectedOutput: modifiers == "abstract " ? null :
@"
True
True
True
B
").VerifyDiagnostics();
var equalityContract = comp.GetMembers("B.EqualityContract").OfType<SynthesizedRecordEqualityContractProperty>().Single();
Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString());
Assert.Equal(modifiers == "sealed " ? Accessibility.Private : Accessibility.Protected, equalityContract.DeclaredAccessibility);
Assert.False(equalityContract.IsAbstract);
Assert.Equal(modifiers != "sealed ", equalityContract.IsVirtual);
Assert.False(equalityContract.IsOverride);
Assert.False(equalityContract.IsSealed);
Assert.True(equalityContract.IsImplicitlyDeclared);
Assert.Empty(equalityContract.DeclaringSyntaxReferences);
var equalityContractGet = equalityContract.GetMethod;
Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString());
Assert.Equal(modifiers == "sealed " ? Accessibility.Private : Accessibility.Protected, equalityContractGet!.DeclaredAccessibility);
Assert.False(equalityContractGet.IsAbstract);
Assert.Equal(modifiers != "sealed ", equalityContractGet.IsVirtual);
Assert.False(equalityContractGet.IsOverride);
Assert.False(equalityContractGet.IsSealed);
Assert.True(equalityContractGet.IsImplicitlyDeclared);
Assert.Empty(equalityContractGet.DeclaringSyntaxReferences);
verifier.VerifyIL("B.EqualityContract.get", @"
{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldtoken ""B""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ret
}
");
}
[Fact]
public void EqualityContract_09()
{
var source =
@"
record A
{
protected virtual int EqualityContract
=> throw null;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (4,27): error CS8874: Record member 'A.EqualityContract' must return 'Type'.
// protected virtual int EqualityContract
Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("A.EqualityContract", "System.Type").WithLocation(4, 27)
);
}
[Fact]
public void EqualityContract_10()
{
var source =
@"
record A
{
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.MakeTypeMissing(WellKnownType.System_Type);
comp.VerifyEmitDiagnostics(
// (2,1): error CS0656: Missing compiler required member 'System.Type.GetTypeFromHandle'
// record A
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"record A
{
}").WithArguments("System.Type", "GetTypeFromHandle").WithLocation(2, 1),
// (2,1): error CS0656: Missing compiler required member 'System.Type.op_Equality'
// record A
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"record A
{
}").WithArguments("System.Type", "op_Equality").WithLocation(2, 1),
// (2,8): error CS0518: Predefined type 'System.Type' is not defined or imported
// record A
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 8)
);
}
[Fact]
public void EqualityContract_11()
{
var source =
@"
record A
{
protected virtual Type EqualityContract
=> throw null;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (4,23): error CS0246: The type or namespace name 'Type' could not be found (are you missing a using directive or an assembly reference?)
// protected virtual Type EqualityContract
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Type").WithArguments("Type").WithLocation(4, 23)
);
}
[Fact]
public void EqualityContract_12()
{
var source =
@"
record A
{
protected System.Type EqualityContract
=> throw null;
}
sealed record B
{
protected System.Type EqualityContract
=> throw null;
}
sealed record C
{
protected virtual System.Type EqualityContract
=> throw null;
}
record D
{
protected virtual System.Type EqualityContract
=> throw null;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (4,27): error CS8872: 'A.EqualityContract' must allow overriding because the containing record is not sealed.
// protected System.Type EqualityContract
Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(4, 27),
// (10,27): warning CS0628: 'B.EqualityContract': new protected member declared in sealed type
// protected System.Type EqualityContract
Diagnostic(ErrorCode.WRN_ProtectedInSealed, "EqualityContract").WithArguments("B.EqualityContract").WithLocation(10, 27),
// (10,27): error CS8879: Record member 'B.EqualityContract' must be private.
// protected System.Type EqualityContract
Diagnostic(ErrorCode.ERR_NonPrivateAPIInRecord, "EqualityContract").WithArguments("B.EqualityContract").WithLocation(10, 27),
// (11,12): warning CS0628: 'B.EqualityContract.get': new protected member declared in sealed type
// => throw null;
Diagnostic(ErrorCode.WRN_ProtectedInSealed, "throw null").WithArguments("B.EqualityContract.get").WithLocation(11, 12),
// (16,35): warning CS0628: 'C.EqualityContract': new protected member declared in sealed type
// protected virtual System.Type EqualityContract
Diagnostic(ErrorCode.WRN_ProtectedInSealed, "EqualityContract").WithArguments("C.EqualityContract").WithLocation(16, 35),
// (16,35): error CS8879: Record member 'C.EqualityContract' must be private.
// protected virtual System.Type EqualityContract
Diagnostic(ErrorCode.ERR_NonPrivateAPIInRecord, "EqualityContract").WithArguments("C.EqualityContract").WithLocation(16, 35),
// (17,12): error CS0549: 'C.EqualityContract.get' is a new virtual member in sealed type 'C'
// => throw null;
Diagnostic(ErrorCode.ERR_NewVirtualInSealed, "throw null").WithArguments("C.EqualityContract.get", "C").WithLocation(17, 12)
);
}
[Fact]
public void EqualityContract_13()
{
var source =
@"
record A
{}
record B : A
{
protected System.Type EqualityContract
=> throw null;
}
sealed record C : A
{
protected System.Type EqualityContract
=> throw null;
}
sealed record D : A
{
protected virtual System.Type EqualityContract
=> throw null;
}
record E : A
{
protected virtual System.Type EqualityContract
=> throw null;
}
record F : A
{
protected override System.Type EqualityContract
=> throw null;
}
record G : A
{
protected sealed override System.Type EqualityContract
=> throw null;
}
sealed record H : A
{
protected sealed override System.Type EqualityContract
=> throw null;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (7,27): error CS8876: 'B.EqualityContract' does not override expected property from 'A'.
// protected System.Type EqualityContract
Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("B.EqualityContract", "A").WithLocation(7, 27),
// (7,27): error CS8872: 'B.EqualityContract' must allow overriding because the containing record is not sealed.
// protected System.Type EqualityContract
Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("B.EqualityContract").WithLocation(7, 27),
// (7,27): warning CS0114: 'B.EqualityContract' hides inherited member 'A.EqualityContract'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.
// protected System.Type EqualityContract
Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "EqualityContract").WithArguments("B.EqualityContract", "A.EqualityContract").WithLocation(7, 27),
// (13,27): warning CS0628: 'C.EqualityContract': new protected member declared in sealed type
// protected System.Type EqualityContract
Diagnostic(ErrorCode.WRN_ProtectedInSealed, "EqualityContract").WithArguments("C.EqualityContract").WithLocation(13, 27),
// (13,27): error CS8876: 'C.EqualityContract' does not override expected property from 'A'.
// protected System.Type EqualityContract
Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("C.EqualityContract", "A").WithLocation(13, 27),
// (13,27): warning CS0114: 'C.EqualityContract' hides inherited member 'A.EqualityContract'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.
// protected System.Type EqualityContract
Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "EqualityContract").WithArguments("C.EqualityContract", "A.EqualityContract").WithLocation(13, 27),
// (14,12): warning CS0628: 'C.EqualityContract.get': new protected member declared in sealed type
// => throw null;
Diagnostic(ErrorCode.WRN_ProtectedInSealed, "throw null").WithArguments("C.EqualityContract.get").WithLocation(14, 12),
// (19,35): warning CS0628: 'D.EqualityContract': new protected member declared in sealed type
// protected virtual System.Type EqualityContract
Diagnostic(ErrorCode.WRN_ProtectedInSealed, "EqualityContract").WithArguments("D.EqualityContract").WithLocation(19, 35),
// (19,35): error CS8876: 'D.EqualityContract' does not override expected property from 'A'.
// protected virtual System.Type EqualityContract
Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("D.EqualityContract", "A").WithLocation(19, 35),
// (19,35): warning CS0114: 'D.EqualityContract' hides inherited member 'A.EqualityContract'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.
// protected virtual System.Type EqualityContract
Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "EqualityContract").WithArguments("D.EqualityContract", "A.EqualityContract").WithLocation(19, 35),
// (20,12): error CS0549: 'D.EqualityContract.get' is a new virtual member in sealed type 'D'
// => throw null;
Diagnostic(ErrorCode.ERR_NewVirtualInSealed, "throw null").WithArguments("D.EqualityContract.get", "D").WithLocation(20, 12),
// (25,35): error CS8876: 'E.EqualityContract' does not override expected property from 'A'.
// protected virtual System.Type EqualityContract
Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("E.EqualityContract", "A").WithLocation(25, 35),
// (25,35): warning CS0114: 'E.EqualityContract' hides inherited member 'A.EqualityContract'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.
// protected virtual System.Type EqualityContract
Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "EqualityContract").WithArguments("E.EqualityContract", "A.EqualityContract").WithLocation(25, 35),
// (37,43): error CS8872: 'G.EqualityContract' must allow overriding because the containing record is not sealed.
// protected sealed override System.Type EqualityContract
Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("G.EqualityContract").WithLocation(37, 43)
);
}
[Fact]
public void EqualityContract_14()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}
public record C : A {
new protected virtual System.Type EqualityContract
=> throw null;
}
public record D : A {
new protected virtual int EqualityContract
=> throw null;
}
public record E : A {
new protected virtual Type EqualityContract
=> throw null;
}
public record F : A {
protected override System.Type EqualityContract
=> throw null;
}
";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0506: 'B.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override
// public record B : A {
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.EqualityContract", "A.EqualityContract").WithLocation(2, 15),
// (6,39): error CS8876: 'C.EqualityContract' does not override expected property from 'A'.
// new protected virtual System.Type EqualityContract
Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("C.EqualityContract", "A").WithLocation(6, 39),
// (11,31): error CS8874: Record member 'D.EqualityContract' must return 'Type'.
// new protected virtual int EqualityContract
Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("D.EqualityContract", "System.Type").WithLocation(11, 31),
// (16,27): error CS0246: The type or namespace name 'Type' could not be found (are you missing a using directive or an assembly reference?)
// new protected virtual Type EqualityContract
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Type").WithArguments("Type").WithLocation(16, 27),
// (21,36): error CS0506: 'F.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override
// protected override System.Type EqualityContract
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "EqualityContract").WithArguments("F.EqualityContract", "A.EqualityContract").WithLocation(21, 36)
);
}
[Fact]
public void EqualityContract_15()
{
var source =
@"
record A
{
protected virtual int EqualityContract
=> throw null;
}
record B : A
{
}
record C : A
{
protected override System.Type EqualityContract
=> throw null;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (4,27): error CS8874: Record member 'A.EqualityContract' must return 'Type'.
// protected virtual int EqualityContract
Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("A.EqualityContract", "System.Type").WithLocation(4, 27),
// (8,8): error CS1715: 'B.EqualityContract': type must be 'int' to match overridden member 'A.EqualityContract'
// record B : A
Diagnostic(ErrorCode.ERR_CantChangeTypeOnOverride, "B").WithArguments("B.EqualityContract", "A.EqualityContract", "int").WithLocation(8, 8),
// (14,36): error CS1715: 'C.EqualityContract': type must be 'int' to match overridden member 'A.EqualityContract'
// protected override System.Type EqualityContract
Diagnostic(ErrorCode.ERR_CantChangeTypeOnOverride, "EqualityContract").WithArguments("C.EqualityContract", "A.EqualityContract", "int").WithLocation(14, 36)
);
}
[Fact]
public void EqualityContract_16()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot final virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}
public record C : A {
new protected virtual System.Type EqualityContract
=> throw null;
}
public record D : A {
new protected virtual int EqualityContract
=> throw null;
}
public record E : A {
new protected virtual Type EqualityContract
=> throw null;
}
public record F : A {
protected override System.Type EqualityContract
=> throw null;
}
";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0506: 'B.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override
// public record B : A {
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.EqualityContract", "A.EqualityContract").WithLocation(2, 15),
// (6,39): error CS8876: 'C.EqualityContract' does not override expected property from 'A'.
// new protected virtual System.Type EqualityContract
Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("C.EqualityContract", "A").WithLocation(6, 39),
// (11,31): error CS8874: Record member 'D.EqualityContract' must return 'Type'.
// new protected virtual int EqualityContract
Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("D.EqualityContract", "System.Type").WithLocation(11, 31),
// (16,27): error CS0246: The type or namespace name 'Type' could not be found (are you missing a using directive or an assembly reference?)
// new protected virtual Type EqualityContract
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Type").WithArguments("Type").WithLocation(16, 27),
// (21,36): error CS0506: 'F.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override
// protected override System.Type EqualityContract
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "EqualityContract").WithArguments("F.EqualityContract", "A.EqualityContract").WithLocation(21, 36)
);
}
[Fact]
public void EqualityContract_17()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}
public record C : A {
protected virtual System.Type EqualityContract
=> throw null;
}
public record D : A {
protected virtual int EqualityContract
=> throw null;
}
public record E : A {
protected virtual Type EqualityContract
=> throw null;
}
public record F : A {
protected override System.Type EqualityContract
=> throw null;
}
";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0115: 'B.EqualityContract': no suitable method found to override
// public record B : A {
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.EqualityContract").WithLocation(2, 15),
// (6,35): error CS8876: 'C.EqualityContract' does not override expected property from 'A'.
// protected virtual System.Type EqualityContract
Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("C.EqualityContract", "A").WithLocation(6, 35),
// (11,27): error CS8874: Record member 'D.EqualityContract' must return 'Type'.
// protected virtual int EqualityContract
Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("D.EqualityContract", "System.Type").WithLocation(11, 27),
// (16,23): error CS0246: The type or namespace name 'Type' could not be found (are you missing a using directive or an assembly reference?)
// protected virtual Type EqualityContract
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Type").WithArguments("Type").WithLocation(16, 23),
// (21,36): error CS0115: 'F.EqualityContract': no suitable method found to override
// protected override System.Type EqualityContract
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "EqualityContract").WithArguments("F.EqualityContract").WithLocation(21, 36)
);
}
[Fact]
public void EqualityContract_18()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
} // end of class A
.class public auto ansi beforefieldinit B
extends A
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public final virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public newslot virtual
instance bool Equals (
class B ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method B::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class B ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method B::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class B
";
var source = @"
public record C : B {
}
public record D : B {
new protected virtual System.Type EqualityContract
=> throw null;
}
public record E : B {
new protected virtual int EqualityContract
=> throw null;
}
public record F : B {
new protected virtual Type EqualityContract
=> throw null;
}
public record G : B {
protected override System.Type EqualityContract
=> throw null;
}
";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS8876: 'C.EqualityContract' does not override expected property from 'B'.
// public record C : B {
Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "C").WithArguments("C.EqualityContract", "B").WithLocation(2, 15),
// (6,39): error CS8876: 'D.EqualityContract' does not override expected property from 'B'.
// new protected virtual System.Type EqualityContract
Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("D.EqualityContract", "B").WithLocation(6, 39),
// (11,31): error CS8874: Record member 'E.EqualityContract' must return 'Type'.
// new protected virtual int EqualityContract
Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("E.EqualityContract", "System.Type").WithLocation(11, 31),
// (16,27): error CS0246: The type or namespace name 'Type' could not be found (are you missing a using directive or an assembly reference?)
// new protected virtual Type EqualityContract
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Type").WithArguments("Type").WithLocation(16, 27),
// (21,36): error CS8876: 'G.EqualityContract' does not override expected property from 'B'.
// protected override System.Type EqualityContract
Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("G.EqualityContract", "B").WithLocation(21, 36)
);
}
[Fact]
public void EqualityContract_19()
{
var source =
@"sealed record A
{
protected static System.Type EqualityContract => throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (3,34): warning CS0628: 'A.EqualityContract': new protected member declared in sealed type
// protected static System.Type EqualityContract => throw null;
Diagnostic(ErrorCode.WRN_ProtectedInSealed, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(3, 34),
// (3,34): error CS8879: Record member 'A.EqualityContract' must be private.
// protected static System.Type EqualityContract => throw null;
Diagnostic(ErrorCode.ERR_NonPrivateAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(3, 34),
// (3,34): error CS8877: Record member 'A.EqualityContract' may not be static.
// protected static System.Type EqualityContract => throw null;
Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(3, 34),
// (3,54): warning CS0628: 'A.EqualityContract.get': new protected member declared in sealed type
// protected static System.Type EqualityContract => throw null;
Diagnostic(ErrorCode.WRN_ProtectedInSealed, "throw null").WithArguments("A.EqualityContract.get").WithLocation(3, 54)
);
}
[Fact]
public void EqualityContract_20()
{
var source =
@"sealed record A
{
private static System.Type EqualityContract => throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (3,32): error CS8877: Record member 'A.EqualityContract' may not be static.
// private static System.Type EqualityContract => throw null;
Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(3, 32)
);
}
[Fact]
public void EqualityContract_21()
{
var source =
@"
sealed record A
{
static void Main()
{
A a1 = new A();
A a2 = new A();
System.Console.WriteLine(a1.Equals(a2));
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: "True").VerifyDiagnostics();
var equalityContract = comp.GetMembers("A.EqualityContract").OfType<SynthesizedRecordEqualityContractProperty>().Single();
Assert.Equal("System.Type A.EqualityContract { get; }", equalityContract.ToTestDisplayString());
Assert.Equal(Accessibility.Private, equalityContract.DeclaredAccessibility);
Assert.False(equalityContract.IsAbstract);
Assert.False(equalityContract.IsVirtual);
Assert.False(equalityContract.IsOverride);
Assert.False(equalityContract.IsSealed);
Assert.True(equalityContract.IsImplicitlyDeclared);
Assert.Empty(equalityContract.DeclaringSyntaxReferences);
}
[Fact]
public void EqualityContract_22()
{
var source =
@"
record A;
sealed record B : A
{
static void Main()
{
A a1 = new B();
A a2 = new B();
System.Console.WriteLine(a1.Equals(a2));
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: "True").VerifyDiagnostics();
var equalityContract = comp.GetMembers("B.EqualityContract").OfType<SynthesizedRecordEqualityContractProperty>().Single();
Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString());
Assert.Equal(Accessibility.Protected, equalityContract.DeclaredAccessibility);
Assert.False(equalityContract.IsAbstract);
Assert.False(equalityContract.IsVirtual);
Assert.True(equalityContract.IsOverride);
Assert.False(equalityContract.IsSealed);
Assert.True(equalityContract.IsImplicitlyDeclared);
Assert.Empty(equalityContract.DeclaringSyntaxReferences);
}
[Fact]
public void EqualityContract_23()
{
var source =
@"
record A
{
protected static System.Type EqualityContract => throw null;
}
record B : A;
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (4,34): error CS8872: 'A.EqualityContract' must allow overriding because the containing record is not sealed.
// protected static System.Type EqualityContract => throw null;
Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(4, 34),
// (7,8): error CS0506: 'B.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override
// record B : A;
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.EqualityContract", "A.EqualityContract").WithLocation(7, 8)
);
}
[Fact]
[WorkItem(48723, "https://github.com/dotnet/roslyn/issues/48723")]
public void EqualityContract_24_SetterOnlyProperty()
{
var src = @"
record R
{
protected virtual System.Type EqualityContract { set { } }
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (4,35): error CS8906: Record equality contract property 'R.EqualityContract' must have a get accessor.
// protected virtual System.Type EqualityContract { set { } }
Diagnostic(ErrorCode.ERR_EqualityContractRequiresGetter, "EqualityContract").WithArguments("R.EqualityContract").WithLocation(4, 35)
);
}
[Fact]
[WorkItem(48723, "https://github.com/dotnet/roslyn/issues/48723")]
public void EqualityContract_24_GetterAndSetterProperty()
{
var src = @"
_ = new R() == new R2();
record R
{
protected virtual System.Type EqualityContract { get { System.Console.Write(""RAN ""); return GetType(); } set { } }
}
record R2 : R;
";
var comp = CreateCompilation(src, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "RAN");
}
[Fact]
[WorkItem(48723, "https://github.com/dotnet/roslyn/issues/48723")]
public void EqualityContract_25_SetterOnlyProperty_DerivedRecord()
{
var src = @"
record Base;
record R : Base
{
protected override System.Type EqualityContract { set { } }
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (5,36): error CS8906: Record equality contract property 'R.EqualityContract' must have a get accessor.
// protected override System.Type EqualityContract { set { } }
Diagnostic(ErrorCode.ERR_EqualityContractRequiresGetter, "EqualityContract").WithArguments("R.EqualityContract").WithLocation(5, 36),
// (5,55): error CS0546: 'R.EqualityContract.set': cannot override because 'Base.EqualityContract' does not have an overridable set accessor
// protected override System.Type EqualityContract { set { } }
Diagnostic(ErrorCode.ERR_NoSetToOverride, "set").WithArguments("R.EqualityContract.set", "Base.EqualityContract").WithLocation(5, 55)
);
}
[Fact]
[WorkItem(48723, "https://github.com/dotnet/roslyn/issues/48723")]
public void EqualityContract_26_SetterOnlyProperty_InMetadata()
{
// `record Base;` with modified EqualityContract property, method bodies simplified and nullability removed
var il = @"
.class public auto ansi beforefieldinit Base
extends [mscorlib]System.Object
implements class [mscorlib]System.IEquatable`1<class Base>
{
.method public hidebysig virtual instance string ToString () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig newslot virtual instance bool PrintMembers( class [mscorlib] System.Text.StringBuilder builder ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname static bool op_Inequality( class Base r1, class Base r2 ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname static bool op_Equality( class Base r1, class Base r2 ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals( object obj ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig newslot virtual instance bool Equals( class Base other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig newslot virtual instance class Base '<Clone>$'() cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig specialname rtspecialname instance void .ctor ( class Base original ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig specialname newslot virtual instance void set_EqualityContract ( class [mscorlib]System.Type 'value' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
// Property has a setter but no getter
.property instance class [mscorlib]System.Type EqualityContract()
{
.set instance void Base::set_EqualityContract(class [mscorlib]System.Type)
}
}
";
var src = @"
record R : Base;
";
var comp = CreateCompilationWithIL(src, il);
comp.VerifyEmitDiagnostics(
// (2,8): error CS0545: 'R.EqualityContract.get': cannot override because 'Base.EqualityContract' does not have an overridable get accessor
// record R : Base;
Diagnostic(ErrorCode.ERR_NoGetToOverride, "R").WithArguments("R.EqualityContract.get", "Base.EqualityContract").WithLocation(2, 8)
);
var src2 = @"
record R : Base
{
protected override System.Type EqualityContract => typeof(R);
}
";
var comp2 = CreateCompilationWithIL(src2, il);
comp2.VerifyEmitDiagnostics(
// (4,56): error CS0545: 'R.EqualityContract.get': cannot override because 'Base.EqualityContract' does not have an overridable get accessor
// protected override System.Type EqualityContract => typeof(R);
Diagnostic(ErrorCode.ERR_NoGetToOverride, "typeof(R)").WithArguments("R.EqualityContract.get", "Base.EqualityContract").WithLocation(4, 56)
);
}
[Fact]
[WorkItem(48723, "https://github.com/dotnet/roslyn/issues/48723")]
public void EqualityContract_27_GetterAndSetterProperty_ExplicitlyOverridden()
{
var src = @"
_ = new R() == new R2();
record R
{
protected virtual System.Type EqualityContract { get { System.Console.Write(""RAN ""); return GetType(); } set { } }
}
record R2 : R
{
protected override System.Type EqualityContract { get { System.Console.Write(""RAN2 ""); return GetType(); } }
}
";
var comp = CreateCompilation(src, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "RAN RAN2");
}
[Fact]
public void EqualityOperators_01()
{
var source =
@"
record A(int X)
{
public virtual bool Equals(ref A other)
=> throw null;
static void Main()
{
Test(null, null);
Test(null, new A(0));
Test(new A(1), new A(1));
Test(new A(2), new A(3));
Test(new A(4), new B(4, 5));
Test(new B(6, 7), new B(6, 7));
Test(new B(8, 9), new B(8, 10));
var a = new A(11);
Test(a, a);
}
static void Test(A a1, A a2)
{
System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == a2, a2 == a1, a1 != a2, a2 != a1);
}
}
record B(int X, int Y) : A(X);
";
var verifier = CompileAndVerify(source, expectedOutput:
@"
True True False False
False False True True
True True False False
False False True True
False False True True
True True False False
False False True True
True True False False
").VerifyDiagnostics();
var comp = (CSharpCompilation)verifier.Compilation;
MethodSymbol op = comp.GetMembers("A." + WellKnownMemberNames.EqualityOperatorName).OfType<SynthesizedRecordEqualityOperator>().Single();
Assert.Equal("System.Boolean A.op_Equality(A? left, A? right)", op.ToTestDisplayString());
Assert.Equal(Accessibility.Public, op.DeclaredAccessibility);
Assert.True(op.IsStatic);
Assert.False(op.IsAbstract);
Assert.False(op.IsVirtual);
Assert.False(op.IsOverride);
Assert.False(op.IsSealed);
Assert.True(op.IsImplicitlyDeclared);
op = comp.GetMembers("A." + WellKnownMemberNames.InequalityOperatorName).OfType<SynthesizedRecordInequalityOperator>().Single();
Assert.Equal("System.Boolean A.op_Inequality(A? left, A? right)", op.ToTestDisplayString());
Assert.Equal(Accessibility.Public, op.DeclaredAccessibility);
Assert.True(op.IsStatic);
Assert.False(op.IsAbstract);
Assert.False(op.IsVirtual);
Assert.False(op.IsOverride);
Assert.False(op.IsSealed);
Assert.True(op.IsImplicitlyDeclared);
verifier.VerifyIL("bool A.op_Equality(A, A)", @"
{
// Code size 19 (0x13)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_0011
IL_0004: ldarg.0
IL_0005: brfalse.s IL_000f
IL_0007: ldarg.0
IL_0008: ldarg.1
IL_0009: callvirt ""bool A.Equals(A)""
IL_000e: ret
IL_000f: ldc.i4.0
IL_0010: ret
IL_0011: ldc.i4.1
IL_0012: ret
}
");
verifier.VerifyIL("bool A.op_Inequality(A, A)", @"
{
// Code size 11 (0xb)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""bool A.op_Equality(A, A)""
IL_0007: ldc.i4.0
IL_0008: ceq
IL_000a: ret
}
");
}
[Fact]
public void EqualityOperators_02()
{
var source =
@"
record B;
record A(int X) : B
{
public virtual bool Equals(A other)
{
System.Console.WriteLine(""Equals(A other)"");
return base.Equals(other) && X == other.X;
}
static void Main()
{
Test(null, null);
Test(null, new A(0));
Test(new A(1), new A(1));
Test(new A(2), new A(3));
var a = new A(11);
Test(a, a);
Test(new A(3), new B());
}
static void Test(A a1, A a2)
{
System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == a2, a2 == a1, a1 != a2, a2 != a1);
}
static void Test(A a1, B b2)
{
System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == b2, b2 == a1, a1 != b2, b2 != a1);
}
}
";
var verifier = CompileAndVerify(source, expectedOutput:
@"
True True False False
Equals(A other)
Equals(A other)
False False True True
Equals(A other)
Equals(A other)
Equals(A other)
Equals(A other)
True True False False
Equals(A other)
Equals(A other)
Equals(A other)
Equals(A other)
False False True True
True True False False
Equals(A other)
Equals(A other)
False False True True
").VerifyDiagnostics(
// (6,25): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode'
// public virtual bool Equals(A other)
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(6, 25)
);
var comp = (CSharpCompilation)verifier.Compilation;
MethodSymbol op = comp.GetMembers("A." + WellKnownMemberNames.EqualityOperatorName).OfType<SynthesizedRecordEqualityOperator>().Single();
Assert.Equal("System.Boolean A.op_Equality(A? left, A? right)", op.ToTestDisplayString());
Assert.Equal(Accessibility.Public, op.DeclaredAccessibility);
Assert.True(op.IsStatic);
Assert.False(op.IsAbstract);
Assert.False(op.IsVirtual);
Assert.False(op.IsOverride);
Assert.False(op.IsSealed);
Assert.True(op.IsImplicitlyDeclared);
op = comp.GetMembers("A." + WellKnownMemberNames.InequalityOperatorName).OfType<SynthesizedRecordInequalityOperator>().Single();
Assert.Equal("System.Boolean A.op_Inequality(A? left, A? right)", op.ToTestDisplayString());
Assert.Equal(Accessibility.Public, op.DeclaredAccessibility);
Assert.True(op.IsStatic);
Assert.False(op.IsAbstract);
Assert.False(op.IsVirtual);
Assert.False(op.IsOverride);
Assert.False(op.IsSealed);
Assert.True(op.IsImplicitlyDeclared);
verifier.VerifyIL("bool A.op_Equality(A, A)", @"
{
// Code size 19 (0x13)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_0011
IL_0004: ldarg.0
IL_0005: brfalse.s IL_000f
IL_0007: ldarg.0
IL_0008: ldarg.1
IL_0009: callvirt ""bool A.Equals(A)""
IL_000e: ret
IL_000f: ldc.i4.0
IL_0010: ret
IL_0011: ldc.i4.1
IL_0012: ret
}
");
verifier.VerifyIL("bool A.op_Inequality(A, A)", @"
{
// Code size 11 (0xb)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""bool A.op_Equality(A, A)""
IL_0007: ldc.i4.0
IL_0008: ceq
IL_000a: ret
}
");
}
[Fact]
public void EqualityOperators_03()
{
var source =
@"
record A
{
public static bool operator==(A r1, A r2)
=> throw null;
public static bool operator==(A r1, string r2)
=> throw null;
public static bool operator!=(A r1, string r2)
=> throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (4,32): error CS0111: Type 'A' already defines a member called 'op_Equality' with the same parameter types
// public static bool operator==(A r1, A r2)
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "==").WithArguments("op_Equality", "A").WithLocation(4, 32)
);
}
[Fact]
public void EqualityOperators_04()
{
var source =
@"
record A
{
public static bool operator!=(A r1, A r2)
=> throw null;
public static bool operator!=(string r1, A r2)
=> throw null;
public static bool operator==(string r1, A r2)
=> throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (4,32): error CS0111: Type 'A' already defines a member called 'op_Inequality' with the same parameter types
// public static bool operator!=(A r1, A r2)
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "!=").WithArguments("op_Inequality", "A").WithLocation(4, 32)
);
}
[Fact]
public void EqualityOperators_05()
{
var source =
@"
record A
{
public static bool op_Equality(A r1, A r2)
=> throw null;
public static bool op_Equality(string r1, A r2)
=> throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (4,24): error CS0111: Type 'A' already defines a member called 'op_Equality' with the same parameter types
// public static bool op_Equality(A r1, A r2)
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "op_Equality").WithArguments("op_Equality", "A").WithLocation(4, 24)
);
}
[Fact]
public void EqualityOperators_06()
{
var source =
@"
record A
{
public static bool op_Inequality(A r1, A r2)
=> throw null;
public static bool op_Inequality(A r1, string r2)
=> throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (4,24): error CS0111: Type 'A' already defines a member called 'op_Inequality' with the same parameter types
// public static bool op_Inequality(A r1, A r2)
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "op_Inequality").WithArguments("op_Inequality", "A").WithLocation(4, 24)
);
}
[Fact]
public void EqualityOperators_07()
{
var source =
@"
record A
{
public static bool Equals(A other)
=> throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (2,8): error CS0736: 'A' does not implement instance interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement the interface member because it is static.
// record A
Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)").WithLocation(2, 8),
// (4,24): error CS8872: 'A.Equals(A)' must allow overriding because the containing record is not sealed.
// public static bool Equals(A other)
Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 24),
// (4,24): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode'
// public static bool Equals(A other)
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24)
);
}
[Fact]
public void EqualityOperators_08()
{
var source =
@"
record A
{
public virtual string Equals(A other)
=> throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (2,8): error CS0738: 'A' does not implement interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement 'IEquatable<A>.Equals(A)' because it does not have the matching return type of 'bool'.
// record A
Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)", "bool").WithLocation(2, 8),
// (4,27): error CS8874: Record member 'A.Equals(A)' must return 'bool'.
// public virtual string Equals(A other)
Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "Equals").WithArguments("A.Equals(A)", "bool").WithLocation(4, 27),
// (4,27): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode'
// public virtual string Equals(A other)
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 27)
);
}
[Theory]
[CombinatorialData]
public void EqualityOperators_09(bool useImageReference)
{
var source1 =
@"
public record A(int X)
{
}
";
var comp1 = CreateCompilation(source1);
var source2 =
@"
class Program
{
static void Main()
{
Test(null, null);
Test(null, new A(0));
Test(new A(1), new A(1));
Test(new A(2), new A(3));
}
static void Test(A a1, A a2)
{
System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == a2, a2 == a1, a1 != a2, a2 != a1);
}
}
";
CompileAndVerify(source2, references: new[] { useImageReference ? comp1.EmitToImageReference() : comp1.ToMetadataReference() }, expectedOutput:
@"
True True False False
False False True True
True True False False
False False True True
").VerifyDiagnostics();
}
[WorkItem(44692, "https://github.com/dotnet/roslyn/issues/44692")]
[Fact]
public void DuplicateProperty_01()
{
var src =
@"record C(object Q)
{
public object P { get; }
public object P { get; }
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (4,19): error CS0102: The type 'C' already contains a definition for 'P'
// public object P { get; }
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C", "P").WithLocation(4, 19));
var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type C.EqualityContract { get; }",
"System.Object C.Q { get; init; }",
"System.Object C.P { get; }",
"System.Object C.P { get; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[WorkItem(44692, "https://github.com/dotnet/roslyn/issues/44692")]
[Fact]
public void DuplicateProperty_02()
{
var src =
@"record C(object P, object Q)
{
public object P { get; }
public int P { get; }
public int Q { get; }
public object Q { get; }
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (1,17): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P, object Q)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(1, 17),
// (1,27): error CS8866: Record member 'C.Q' must be a readable instance property or field of type 'object' to match positional parameter 'Q'.
// record C(object P, object Q)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Q").WithArguments("C.Q", "object", "Q").WithLocation(1, 27),
// (1,27): warning CS8907: Parameter 'Q' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P, object Q)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Q").WithArguments("Q").WithLocation(1, 27),
// (4,16): error CS0102: The type 'C' already contains a definition for 'P'
// public int P { get; }
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C", "P").WithLocation(4, 16),
// (6,19): error CS0102: The type 'C' already contains a definition for 'Q'
// public object Q { get; }
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Q").WithArguments("C", "Q").WithLocation(6, 19));
var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type C.EqualityContract { get; }",
"System.Object C.P { get; }",
"System.Int32 C.P { get; }",
"System.Int32 C.Q { get; }",
"System.Object C.Q { get; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void DuplicateProperty_03()
{
var src =
@"record A
{
public object P { get; }
public object P { get; }
public object Q { get; }
public int Q { get; }
}
record B(object Q) : A
{
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (4,19): error CS0102: The type 'A' already contains a definition for 'P'
// public object P { get; }
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("A", "P").WithLocation(4, 19),
// (6,16): error CS0102: The type 'A' already contains a definition for 'Q'
// public int Q { get; }
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Q").WithArguments("A", "Q").WithLocation(6, 16),
// (8,17): warning CS8907: Parameter 'Q' is unread. Did you forget to use it to initialize the property with that name?
// record B(object Q) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Q").WithArguments("Q").WithLocation(8, 17));
var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings();
AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers);
}
[Fact]
public void NominalRecordWith()
{
var src = @"
using System;
record C
{
public int X { get; init; }
public string Y;
public int Z { get; set; }
public static void Main()
{
var c = new C() { X = 1, Y = ""2"", Z = 3 };
var c2 = new C() { X = 1, Y = ""2"", Z = 3 };
Console.WriteLine(c.Equals(c2));
var c3 = c2 with { X = 3, Y = ""2"", Z = 1 };
Console.WriteLine(c.Equals(c2));
Console.WriteLine(c3.Equals(c2));
Console.WriteLine(c2.X + "" "" + c2.Y + "" "" + c2.Z);
}
}";
CompileAndVerify(src, expectedOutput: @"
True
True
False
1 2 3").VerifyDiagnostics();
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void WithExprReference(bool emitRef)
{
var src = @"
public record C
{
public int X { get; init; }
}
public record D(int Y) : C;";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
var src2 = @"
using System;
class E
{
public static void Main()
{
var c = new C() { X = 1 };
var c2 = c with { X = 2 };
Console.WriteLine(c.X);
Console.WriteLine(c2.X);
var d = new D(2) { X = 1 };
var d2 = d with { X = 2, Y = 3 };
Console.WriteLine(d.X + "" "" + d.Y);
Console.WriteLine(d2.X + "" "" + d2.Y);
C c3 = d;
C c4 = d2;
c3 = c3 with { X = 3 };
c4 = c4 with { X = 4 };
d = (D)c3;
d2 = (D)c4;
Console.WriteLine(d.X + "" "" + d.Y);
Console.WriteLine(d2.X + "" "" + d2.Y);
}
}";
var verifier = CompileAndVerify(src2,
references: new[] { emitRef ? comp.EmitToImageReference() : comp.ToMetadataReference() },
expectedOutput: @"
1
2
1 2
2 3
3 2
4 3").VerifyDiagnostics();
verifier.VerifyIL("E.Main", @"
{
// Code size 318 (0x13e)
.maxstack 3
.locals init (C V_0, //c
D V_1, //d
D V_2, //d2
C V_3, //c3
C V_4, //c4
int V_5)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: ldc.i4.1
IL_0007: callvirt ""void C.X.init""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()""
IL_0013: dup
IL_0014: ldc.i4.2
IL_0015: callvirt ""void C.X.init""
IL_001a: ldloc.0
IL_001b: callvirt ""int C.X.get""
IL_0020: call ""void System.Console.WriteLine(int)""
IL_0025: callvirt ""int C.X.get""
IL_002a: call ""void System.Console.WriteLine(int)""
IL_002f: ldc.i4.2
IL_0030: newobj ""D..ctor(int)""
IL_0035: dup
IL_0036: ldc.i4.1
IL_0037: callvirt ""void C.X.init""
IL_003c: stloc.1
IL_003d: ldloc.1
IL_003e: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()""
IL_0043: castclass ""D""
IL_0048: dup
IL_0049: ldc.i4.2
IL_004a: callvirt ""void C.X.init""
IL_004f: dup
IL_0050: ldc.i4.3
IL_0051: callvirt ""void D.Y.init""
IL_0056: stloc.2
IL_0057: ldloc.1
IL_0058: callvirt ""int C.X.get""
IL_005d: stloc.s V_5
IL_005f: ldloca.s V_5
IL_0061: call ""string int.ToString()""
IL_0066: ldstr "" ""
IL_006b: ldloc.1
IL_006c: callvirt ""int D.Y.get""
IL_0071: stloc.s V_5
IL_0073: ldloca.s V_5
IL_0075: call ""string int.ToString()""
IL_007a: call ""string string.Concat(string, string, string)""
IL_007f: call ""void System.Console.WriteLine(string)""
IL_0084: ldloc.2
IL_0085: callvirt ""int C.X.get""
IL_008a: stloc.s V_5
IL_008c: ldloca.s V_5
IL_008e: call ""string int.ToString()""
IL_0093: ldstr "" ""
IL_0098: ldloc.2
IL_0099: callvirt ""int D.Y.get""
IL_009e: stloc.s V_5
IL_00a0: ldloca.s V_5
IL_00a2: call ""string int.ToString()""
IL_00a7: call ""string string.Concat(string, string, string)""
IL_00ac: call ""void System.Console.WriteLine(string)""
IL_00b1: ldloc.1
IL_00b2: stloc.3
IL_00b3: ldloc.2
IL_00b4: stloc.s V_4
IL_00b6: ldloc.3
IL_00b7: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()""
IL_00bc: dup
IL_00bd: ldc.i4.3
IL_00be: callvirt ""void C.X.init""
IL_00c3: stloc.3
IL_00c4: ldloc.s V_4
IL_00c6: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()""
IL_00cb: dup
IL_00cc: ldc.i4.4
IL_00cd: callvirt ""void C.X.init""
IL_00d2: stloc.s V_4
IL_00d4: ldloc.3
IL_00d5: castclass ""D""
IL_00da: stloc.1
IL_00db: ldloc.s V_4
IL_00dd: castclass ""D""
IL_00e2: stloc.2
IL_00e3: ldloc.1
IL_00e4: callvirt ""int C.X.get""
IL_00e9: stloc.s V_5
IL_00eb: ldloca.s V_5
IL_00ed: call ""string int.ToString()""
IL_00f2: ldstr "" ""
IL_00f7: ldloc.1
IL_00f8: callvirt ""int D.Y.get""
IL_00fd: stloc.s V_5
IL_00ff: ldloca.s V_5
IL_0101: call ""string int.ToString()""
IL_0106: call ""string string.Concat(string, string, string)""
IL_010b: call ""void System.Console.WriteLine(string)""
IL_0110: ldloc.2
IL_0111: callvirt ""int C.X.get""
IL_0116: stloc.s V_5
IL_0118: ldloca.s V_5
IL_011a: call ""string int.ToString()""
IL_011f: ldstr "" ""
IL_0124: ldloc.2
IL_0125: callvirt ""int D.Y.get""
IL_012a: stloc.s V_5
IL_012c: ldloca.s V_5
IL_012e: call ""string int.ToString()""
IL_0133: call ""string string.Concat(string, string, string)""
IL_0138: call ""void System.Console.WriteLine(string)""
IL_013d: ret
}");
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void WithExprReference_WithCovariantReturns(bool emitRef)
{
var src = @"
public record C
{
public int X { get; init; }
}
public record D(int Y) : C;";
var comp = CreateCompilation(RuntimeUtilities.IsCoreClrRuntime ? src : new[] { src, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.StandardLatest);
comp.VerifyDiagnostics();
var src2 = @"
using System;
class E
{
public static void Main()
{
var c = new C() { X = 1 };
var c2 = CHelper(c);
Console.WriteLine(c.X);
Console.WriteLine(c2.X);
var d = new D(2) { X = 1 };
var d2 = DHelper(d);
Console.WriteLine(d.X + "" "" + d.Y);
Console.WriteLine(d2.X + "" "" + d2.Y);
}
private static C CHelper(C c)
{
return c with { X = 2 };
}
private static D DHelper(D d)
{
return d with { X = 2, Y = 3 };
}
}";
var verifier = CompileAndVerify(RuntimeUtilities.IsCoreClrRuntime ? src2 : new[] { src2, IsExternalInitTypeDefinition },
references: new[] { emitRef ? comp.EmitToImageReference() : comp.ToMetadataReference() },
expectedOutput: @"
1
2
1 2
2 3", targetFramework: TargetFramework.StandardLatest).VerifyDiagnostics().VerifyIL("E.CHelper", @"
{
// Code size 14 (0xe)
.maxstack 3
IL_0000: ldarg.0
IL_0001: callvirt ""C C.<Clone>$()""
IL_0006: dup
IL_0007: ldc.i4.2
IL_0008: callvirt ""void C.X.init""
IL_000d: ret
}
");
if (RuntimeUtilities.IsCoreClrRuntime)
{
verifier.VerifyIL("E.DHelper", @"
{
// Code size 21 (0x15)
.maxstack 3
IL_0000: ldarg.0
IL_0001: callvirt ""D D.<Clone>$()""
IL_0006: dup
IL_0007: ldc.i4.2
IL_0008: callvirt ""void C.X.init""
IL_000d: dup
IL_000e: ldc.i4.3
IL_000f: callvirt ""void D.Y.init""
IL_0014: ret
}
");
}
else
{
verifier.VerifyIL("E.DHelper", @"
{
// Code size 26 (0x1a)
.maxstack 3
IL_0000: ldarg.0
IL_0001: callvirt ""C C.<Clone>$()""
IL_0006: castclass ""D""
IL_000b: dup
IL_000c: ldc.i4.2
IL_000d: callvirt ""void C.X.init""
IL_0012: dup
IL_0013: ldc.i4.3
IL_0014: callvirt ""void D.Y.init""
IL_0019: ret
}
");
}
}
private static ImmutableArray<Symbol> GetProperties(CSharpCompilation comp, string typeName)
{
return comp.GetMember<NamedTypeSymbol>(typeName).GetMembers().WhereAsArray(m => m.Kind == SymbolKind.Property);
}
[Fact]
public void BaseArguments_01()
{
var src = @"
using System;
record Base
{
public Base(int X, int Y)
{
Console.WriteLine(X);
Console.WriteLine(Y);
}
public Base() {}
}
record C(int X, int Y = 123) : Base(X, Y)
{
int Z = 123;
public static void Main()
{
var c = new C(1, 2);
Console.WriteLine(c.Z);
}
C(int X, int Y, int Z = 124) : this(X, Y) {}
}";
var verifier = CompileAndVerify(src, expectedOutput: @"
1
2
123").VerifyDiagnostics();
verifier.VerifyIL("C..ctor(int, int)", @"
{
// Code size 31 (0x1f)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld ""int C.<X>k__BackingField""
IL_0007: ldarg.0
IL_0008: ldarg.2
IL_0009: stfld ""int C.<Y>k__BackingField""
IL_000e: ldarg.0
IL_000f: ldc.i4.s 123
IL_0011: stfld ""int C.Z""
IL_0016: ldarg.0
IL_0017: ldarg.1
IL_0018: ldarg.2
IL_0019: call ""Base..ctor(int, int)""
IL_001e: ret
}
");
var comp = CreateCompilation(src);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ElementAt(1);
Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString());
var symbol = model.GetSymbolInfo(x).Symbol;
Assert.Equal(SymbolKind.Parameter, symbol!.Kind);
Assert.Equal("System.Int32 X", symbol.ToTestDisplayString());
Assert.Equal("C..ctor(System.Int32 X, [System.Int32 Y = 123])", symbol.ContainingSymbol.ToTestDisplayString());
Assert.Equal(Accessibility.Public, symbol.ContainingSymbol.DeclaredAccessibility);
Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart));
Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X"));
Assert.Contains("X", model.LookupNames(x.SpanStart));
{
var baseWithargs = tree.GetRoot().DescendantNodes().OfType<PrimaryConstructorBaseTypeSyntax>().Single();
Assert.Equal("Base(X, Y)", baseWithargs.ToString());
Assert.Equal("Base", model.GetTypeInfo(baseWithargs.Type).Type.ToTestDisplayString());
Assert.Equal(TypeInfo.None, model.GetTypeInfo(baseWithargs));
Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", model.GetSymbolInfo((SyntaxNode)baseWithargs).Symbol.ToTestDisplayString());
Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", model.GetSymbolInfo(baseWithargs).Symbol.ToTestDisplayString());
Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", CSharpExtensions.GetSymbolInfo(model, baseWithargs).Symbol.ToTestDisplayString());
Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs));
Assert.Empty(model.GetMemberGroup(baseWithargs));
model = comp.GetSemanticModel(tree);
Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", model.GetSymbolInfo((SyntaxNode)baseWithargs).Symbol.ToTestDisplayString());
model = comp.GetSemanticModel(tree);
Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", model.GetSymbolInfo(baseWithargs).Symbol.ToTestDisplayString());
model = comp.GetSemanticModel(tree);
Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", CSharpExtensions.GetSymbolInfo(model, baseWithargs).Symbol.ToTestDisplayString());
model = comp.GetSemanticModel(tree);
Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs));
model = comp.GetSemanticModel(tree);
Assert.Empty(model.GetMemberGroup(baseWithargs));
model = comp.GetSemanticModel(tree);
#nullable disable
var operation = model.GetOperation(baseWithargs);
VerifyOperationTree(comp, operation,
@"
IInvocationOperation ( Base..ctor(System.Int32 X, System.Int32 Y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Base(X, Y)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: 'Base(X, Y)')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X')
IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y')
IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
Assert.Null(model.GetOperation(baseWithargs.Type));
Assert.Null(model.GetOperation(baseWithargs.Parent));
Assert.Same(operation.Parent.Parent, model.GetOperation(baseWithargs.Parent.Parent));
Assert.Equal(SyntaxKind.RecordDeclaration, baseWithargs.Parent.Parent.Kind());
VerifyOperationTree(comp, operation.Parent.Parent,
@"
IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null) (Syntax: 'record C(in ... }')
Initializer:
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'Base(X, Y)')
Expression:
IInvocationOperation ( Base..ctor(System.Int32 X, System.Int32 Y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Base(X, Y)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: 'Base(X, Y)')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X')
IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y')
IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
BlockBody:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'record C(in ... }')
ExpressionBody:
null
");
Assert.Null(operation.Parent.Parent.Parent);
VerifyFlowGraph(comp, operation.Parent.Parent.Syntax, @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'Base(X, Y)')
Expression:
IInvocationOperation ( Base..ctor(System.Int32 X, System.Int32 Y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Base(X, Y)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: 'Base(X, Y)')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X')
IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y')
IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
");
var equalsValue = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().First();
Assert.Equal("= 123", equalsValue.ToString());
model.VerifyOperationTree(equalsValue,
@"
IParameterInitializerOperation (Parameter: [System.Int32 Y = 123]) (OperationKind.ParameterInitializer, Type: null) (Syntax: '= 123')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 123) (Syntax: '123')
");
#nullable enable
}
{
var baseWithargs = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single();
Assert.Equal(": this(X, Y)", baseWithargs.ToString());
Assert.Equal("C..ctor(System.Int32 X, [System.Int32 Y = 123])", model.GetSymbolInfo((SyntaxNode)baseWithargs).Symbol.ToTestDisplayString());
Assert.Equal("C..ctor(System.Int32 X, [System.Int32 Y = 123])", model.GetSymbolInfo(baseWithargs).Symbol.ToTestDisplayString());
Assert.Equal("C..ctor(System.Int32 X, [System.Int32 Y = 123])", CSharpExtensions.GetSymbolInfo(model, baseWithargs).Symbol.ToTestDisplayString());
Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs).Select(m => m.ToTestDisplayString()));
Assert.Empty(model.GetMemberGroup(baseWithargs).Select(m => m.ToTestDisplayString()));
Assert.Empty(CSharpExtensions.GetMemberGroup(model, baseWithargs).Select(m => m.ToTestDisplayString()));
model.VerifyOperationTree(baseWithargs,
@"
IInvocationOperation ( C..ctor(System.Int32 X, [System.Int32 Y = 123])) (OperationKind.Invocation, Type: System.Void) (Syntax: ': this(X, Y)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: ': this(X, Y)')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X')
IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y')
IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
var equalsValue = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Last();
Assert.Equal("= 124", equalsValue.ToString());
model.VerifyOperationTree(equalsValue,
@"
IParameterInitializerOperation (Parameter: [System.Int32 Z = 124]) (OperationKind.ParameterInitializer, Type: null) (Syntax: '= 124')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 124) (Syntax: '124')
");
model.VerifyOperationTree(baseWithargs.Parent,
@"
IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null) (Syntax: 'C(int X, in ... is(X, Y) {}')
Initializer:
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: ': this(X, Y)')
Expression:
IInvocationOperation ( C..ctor(System.Int32 X, [System.Int32 Y = 123])) (OperationKind.Invocation, Type: System.Void) (Syntax: ': this(X, Y)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: ': this(X, Y)')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X')
IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y')
IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
BlockBody:
IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{}')
ExpressionBody:
null
");
}
}
[Fact]
public void BaseArguments_02()
{
var src = @"
using System;
record Base
{
public Base(int X, int Y)
{
Console.WriteLine(X);
Console.WriteLine(Y);
}
public Base() {}
}
record C(int X) : Base(Test(X, out var y), y)
{
public static void Main()
{
var c = new C(1);
}
private static int Test(int x, out int y)
{
y = 2;
return x;
}
}";
var verifier = CompileAndVerify(src, expectedOutput: @"
1
2").VerifyDiagnostics();
var comp = CreateCompilation(src);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var yDecl = OutVarTests.GetOutVarDeclaration(tree, "y");
var yRef = OutVarTests.GetReferences(tree, "y").ToArray();
Assert.Equal(2, yRef.Length);
OutVarTests.VerifyModelForOutVar(model, yDecl, yRef[0]);
OutVarTests.VerifyNotAnOutLocal(model, yRef[1]);
var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ElementAt(1);
Assert.Equal("Test(X, out var y)", x.Parent!.Parent!.Parent!.ToString());
var symbol = model.GetSymbolInfo(x).Symbol;
Assert.Equal(SymbolKind.Parameter, symbol!.Kind);
Assert.Equal("System.Int32 X", symbol.ToTestDisplayString());
Assert.Equal("C..ctor(System.Int32 X)", symbol.ContainingSymbol.ToTestDisplayString());
Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart));
Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X"));
Assert.Contains("X", model.LookupNames(x.SpanStart));
var y = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "y").First();
Assert.Equal("y", y.Parent!.ToString());
Assert.Equal("(Test(X, out var y), y)", y.Parent!.Parent!.ToString());
Assert.Equal("Base(Test(X, out var y), y)", y.Parent!.Parent!.Parent!.ToString());
symbol = model.GetSymbolInfo(y).Symbol;
Assert.Equal(SymbolKind.Local, symbol!.Kind);
Assert.Equal("System.Int32 y", symbol.ToTestDisplayString());
Assert.Equal("C..ctor(System.Int32 X)", symbol.ContainingSymbol.ToTestDisplayString());
Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart));
Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "y"));
Assert.Contains("y", model.LookupNames(x.SpanStart));
var test = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test").First();
Assert.Equal("(Test(X, out var y), y)", test.Parent!.Parent!.Parent!.ToString());
symbol = model.GetSymbolInfo(test).Symbol;
Assert.Equal(SymbolKind.Method, symbol!.Kind);
Assert.Equal("System.Int32 C.Test(System.Int32 x, out System.Int32 y)", symbol.ToTestDisplayString());
Assert.Equal("C", symbol.ContainingSymbol.ToTestDisplayString());
Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "Test"));
Assert.Contains("Test", model.LookupNames(x.SpanStart));
}
[Fact]
public void BaseArguments_03()
{
var src = @"
using System;
record Base
{
public Base(int X, int Y)
{
}
public Base() {}
}
record C : Base(X, Y)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (13,16): error CS8861: Unexpected argument list.
// record C : Base(X, Y)
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(13, 16)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First();
Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString());
var symbolInfo = model.GetSymbolInfo(x);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString());
Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X"));
Assert.DoesNotContain("X", model.LookupNames(x.SpanStart));
}
[Fact]
public void BaseArguments_04()
{
var src = @"
using System;
record Base
{
public Base(int X, int Y)
{
}
public Base() {}
}
partial record C(int X, int Y)
{
}
partial record C : Base(X, Y)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (17,24): error CS8861: Unexpected argument list.
// partial record C : Base(X, Y)
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(17, 24)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First();
Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString());
var symbolInfo = model.GetSymbolInfo(x);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString());
Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X"));
Assert.DoesNotContain("X", model.LookupNames(x.SpanStart));
var recordDeclarations = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Skip(1).ToArray();
Assert.Equal("C", recordDeclarations[0].Identifier.ValueText);
Assert.Null(model.GetOperation(recordDeclarations[0]));
Assert.Equal("C", recordDeclarations[1].Identifier.ValueText);
Assert.Null(model.GetOperation(recordDeclarations[1]));
}
[Fact]
public void BaseArguments_05()
{
var src = @"
using System;
record Base
{
public Base(int X, int Y)
{
}
public Base() {}
}
partial record C : Base(X, Y)
{
}
partial record C : Base(X, Y)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (13,24): error CS8861: Unexpected argument list.
// partial record C : Base(X, Y)
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(13, 24),
// (17,24): error CS8861: Unexpected argument list.
// partial record C : Base(X, Y)
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(17, 24)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var xs = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ToArray();
Assert.Equal(2, xs.Length);
foreach (var x in xs)
{
Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString());
var symbolInfo = model.GetSymbolInfo(x);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString());
Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X"));
Assert.DoesNotContain("X", model.LookupNames(x.SpanStart));
}
var recordDeclarations = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Skip(1).ToArray();
Assert.Equal("C", recordDeclarations[0].Identifier.ValueText);
Assert.Null(model.GetOperation(recordDeclarations[0]));
Assert.Equal("C", recordDeclarations[1].Identifier.ValueText);
Assert.Null(model.GetOperation(recordDeclarations[1]));
}
[Fact]
public void BaseArguments_06()
{
var src = @"
using System;
record Base
{
public Base(int X, int Y)
{
}
public Base() {}
}
partial record C(int X, int Y) : Base(X, Y)
{
}
partial record C : Base(X, Y)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (17,24): error CS8861: Unexpected argument list.
// partial record C : Base(X, Y)
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(17, 24)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var xs = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ToArray();
Assert.Equal(2, xs.Length);
var x = xs[0];
Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString());
var symbol = model.GetSymbolInfo(x).Symbol;
Assert.Equal(SymbolKind.Parameter, symbol!.Kind);
Assert.Equal("System.Int32 X", symbol.ToTestDisplayString());
Assert.Equal("C..ctor(System.Int32 X, System.Int32 Y)", symbol.ContainingSymbol.ToTestDisplayString());
Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart));
Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X"));
Assert.Contains("X", model.LookupNames(x.SpanStart));
x = xs[1];
Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString());
var symbolInfo = model.GetSymbolInfo(x);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString());
Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X"));
Assert.DoesNotContain("X", model.LookupNames(x.SpanStart));
var recordDeclarations = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Skip(1).ToArray();
Assert.Equal("C", recordDeclarations[0].Identifier.ValueText);
model.VerifyOperationTree(recordDeclarations[0],
@"
IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null) (Syntax: 'partial rec ... }')
Initializer:
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'Base(X, Y)')
Expression:
IInvocationOperation ( Base..ctor(System.Int32 X, System.Int32 Y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Base(X, Y)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: 'Base(X, Y)')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X')
IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y')
IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
BlockBody:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'partial rec ... }')
ExpressionBody:
null
");
Assert.Equal("C", recordDeclarations[1].Identifier.ValueText);
Assert.Null(model.GetOperation(recordDeclarations[1]));
}
[Fact]
public void BaseArguments_07()
{
var src = @"
using System;
record Base
{
public Base(int X, int Y)
{
}
public Base() {}
}
partial record C : Base(X, Y)
{
}
partial record C(int X, int Y) : Base(X, Y)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (13,24): error CS8861: Unexpected argument list.
// partial record C : Base(X, Y)
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(13, 24)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var xs = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ToArray();
Assert.Equal(2, xs.Length);
var x = xs[1];
Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString());
var symbol = model.GetSymbolInfo(x).Symbol;
Assert.Equal(SymbolKind.Parameter, symbol!.Kind);
Assert.Equal("System.Int32 X", symbol.ToTestDisplayString());
Assert.Equal("C..ctor(System.Int32 X, System.Int32 Y)", symbol.ContainingSymbol.ToTestDisplayString());
Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart));
Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X"));
Assert.Contains("X", model.LookupNames(x.SpanStart));
x = xs[0];
Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString());
var symbolInfo = model.GetSymbolInfo(x);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString());
Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X"));
Assert.DoesNotContain("X", model.LookupNames(x.SpanStart));
var recordDeclarations = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Skip(1).ToArray();
Assert.Equal("C", recordDeclarations[0].Identifier.ValueText);
Assert.Null(model.GetOperation(recordDeclarations[0]));
Assert.Equal("C", recordDeclarations[1].Identifier.ValueText);
model.VerifyOperationTree(recordDeclarations[1],
@"
IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null) (Syntax: 'partial rec ... }')
Initializer:
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'Base(X, Y)')
Expression:
IInvocationOperation ( Base..ctor(System.Int32 X, System.Int32 Y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Base(X, Y)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: 'Base(X, Y)')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X')
IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y')
IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
BlockBody:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'partial rec ... }')
ExpressionBody:
null
");
}
[Fact]
public void BaseArguments_08()
{
var src = @"
record Base
{
public Base(int Y)
{
}
public Base() {}
}
record C(int X) : Base(Y)
{
public int Y = 0;
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (11,24): error CS0120: An object reference is required for the non-static field, method, or property 'C.Y'
// record C(int X) : Base(Y)
Diagnostic(ErrorCode.ERR_ObjectRequired, "Y").WithArguments("C.Y").WithLocation(11, 24)
);
}
[Fact]
public void BaseArguments_09()
{
var src = @"
record Base
{
public Base(int X)
{
}
public Base() {}
}
record C(int X) : Base(this.X)
{
public int Y = 0;
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (11,24): error CS0027: Keyword 'this' is not available in the current context
// record C(int X) : Base(this.X)
Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(11, 24)
);
}
[Fact]
public void BaseArguments_10()
{
var src = @"
record Base
{
public Base(int X)
{
}
public Base() {}
}
record C(dynamic X) : Base(X)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (11,27): error CS1975: The constructor call needs to be dynamically dispatched, but cannot be because it is part of a constructor initializer. Consider casting the dynamic arguments.
// record C(dynamic X) : Base(X)
Diagnostic(ErrorCode.ERR_NoDynamicPhantomOnBaseCtor, "(X)").WithLocation(11, 27)
);
}
[Fact]
public void BaseArguments_11()
{
var src = @"
record Base
{
public Base(int X, int Y)
{
}
public Base() {}
}
record C(int X) : Base(Test(X, out var y), y)
{
int Z = y;
private static int Test(int x, out int y)
{
y = 2;
return x;
}
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (13,13): error CS0103: The name 'y' does not exist in the current context
// int Z = y;
Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(13, 13)
);
}
[Fact]
public void BaseArguments_12()
{
var src = @"
using System;
class Base
{
public Base(int X)
{
}
}
class C : Base(X)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (11,7): error CS7036: There is no argument given that corresponds to the required formal parameter 'X' of 'Base.Base(int)'
// class C : Base(X)
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("X", "Base.Base(int)").WithLocation(11, 7),
// (11,15): error CS8861: Unexpected argument list.
// class C : Base(X)
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(11, 15)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First();
Assert.Equal("Base(X)", x.Parent!.Parent!.Parent!.ToString());
var symbolInfo = model.GetSymbolInfo(x);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString());
Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X"));
Assert.DoesNotContain("X", model.LookupNames(x.SpanStart));
}
[Fact]
public void BaseArguments_13()
{
var src = @"
using System;
interface Base
{
}
struct C : Base(X)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (8,16): error CS8861: Unexpected argument list.
// struct C : Base(X)
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(8, 16)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First();
Assert.Equal("Base(X)", x.Parent!.Parent!.Parent!.ToString());
var symbolInfo = model.GetSymbolInfo(x);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString());
Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X"));
Assert.DoesNotContain("X", model.LookupNames(x.SpanStart));
}
[Fact]
public void BaseArguments_14()
{
var src = @"
using System;
interface Base
{
}
interface C : Base(X)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (8,19): error CS8861: Unexpected argument list.
// interface C : Base(X)
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(8, 19)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First();
Assert.Equal("Base(X)", x.Parent!.Parent!.Parent!.ToString());
var symbolInfo = model.GetSymbolInfo(x);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString());
Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X"));
Assert.DoesNotContain("X", model.LookupNames(x.SpanStart));
}
[Fact]
public void BaseArguments_15()
{
var src = @"
using System;
record Base
{
public Base(int X, int Y)
{
Console.WriteLine(X);
Console.WriteLine(Y);
}
public Base() {}
}
partial record C
{
}
partial record C(int X, int Y) : Base(X, Y)
{
int Z = 123;
public static void Main()
{
var c = new C(1, 2);
Console.WriteLine(c.Z);
}
}
partial record C
{
}
";
var verifier = CompileAndVerify(src, expectedOutput: @"
1
2
123").VerifyDiagnostics();
verifier.VerifyIL("C..ctor(int, int)", @"
{
// Code size 31 (0x1f)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld ""int C.<X>k__BackingField""
IL_0007: ldarg.0
IL_0008: ldarg.2
IL_0009: stfld ""int C.<Y>k__BackingField""
IL_000e: ldarg.0
IL_000f: ldc.i4.s 123
IL_0011: stfld ""int C.Z""
IL_0016: ldarg.0
IL_0017: ldarg.1
IL_0018: ldarg.2
IL_0019: call ""Base..ctor(int, int)""
IL_001e: ret
}
");
var comp = CreateCompilation(src);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ElementAt(1);
Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString());
var symbol = model.GetSymbolInfo(x).Symbol;
Assert.Equal(SymbolKind.Parameter, symbol!.Kind);
Assert.Equal("System.Int32 X", symbol.ToTestDisplayString());
Assert.Equal("C..ctor(System.Int32 X, System.Int32 Y)", symbol.ContainingSymbol.ToTestDisplayString());
Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart));
Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X"));
Assert.Contains("X", model.LookupNames(x.SpanStart));
}
[Fact]
public void BaseArguments_16()
{
var src = @"
using System;
record Base
{
public Base(Func<int> X)
{
Console.WriteLine(X());
}
public Base() {}
}
record C(int X) : Base(() => X)
{
public static void Main()
{
var c = new C(1);
}
}";
var verifier = CompileAndVerify(src, expectedOutput: @"1").VerifyDiagnostics();
}
[Fact]
public void BaseArguments_17()
{
var src = @"
record Base
{
public Base(int X, int Y)
{
}
public Base() {}
}
record C(int X, int y)
: Base(Test(X, out var y),
Test(X, out var z))
{
int Z = z;
private static int Test(int x, out int y)
{
y = 2;
return x;
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (12,28): error CS0136: A local or parameter named 'y' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// : Base(Test(X, out var y),
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y").WithArguments("y").WithLocation(12, 28),
// (15,13): error CS0103: The name 'z' does not exist in the current context
// int Z = z;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z").WithArguments("z").WithLocation(15, 13)
);
}
[Fact]
public void BaseArguments_18()
{
var src = @"
record Base
{
public Base(int X, int Y)
{
}
public Base() {}
}
record C(int X, int y)
: Base(Test(X + 1, out var z),
Test(X + 2, out var z))
{
private static int Test(int x, out int y)
{
y = 2;
return x;
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (13,32): error CS0128: A local variable or function named 'z' is already defined in this scope
// Test(X + 2, out var z))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "z").WithArguments("z").WithLocation(13, 32)
);
}
[Fact]
public void BaseArguments_19()
{
var src = @"
record Base
{
public Base(int X)
{
}
public Base() {}
}
record C(int X, int Y) : Base(GetInt(X, out var xx) + xx, Y), I
{
C(int X, int Y, int Z) : this(X, Y, Z, 1) { return; }
static int GetInt(int x1, out int x2)
{
throw null;
}
}
interface I {}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (11,30): error CS1729: 'Base' does not contain a constructor that takes 2 arguments
// record C(int X, int Y) : Base(GetInt(X, out var xx) + xx, Y)
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(GetInt(X, out var xx) + xx, Y)").WithArguments("Base", "2").WithLocation(11, 30),
// (13,30): error CS1729: 'C' does not contain a constructor that takes 4 arguments
// C(int X, int Y, int Z) : this(X, Y, Z, 1) {}
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "this").WithArguments("C", "4").WithLocation(13, 30)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
SymbolInfo symbolInfo;
PrimaryConstructorBaseTypeSyntax speculativePrimaryInitializer;
ConstructorInitializerSyntax speculativeBaseInitializer;
{
var baseWithargs = tree.GetRoot().DescendantNodes().OfType<PrimaryConstructorBaseTypeSyntax>().Single();
Assert.Equal("Base(GetInt(X, out var xx) + xx, Y)", baseWithargs.ToString());
Assert.Equal("Base", model.GetTypeInfo(baseWithargs.Type).Type.ToTestDisplayString());
Assert.Equal(TypeInfo.None, model.GetTypeInfo(baseWithargs));
symbolInfo = model.GetSymbolInfo((SyntaxNode)baseWithargs);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason);
string[] candidates = new[] { "Base..ctor(Base original)", "Base..ctor(System.Int32 X)", "Base..ctor()" };
Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString()));
symbolInfo = model.GetSymbolInfo(baseWithargs);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason);
Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString()));
symbolInfo = CSharpExtensions.GetSymbolInfo(model, baseWithargs);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason);
Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString()));
Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs));
Assert.Empty(model.GetMemberGroup(baseWithargs));
model = comp.GetSemanticModel(tree);
symbolInfo = model.GetSymbolInfo((SyntaxNode)baseWithargs);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason);
Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString()));
model = comp.GetSemanticModel(tree);
symbolInfo = model.GetSymbolInfo(baseWithargs);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason);
Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString()));
model = comp.GetSemanticModel(tree);
symbolInfo = CSharpExtensions.GetSymbolInfo(model, baseWithargs);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason);
Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString()));
model = comp.GetSemanticModel(tree);
Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs));
model = comp.GetSemanticModel(tree);
Assert.Empty(model.GetMemberGroup(baseWithargs));
model = comp.GetSemanticModel(tree);
SemanticModel speculativeModel;
speculativePrimaryInitializer = baseWithargs.WithArgumentList(baseWithargs.ArgumentList.WithArguments(baseWithargs.ArgumentList.Arguments.RemoveAt(1)));
speculativeBaseInitializer = SyntaxFactory.ConstructorInitializer(SyntaxKind.BaseConstructorInitializer, speculativePrimaryInitializer.ArgumentList);
Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer, out _));
symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativeBaseInitializer, SpeculativeBindingOption.BindAsExpression);
Assert.Equal(SymbolInfo.None, symbolInfo);
symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer);
Assert.Equal(SymbolInfo.None, symbolInfo);
Assert.False(model.TryGetSpeculativeSemanticModel(tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single().SpanStart,
speculativeBaseInitializer, out _));
var otherBasePosition = ((BaseListSyntax)baseWithargs.Parent!).Types[1].SpanStart;
Assert.False(model.TryGetSpeculativeSemanticModel(otherBasePosition, speculativePrimaryInitializer, out _));
Assert.True(model.TryGetSpeculativeSemanticModel(baseWithargs.SpanStart, speculativePrimaryInitializer, out speculativeModel!));
Assert.Equal("Base..ctor(System.Int32 X)", speculativeModel!.GetSymbolInfo((SyntaxNode)speculativePrimaryInitializer).Symbol.ToTestDisplayString());
Assert.Equal("Base..ctor(System.Int32 X)", speculativeModel.GetSymbolInfo(speculativePrimaryInitializer).Symbol.ToTestDisplayString());
Assert.Equal("Base..ctor(System.Int32 X)", CSharpExtensions.GetSymbolInfo(speculativeModel, speculativePrimaryInitializer).Symbol.ToTestDisplayString());
Assert.True(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer, out speculativeModel!));
var xxDecl = OutVarTests.GetOutVarDeclaration(speculativePrimaryInitializer.SyntaxTree, "xx");
var xxRef = OutVarTests.GetReferences(speculativePrimaryInitializer.SyntaxTree, "xx").ToArray();
Assert.Equal(1, xxRef.Length);
OutVarTests.VerifyModelForOutVar(speculativeModel, xxDecl, xxRef);
Assert.Equal("Base..ctor(System.Int32 X)", speculativeModel!.GetSymbolInfo((SyntaxNode)speculativePrimaryInitializer).Symbol.ToTestDisplayString());
Assert.Equal("Base..ctor(System.Int32 X)", speculativeModel.GetSymbolInfo(speculativePrimaryInitializer).Symbol.ToTestDisplayString());
Assert.Equal("Base..ctor(System.Int32 X)", CSharpExtensions.GetSymbolInfo(speculativeModel, speculativePrimaryInitializer).Symbol.ToTestDisplayString());
Assert.Throws<ArgumentNullException>(() => model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (PrimaryConstructorBaseTypeSyntax)null!, out _));
Assert.Throws<ArgumentException>(() => model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, baseWithargs, out _));
symbolInfo = model.GetSpeculativeSymbolInfo(otherBasePosition, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression);
Assert.Equal(SymbolInfo.None, symbolInfo);
symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, otherBasePosition, speculativePrimaryInitializer);
Assert.Equal(SymbolInfo.None, symbolInfo);
symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression);
Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString());
symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.SpanStart, speculativePrimaryInitializer);
Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString());
symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression);
Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString());
symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer);
Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression));
Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single().ArgumentList.OpenParenToken.SpanStart,
(SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression));
}
{
var baseWithargs = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single();
Assert.Equal(": this(X, Y, Z, 1)", baseWithargs.ToString());
symbolInfo = model.GetSymbolInfo((SyntaxNode)baseWithargs);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason);
string[] candidates = new[] { "C..ctor(System.Int32 X, System.Int32 Y)", "C..ctor(C original)", "C..ctor(System.Int32 X, System.Int32 Y, System.Int32 Z)" };
Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString()));
symbolInfo = model.GetSymbolInfo(baseWithargs);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason);
Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString()));
symbolInfo = CSharpExtensions.GetSymbolInfo(model, baseWithargs);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason);
Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString()));
Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs).Select(m => m.ToTestDisplayString()));
Assert.Empty(model.GetMemberGroup(baseWithargs).Select(m => m.ToTestDisplayString()));
Assert.Empty(CSharpExtensions.GetMemberGroup(model, baseWithargs).Select(m => m.ToTestDisplayString()));
Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer, out _));
symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer);
Assert.Equal(SymbolInfo.None, symbolInfo);
symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativeBaseInitializer, SpeculativeBindingOption.BindAsExpression);
Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString());
symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer);
Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression));
}
}
[Fact]
public void BaseArguments_20()
{
var src = @"
class Base
{
public Base(int X)
{
}
public Base() {}
}
class C : Base(GetInt(X, out var xx) + xx, Y), I
{
C(int X, int Y, int Z) : base(X, Y, Z, 1) { return; }
static int GetInt(int x1, out int x2)
{
throw null;
}
}
interface I {}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (11,15): error CS8861: Unexpected argument list.
// class C : Base(GetInt(X, out var xx) + xx, Y), I
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(GetInt(X, out var xx) + xx, Y)").WithLocation(11, 15),
// (13,30): error CS1729: 'Base' does not contain a constructor that takes 4 arguments
// C(int X, int Y, int Z) : base(X, Y, Z, 1) { return; }
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "base").WithArguments("Base", "4").WithLocation(13, 30)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
SymbolInfo symbolInfo;
PrimaryConstructorBaseTypeSyntax speculativePrimaryInitializer;
ConstructorInitializerSyntax speculativeBaseInitializer;
{
var baseWithargs = tree.GetRoot().DescendantNodes().OfType<PrimaryConstructorBaseTypeSyntax>().Single();
Assert.Equal("Base(GetInt(X, out var xx) + xx, Y)", baseWithargs.ToString());
Assert.Equal("Base", model.GetTypeInfo(baseWithargs.Type).Type.ToTestDisplayString());
Assert.Equal(TypeInfo.None, model.GetTypeInfo(baseWithargs));
symbolInfo = model.GetSymbolInfo((SyntaxNode)baseWithargs);
Assert.Equal(SymbolInfo.None, symbolInfo);
symbolInfo = model.GetSymbolInfo(baseWithargs);
Assert.Equal(SymbolInfo.None, symbolInfo);
symbolInfo = CSharpExtensions.GetSymbolInfo(model, baseWithargs);
Assert.Equal(SymbolInfo.None, symbolInfo);
Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs));
Assert.Empty(model.GetMemberGroup(baseWithargs));
speculativePrimaryInitializer = baseWithargs.WithArgumentList(baseWithargs.ArgumentList.WithArguments(baseWithargs.ArgumentList.Arguments.RemoveAt(1)));
speculativeBaseInitializer = SyntaxFactory.ConstructorInitializer(SyntaxKind.BaseConstructorInitializer, speculativePrimaryInitializer.ArgumentList);
Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer, out _));
symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativeBaseInitializer, SpeculativeBindingOption.BindAsExpression);
Assert.Equal(SymbolInfo.None, symbolInfo);
symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer);
Assert.Equal(SymbolInfo.None, symbolInfo);
Assert.False(model.TryGetSpeculativeSemanticModel(tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single().SpanStart,
speculativeBaseInitializer, out _));
var otherBasePosition = ((BaseListSyntax)baseWithargs.Parent!).Types[1].SpanStart;
Assert.False(model.TryGetSpeculativeSemanticModel(otherBasePosition, speculativePrimaryInitializer, out _));
Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.SpanStart, speculativePrimaryInitializer, out _));
Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer, out _));
Assert.Throws<ArgumentNullException>(() => model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (PrimaryConstructorBaseTypeSyntax)null!, out _));
Assert.Throws<ArgumentException>(() => model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, baseWithargs, out _));
symbolInfo = model.GetSpeculativeSymbolInfo(otherBasePosition, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression);
Assert.Equal(SymbolInfo.None, symbolInfo);
symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, otherBasePosition, speculativePrimaryInitializer);
Assert.Equal(SymbolInfo.None, symbolInfo);
symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression);
Assert.Equal(SymbolInfo.None, symbolInfo);
symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.SpanStart, speculativePrimaryInitializer);
Assert.Equal(SymbolInfo.None, symbolInfo);
symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression);
Assert.Equal(SymbolInfo.None, symbolInfo);
symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer);
Assert.Equal(SymbolInfo.None, symbolInfo);
Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression));
Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single().ArgumentList.OpenParenToken.SpanStart,
(SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression));
}
{
var baseWithargs = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single();
Assert.Equal(": base(X, Y, Z, 1)", baseWithargs.ToString());
symbolInfo = model.GetSymbolInfo((SyntaxNode)baseWithargs);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason);
string[] candidates = new[] { "Base..ctor(System.Int32 X)", "Base..ctor()" };
Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString()));
symbolInfo = model.GetSymbolInfo(baseWithargs);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason);
Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString()));
symbolInfo = CSharpExtensions.GetSymbolInfo(model, baseWithargs);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason);
Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString()));
Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs).Select(m => m.ToTestDisplayString()));
Assert.Empty(model.GetMemberGroup(baseWithargs).Select(m => m.ToTestDisplayString()));
Assert.Empty(CSharpExtensions.GetMemberGroup(model, baseWithargs).Select(m => m.ToTestDisplayString()));
Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer, out _));
symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer);
Assert.Equal(SymbolInfo.None, symbolInfo);
symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativeBaseInitializer, SpeculativeBindingOption.BindAsExpression);
Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString());
symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer);
Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression));
}
}
[Fact]
public void Equality_02()
{
var source =
@"using static System.Console;
record C;
class Program
{
static void Main()
{
var x = new C();
var y = new C();
WriteLine(x.Equals(y) && x.GetHashCode() == y.GetHashCode());
WriteLine(((object)x).Equals(y));
WriteLine(((System.IEquatable<C>)x).Equals(y));
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
var ordinaryMethods = comp.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind == MethodKind.Ordinary).ToArray();
Assert.Equal(6, ordinaryMethods.Length);
foreach (var m in ordinaryMethods)
{
Assert.True(m.IsImplicitlyDeclared);
}
var verifier = CompileAndVerify(comp, expectedOutput:
@"True
True
True").VerifyDiagnostics();
verifier.VerifyIL("C.Equals(C)",
@"{
// Code size 29 (0x1d)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_001b
IL_0004: ldarg.1
IL_0005: brfalse.s IL_0019
IL_0007: ldarg.0
IL_0008: callvirt ""System.Type C.EqualityContract.get""
IL_000d: ldarg.1
IL_000e: callvirt ""System.Type C.EqualityContract.get""
IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)""
IL_0018: ret
IL_0019: ldc.i4.0
IL_001a: ret
IL_001b: ldc.i4.1
IL_001c: ret
}");
verifier.VerifyIL("C.Equals(object)",
@"{
// Code size 13 (0xd)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: isinst ""C""
IL_0007: callvirt ""bool C.Equals(C)""
IL_000c: ret
}");
verifier.VerifyIL("C.GetHashCode()",
@"{
// Code size 17 (0x11)
.maxstack 2
IL_0000: call ""System.Collections.Generic.EqualityComparer<System.Type> System.Collections.Generic.EqualityComparer<System.Type>.Default.get""
IL_0005: ldarg.0
IL_0006: callvirt ""System.Type C.EqualityContract.get""
IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<System.Type>.GetHashCode(System.Type)""
IL_0010: ret
}");
}
[Fact]
public void Equality_03()
{
var source =
@"using static System.Console;
record C
{
private static int _nextId = 0;
private int _id;
public C() { _id = _nextId++; }
}
class Program
{
static void Main()
{
var x = new C();
var y = new C();
WriteLine(x.Equals(x));
WriteLine(x.Equals(y));
WriteLine(y.Equals(y));
}
}";
var verifier = CompileAndVerify(source, expectedOutput:
@"True
False
True").VerifyDiagnostics();
verifier.VerifyIL("C.Equals(C)",
@"{
// Code size 53 (0x35)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_0033
IL_0004: ldarg.1
IL_0005: brfalse.s IL_0031
IL_0007: ldarg.0
IL_0008: callvirt ""System.Type C.EqualityContract.get""
IL_000d: ldarg.1
IL_000e: callvirt ""System.Type C.EqualityContract.get""
IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)""
IL_0018: brfalse.s IL_0031
IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get""
IL_001f: ldarg.0
IL_0020: ldfld ""int C._id""
IL_0025: ldarg.1
IL_0026: ldfld ""int C._id""
IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)""
IL_0030: ret
IL_0031: ldc.i4.0
IL_0032: ret
IL_0033: ldc.i4.1
IL_0034: ret
}");
verifier.VerifyIL("C.GetHashCode()",
@"{
// Code size 40 (0x28)
.maxstack 3
IL_0000: call ""System.Collections.Generic.EqualityComparer<System.Type> System.Collections.Generic.EqualityComparer<System.Type>.Default.get""
IL_0005: ldarg.0
IL_0006: callvirt ""System.Type C.EqualityContract.get""
IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<System.Type>.GetHashCode(System.Type)""
IL_0010: ldc.i4 0xa5555529
IL_0015: mul
IL_0016: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get""
IL_001b: ldarg.0
IL_001c: ldfld ""int C._id""
IL_0021: callvirt ""int System.Collections.Generic.EqualityComparer<int>.GetHashCode(int)""
IL_0026: add
IL_0027: ret
}");
var clone = ((CSharpCompilation)verifier.Compilation).GetMember<MethodSymbol>("C." + WellKnownMemberNames.CloneMethodName);
Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility);
Assert.False(clone.IsOverride);
Assert.True(clone.IsVirtual);
Assert.False(clone.IsAbstract);
Assert.False(clone.IsSealed);
Assert.True(clone.IsImplicitlyDeclared);
}
[Fact]
public void Equality_04()
{
var source =
@"using static System.Console;
record A;
record B1(int P) : A
{
internal B1() : this(0) { } // Use record base call syntax instead
internal int P { get; set; } // Use record base call syntax instead
}
record B2(int P) : A
{
internal B2() : this(0) { } // Use record base call syntax instead
internal int P { get; set; } // Use record base call syntax instead
}
class Program
{
static B1 NewB1(int p) => new B1 { P = p }; // Use record base call syntax instead
static B2 NewB2(int p) => new B2 { P = p }; // Use record base call syntax instead
static void Main()
{
WriteLine(new A().Equals(NewB1(1)));
WriteLine(NewB1(1).Equals(new A()));
WriteLine(NewB1(1).Equals(NewB2(1)));
WriteLine(new A().Equals((A)NewB2(1)));
WriteLine(((A)NewB2(1)).Equals(new A()));
WriteLine(((A)NewB2(1)).Equals(NewB2(1)) && ((A)NewB2(1)).GetHashCode() == NewB2(1).GetHashCode());
WriteLine(NewB2(1).Equals((A)NewB2(1)));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
var verifier = CompileAndVerify(comp, expectedOutput:
@"False
False
False
False
False
True
True").VerifyDiagnostics(
// (3,15): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name?
// record B1(int P) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(3, 15),
// (8,15): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name?
// record B2(int P) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(8, 15)
);
verifier.VerifyIL("A.Equals(A)",
@"{
// Code size 29 (0x1d)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_001b
IL_0004: ldarg.1
IL_0005: brfalse.s IL_0019
IL_0007: ldarg.0
IL_0008: callvirt ""System.Type A.EqualityContract.get""
IL_000d: ldarg.1
IL_000e: callvirt ""System.Type A.EqualityContract.get""
IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)""
IL_0018: ret
IL_0019: ldc.i4.0
IL_001a: ret
IL_001b: ldc.i4.1
IL_001c: ret
}");
verifier.VerifyIL("B1.Equals(B1)",
@"{
// Code size 40 (0x28)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_0026
IL_0004: ldarg.0
IL_0005: ldarg.1
IL_0006: call ""bool A.Equals(A)""
IL_000b: brfalse.s IL_0024
IL_000d: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get""
IL_0012: ldarg.0
IL_0013: ldfld ""int B1.<P>k__BackingField""
IL_0018: ldarg.1
IL_0019: ldfld ""int B1.<P>k__BackingField""
IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)""
IL_0023: ret
IL_0024: ldc.i4.0
IL_0025: ret
IL_0026: ldc.i4.1
IL_0027: ret
}");
verifier.VerifyIL("B1.GetHashCode()",
@"{
// Code size 30 (0x1e)
.maxstack 3
IL_0000: ldarg.0
IL_0001: call ""int A.GetHashCode()""
IL_0006: ldc.i4 0xa5555529
IL_000b: mul
IL_000c: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get""
IL_0011: ldarg.0
IL_0012: ldfld ""int B1.<P>k__BackingField""
IL_0017: callvirt ""int System.Collections.Generic.EqualityComparer<int>.GetHashCode(int)""
IL_001c: add
IL_001d: ret
}");
}
[Fact]
public void Equality_05()
{
var source =
@"using static System.Console;
record A(int P)
{
internal A() : this(0) { } // Use record base call syntax instead
internal int P { get; set; } // Use record base call syntax instead
}
record B1(int P) : A
{
internal B1() : this(0) { } // Use record base call syntax instead
}
record B2(int P) : A
{
internal B2() : this(0) { } // Use record base call syntax instead
}
class Program
{
static A NewA(int p) => new A { P = p }; // Use record base call syntax instead
static B1 NewB1(int p) => new B1 { P = p }; // Use record base call syntax instead
static B2 NewB2(int p) => new B2 { P = p }; // Use record base call syntax instead
static void Main()
{
WriteLine(NewA(1).Equals(NewA(2)));
WriteLine(NewA(1).Equals(NewA(1)) && NewA(1).GetHashCode() == NewA(1).GetHashCode());
WriteLine(NewA(1).Equals(NewB1(1)));
WriteLine(NewB1(1).Equals(NewA(1)));
WriteLine(NewB1(1).Equals(NewB2(1)));
WriteLine(NewA(1).Equals((A)NewB2(1)));
WriteLine(((A)NewB2(1)).Equals(NewA(1)));
WriteLine(((A)NewB2(1)).Equals(NewB2(1)));
WriteLine(NewB2(1).Equals((A)NewB2(1)));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
var verifier = CompileAndVerify(comp, expectedOutput:
@"False
True
False
False
False
False
False
True
True").VerifyDiagnostics(
// (2,14): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name?
// record A(int P)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 14),
// (7,15): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name?
// record B1(int P) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(7, 15),
// (11,15): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name?
// record B2(int P) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(11, 15)
);
verifier.VerifyIL("A.Equals(A)",
@"{
// Code size 53 (0x35)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_0033
IL_0004: ldarg.1
IL_0005: brfalse.s IL_0031
IL_0007: ldarg.0
IL_0008: callvirt ""System.Type A.EqualityContract.get""
IL_000d: ldarg.1
IL_000e: callvirt ""System.Type A.EqualityContract.get""
IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)""
IL_0018: brfalse.s IL_0031
IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get""
IL_001f: ldarg.0
IL_0020: ldfld ""int A.<P>k__BackingField""
IL_0025: ldarg.1
IL_0026: ldfld ""int A.<P>k__BackingField""
IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)""
IL_0030: ret
IL_0031: ldc.i4.0
IL_0032: ret
IL_0033: ldc.i4.1
IL_0034: ret
}");
verifier.VerifyIL("B1.Equals(B1)",
@"{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_000c
IL_0004: ldarg.0
IL_0005: ldarg.1
IL_0006: call ""bool A.Equals(A)""
IL_000b: ret
IL_000c: ldc.i4.1
IL_000d: ret
}");
verifier.VerifyIL("B1.GetHashCode()",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""int A.GetHashCode()""
IL_0006: ret
}");
}
[Fact]
public void Equality_06()
{
var source =
@"
using System;
using static System.Console;
record A;
record B : A
{
protected override Type EqualityContract => typeof(A);
public virtual bool Equals(B b) => base.Equals((A)b);
}
record C : B;
class Program
{
static void Main()
{
WriteLine(new A().Equals(new A()));
WriteLine(new A().Equals(new B()));
WriteLine(new A().Equals(new C()));
WriteLine(new B().Equals(new A()));
WriteLine(new B().Equals(new B()));
WriteLine(new B().Equals(new C()));
WriteLine(new C().Equals(new A()));
WriteLine(new C().Equals(new B()));
WriteLine(new C().Equals(new C()));
WriteLine(((A)new C()).Equals(new A()));
WriteLine(((A)new C()).Equals(new B()));
WriteLine(((A)new C()).Equals(new C()));
WriteLine(new C().Equals((A)new C()));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var recordDeclaration = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().First();
Assert.Null(model.GetOperation(recordDeclaration));
var verifier = CompileAndVerify(comp, expectedOutput:
@"True
True
False
False
True
False
False
False
True
False
False
True
True").VerifyDiagnostics(
// (8,25): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode'
// public virtual bool Equals(B b) => base.Equals((A)b);
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(8, 25)
);
verifier.VerifyIL("A.Equals(A)",
@"{
// Code size 29 (0x1d)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_001b
IL_0004: ldarg.1
IL_0005: brfalse.s IL_0019
IL_0007: ldarg.0
IL_0008: callvirt ""System.Type A.EqualityContract.get""
IL_000d: ldarg.1
IL_000e: callvirt ""System.Type A.EqualityContract.get""
IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)""
IL_0018: ret
IL_0019: ldc.i4.0
IL_001a: ret
IL_001b: ldc.i4.1
IL_001c: ret
}");
verifier.VerifyIL("C.Equals(C)",
@"{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_000c
IL_0004: ldarg.0
IL_0005: ldarg.1
IL_0006: call ""bool B.Equals(B)""
IL_000b: ret
IL_000c: ldc.i4.1
IL_000d: ret
}");
}
[Fact]
public void Equality_07()
{
var source =
@"using System;
using static System.Console;
record A;
record B : A;
record C : B;
class Program
{
static void Main()
{
WriteLine(new A().Equals(new A()));
WriteLine(new A().Equals(new B()));
WriteLine(new A().Equals(new C()));
WriteLine(new B().Equals(new A()));
WriteLine(new B().Equals(new B()));
WriteLine(new B().Equals(new C()));
WriteLine(new C().Equals(new A()));
WriteLine(new C().Equals(new B()));
WriteLine(new C().Equals(new C()));
WriteLine(((A)new B()).Equals(new A()));
WriteLine(((A)new B()).Equals(new B()));
WriteLine(((A)new B()).Equals(new C()));
WriteLine(((A)new C()).Equals(new A()));
WriteLine(((A)new C()).Equals(new B()));
WriteLine(((A)new C()).Equals(new C()));
WriteLine(((B)new C()).Equals(new A()));
WriteLine(((B)new C()).Equals(new B()));
WriteLine(((B)new C()).Equals(new C()));
WriteLine(new C().Equals((A)new C()));
WriteLine(((IEquatable<A>)new B()).Equals(new A()));
WriteLine(((IEquatable<A>)new B()).Equals(new B()));
WriteLine(((IEquatable<A>)new B()).Equals(new C()));
WriteLine(((IEquatable<A>)new C()).Equals(new A()));
WriteLine(((IEquatable<A>)new C()).Equals(new B()));
WriteLine(((IEquatable<A>)new C()).Equals(new C()));
WriteLine(((IEquatable<B>)new C()).Equals(new A()));
WriteLine(((IEquatable<B>)new C()).Equals(new B()));
WriteLine(((IEquatable<B>)new C()).Equals(new C()));
WriteLine(((IEquatable<C>)new C()).Equals(new C()));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
var verifier = CompileAndVerify(comp, expectedOutput:
@"True
False
False
False
True
False
False
False
True
False
True
False
False
False
True
False
False
True
True
False
True
False
False
False
True
False
False
True
True").VerifyDiagnostics();
verifier.VerifyIL("A.Equals(A)",
@"{
// Code size 29 (0x1d)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_001b
IL_0004: ldarg.1
IL_0005: brfalse.s IL_0019
IL_0007: ldarg.0
IL_0008: callvirt ""System.Type A.EqualityContract.get""
IL_000d: ldarg.1
IL_000e: callvirt ""System.Type A.EqualityContract.get""
IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)""
IL_0018: ret
IL_0019: ldc.i4.0
IL_001a: ret
IL_001b: ldc.i4.1
IL_001c: ret
}");
verifier.VerifyIL("B.Equals(A)",
@"{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: callvirt ""bool object.Equals(object)""
IL_0007: ret
}");
verifier.VerifyIL("C.Equals(B)",
@"{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: callvirt ""bool object.Equals(object)""
IL_0007: ret
}");
verifier.VerifyIL("C.Equals(C)",
@"{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_000c
IL_0004: ldarg.0
IL_0005: ldarg.1
IL_0006: call ""bool B.Equals(B)""
IL_000b: ret
IL_000c: ldc.i4.1
IL_000d: ret
}");
VerifyVirtualMethod(comp.GetMember<MethodSymbol>("A.get_EqualityContract"), isOverride: false);
VerifyVirtualMethod(comp.GetMember<MethodSymbol>("B.get_EqualityContract"), isOverride: true);
VerifyVirtualMethod(comp.GetMember<MethodSymbol>("C.get_EqualityContract"), isOverride: true);
VerifyVirtualMethod(comp.GetMember<MethodSymbol>("A." + WellKnownMemberNames.CloneMethodName), isOverride: false);
VerifyVirtualMethod(comp.GetMember<MethodSymbol>("B." + WellKnownMemberNames.CloneMethodName), isOverride: true);
VerifyVirtualMethod(comp.GetMember<MethodSymbol>("C." + WellKnownMemberNames.CloneMethodName), isOverride: true);
VerifyVirtualMethod(comp.GetMember<MethodSymbol>("A.GetHashCode"), isOverride: true);
VerifyVirtualMethod(comp.GetMember<MethodSymbol>("B.GetHashCode"), isOverride: true);
VerifyVirtualMethod(comp.GetMember<MethodSymbol>("C.GetHashCode"), isOverride: true);
VerifyVirtualMethods(comp.GetMembers("A.Equals"), ("System.Boolean A.Equals(A? other)", false), ("System.Boolean A.Equals(System.Object? obj)", true));
VerifyVirtualMethods(comp.GetMembers("B.Equals"), ("System.Boolean B.Equals(B? other)", false), ("System.Boolean B.Equals(A? other)", true), ("System.Boolean B.Equals(System.Object? obj)", true));
ImmutableArray<Symbol> cEquals = comp.GetMembers("C.Equals");
VerifyVirtualMethods(cEquals, ("System.Boolean C.Equals(C? other)", false), ("System.Boolean C.Equals(B? other)", true), ("System.Boolean C.Equals(System.Object? obj)", true));
var baseEquals = cEquals[1];
Assert.Equal("System.Boolean C.Equals(B? other)", baseEquals.ToTestDisplayString());
Assert.Equal(Accessibility.Public, baseEquals.DeclaredAccessibility);
Assert.True(baseEquals.IsOverride);
Assert.True(baseEquals.IsSealed);
Assert.True(baseEquals.IsImplicitlyDeclared);
}
private static void VerifyVirtualMethod(MethodSymbol method, bool isOverride)
{
Assert.Equal(!isOverride, method.IsVirtual);
Assert.Equal(isOverride, method.IsOverride);
Assert.True(method.IsMetadataVirtual());
Assert.Equal(!isOverride, method.IsMetadataNewSlot());
}
private static void VerifyVirtualMethods(ImmutableArray<Symbol> members, params (string displayString, bool isOverride)[] values)
{
Assert.Equal(members.Length, values.Length);
for (int i = 0; i < members.Length; i++)
{
var method = (MethodSymbol)members[i];
(string displayString, bool isOverride) = values[i];
Assert.Equal(displayString, method.ToTestDisplayString(includeNonNullable: true));
VerifyVirtualMethod(method, isOverride);
}
}
[WorkItem(44895, "https://github.com/dotnet/roslyn/issues/44895")]
[Fact]
public void Equality_08()
{
var source =
@"
using System;
using static System.Console;
record A(int X)
{
internal A() : this(0) { } // Use record base call syntax instead
internal int X { get; set; } // Use record base call syntax instead
}
record B : A
{
internal B() { } // Use record base call syntax instead
internal B(int X, int Y) : base(X) { this.Y = Y; }
internal int Y { get; set; }
protected override Type EqualityContract => typeof(A);
public virtual bool Equals(B b) => base.Equals((A)b);
}
record C(int X, int Y, int Z) : B
{
internal C() : this(0, 0, 0) { } // Use record base call syntax instead
internal int Z { get; set; } // Use record base call syntax instead
}
class Program
{
static A NewA(int x) => new A { X = x }; // Use record base call syntax instead
static B NewB(int x, int y) => new B { X = x, Y = y };
static C NewC(int x, int y, int z) => new C { X = x, Y = y, Z = z };
static void Main()
{
WriteLine(NewA(1).Equals(NewA(1)));
WriteLine(NewA(1).Equals(NewB(1, 2)));
WriteLine(NewA(1).Equals(NewC(1, 2, 3)));
WriteLine(NewB(1, 2).Equals(NewA(1)));
WriteLine(NewB(1, 2).Equals(NewB(1, 2)));
WriteLine(NewB(1, 2).Equals(NewC(1, 2, 3)));
WriteLine(NewC(1, 2, 3).Equals(NewA(1)));
WriteLine(NewC(1, 2, 3).Equals(NewB(1, 2)));
WriteLine(NewC(1, 2, 3).Equals(NewC(1, 2, 3)));
WriteLine(NewC(1, 2, 3).Equals(NewC(4, 2, 3)));
WriteLine(NewC(1, 2, 3).Equals(NewC(1, 4, 3)));
WriteLine(NewC(1, 2, 3).Equals(NewC(1, 4, 4)));
WriteLine(((A)NewB(1, 2)).Equals(NewA(1)));
WriteLine(((A)NewB(1, 2)).Equals(NewB(1, 2)));
WriteLine(((A)NewB(1, 2)).Equals(NewC(1, 2, 3)));
WriteLine(((A)NewC(1, 2, 3)).Equals(NewA(1)));
WriteLine(((A)NewC(1, 2, 3)).Equals(NewB(1, 2)));
WriteLine(((A)NewC(1, 2, 3)).Equals(NewC(1, 2, 3)));
WriteLine(((B)NewC(1, 2, 3)).Equals(NewA(1)));
WriteLine(((B)NewC(1, 2, 3)).Equals(NewB(1, 2)));
WriteLine(((B)NewC(1, 2, 3)).Equals(NewC(1, 2, 3)) && NewC(1, 2, 3).GetHashCode() == NewC(1, 2, 3).GetHashCode());
WriteLine(NewC(1, 2, 3).Equals((A)NewC(1, 2, 3)));
}
}";
// https://github.com/dotnet/roslyn/issues/44895: C.Equals() should compare B.Y.
var verifier = CompileAndVerify(source, expectedOutput:
@"True
True
False
False
True
False
False
False
True
False
True
False
False
True
False
False
False
True
False
False
True
True").VerifyDiagnostics(
// (4,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record A(int X)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(4, 14),
// (15,25): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode'
// public virtual bool Equals(B b) => base.Equals((A)b);
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(15, 25),
// (17,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X, int Y, int Z) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(17, 14),
// (17,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X, int Y, int Z) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(17, 21),
// (17,28): warning CS8907: Parameter 'Z' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X, int Y, int Z) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Z").WithArguments("Z").WithLocation(17, 28)
);
verifier.VerifyIL("A.Equals(A)",
@"{
// Code size 53 (0x35)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_0033
IL_0004: ldarg.1
IL_0005: brfalse.s IL_0031
IL_0007: ldarg.0
IL_0008: callvirt ""System.Type A.EqualityContract.get""
IL_000d: ldarg.1
IL_000e: callvirt ""System.Type A.EqualityContract.get""
IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)""
IL_0018: brfalse.s IL_0031
IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get""
IL_001f: ldarg.0
IL_0020: ldfld ""int A.<X>k__BackingField""
IL_0025: ldarg.1
IL_0026: ldfld ""int A.<X>k__BackingField""
IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)""
IL_0030: ret
IL_0031: ldc.i4.0
IL_0032: ret
IL_0033: ldc.i4.1
IL_0034: ret
}");
// https://github.com/dotnet/roslyn/issues/44895: C.Equals() should compare B.Y.
verifier.VerifyIL("C.Equals(C)",
@"{
// Code size 40 (0x28)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_0026
IL_0004: ldarg.0
IL_0005: ldarg.1
IL_0006: call ""bool B.Equals(B)""
IL_000b: brfalse.s IL_0024
IL_000d: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get""
IL_0012: ldarg.0
IL_0013: ldfld ""int C.<Z>k__BackingField""
IL_0018: ldarg.1
IL_0019: ldfld ""int C.<Z>k__BackingField""
IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)""
IL_0023: ret
IL_0024: ldc.i4.0
IL_0025: ret
IL_0026: ldc.i4.1
IL_0027: ret
}");
verifier.VerifyIL("C.GetHashCode()",
@"{
// Code size 30 (0x1e)
.maxstack 3
IL_0000: ldarg.0
IL_0001: call ""int B.GetHashCode()""
IL_0006: ldc.i4 0xa5555529
IL_000b: mul
IL_000c: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get""
IL_0011: ldarg.0
IL_0012: ldfld ""int C.<Z>k__BackingField""
IL_0017: callvirt ""int System.Collections.Generic.EqualityComparer<int>.GetHashCode(int)""
IL_001c: add
IL_001d: ret
}");
}
[Fact]
public void Equality_09()
{
var source =
@"using static System.Console;
record A(int X)
{
internal A() : this(0) { } // Use record base call syntax instead
internal int X { get; set; } // Use record base call syntax instead
}
record B(int X, int Y) : A
{
internal B() : this(0, 0) { } // Use record base call syntax instead
internal int Y { get; set; }
}
record C(int X, int Y, int Z) : B
{
internal C() : this(0, 0, 0) { } // Use record base call syntax instead
internal int Z { get; set; } // Use record base call syntax instead
}
class Program
{
static A NewA(int x) => new A { X = x }; // Use record base call syntax instead
static B NewB(int x, int y) => new B { X = x, Y = y };
static C NewC(int x, int y, int z) => new C { X = x, Y = y, Z = z };
static void Main()
{
WriteLine(NewA(1).Equals(NewA(1)));
WriteLine(NewA(1).Equals(NewB(1, 2)));
WriteLine(NewA(1).Equals(NewC(1, 2, 3)));
WriteLine(NewB(1, 2).Equals(NewA(1)));
WriteLine(NewB(1, 2).Equals(NewB(1, 2)));
WriteLine(NewB(1, 2).Equals(NewC(1, 2, 3)));
WriteLine(NewC(1, 2, 3).Equals(NewA(1)));
WriteLine(NewC(1, 2, 3).Equals(NewB(1, 2)));
WriteLine(NewC(1, 2, 3).Equals(NewC(1, 2, 3)));
WriteLine(NewC(1, 2, 3).Equals(NewC(4, 2, 3)));
WriteLine(NewC(1, 2, 3).Equals(NewC(1, 4, 3)));
WriteLine(NewC(1, 2, 3).Equals(NewC(1, 4, 4)));
WriteLine(((A)NewB(1, 2)).Equals(NewA(1)));
WriteLine(((A)NewB(1, 2)).Equals(NewB(1, 2)));
WriteLine(((A)NewB(1, 2)).Equals(NewC(1, 2, 3)));
WriteLine(((A)NewC(1, 2, 3)).Equals(NewA(1)));
WriteLine(((A)NewC(1, 2, 3)).Equals(NewB(1, 2)));
WriteLine(((A)NewC(1, 2, 3)).Equals(NewC(1, 2, 3)));
WriteLine(((B)NewC(1, 2, 3)).Equals(NewA(1)));
WriteLine(((B)NewC(1, 2, 3)).Equals(NewB(1, 2)));
WriteLine(((B)NewC(1, 2, 3)).Equals(NewC(1, 2, 3)));
WriteLine(NewC(1, 2, 3).Equals((A)NewC(1, 2, 3)));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var recordDeclaration = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().ElementAt(1);
Assert.Equal("B", recordDeclaration.Identifier.ValueText);
Assert.Null(model.GetOperation(recordDeclaration));
var verifier = CompileAndVerify(comp, expectedOutput:
@"True
False
False
False
True
False
False
False
True
False
False
False
False
True
False
False
False
True
False
False
True
True").VerifyDiagnostics(
// (2,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record A(int X)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 14),
// (7,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record B(int X, int Y) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(7, 14),
// (7,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// record B(int X, int Y) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(7, 21),
// (12,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X, int Y, int Z) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(12, 14),
// (12,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X, int Y, int Z) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(12, 21),
// (12,28): warning CS8907: Parameter 'Z' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X, int Y, int Z) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Z").WithArguments("Z").WithLocation(12, 28)
);
verifier.VerifyIL("A.Equals(A)",
@"{
// Code size 53 (0x35)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_0033
IL_0004: ldarg.1
IL_0005: brfalse.s IL_0031
IL_0007: ldarg.0
IL_0008: callvirt ""System.Type A.EqualityContract.get""
IL_000d: ldarg.1
IL_000e: callvirt ""System.Type A.EqualityContract.get""
IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)""
IL_0018: brfalse.s IL_0031
IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get""
IL_001f: ldarg.0
IL_0020: ldfld ""int A.<X>k__BackingField""
IL_0025: ldarg.1
IL_0026: ldfld ""int A.<X>k__BackingField""
IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)""
IL_0030: ret
IL_0031: ldc.i4.0
IL_0032: ret
IL_0033: ldc.i4.1
IL_0034: ret
}");
verifier.VerifyIL("B.Equals(A)",
@"{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: callvirt ""bool object.Equals(object)""
IL_0007: ret
}");
verifier.VerifyIL("B.Equals(B)",
@"{
// Code size 40 (0x28)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_0026
IL_0004: ldarg.0
IL_0005: ldarg.1
IL_0006: call ""bool A.Equals(A)""
IL_000b: brfalse.s IL_0024
IL_000d: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get""
IL_0012: ldarg.0
IL_0013: ldfld ""int B.<Y>k__BackingField""
IL_0018: ldarg.1
IL_0019: ldfld ""int B.<Y>k__BackingField""
IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)""
IL_0023: ret
IL_0024: ldc.i4.0
IL_0025: ret
IL_0026: ldc.i4.1
IL_0027: ret
}");
verifier.VerifyIL("C.Equals(B)",
@"{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: callvirt ""bool object.Equals(object)""
IL_0007: ret
}");
verifier.VerifyIL("C.Equals(C)",
@"{
// Code size 40 (0x28)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_0026
IL_0004: ldarg.0
IL_0005: ldarg.1
IL_0006: call ""bool B.Equals(B)""
IL_000b: brfalse.s IL_0024
IL_000d: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get""
IL_0012: ldarg.0
IL_0013: ldfld ""int C.<Z>k__BackingField""
IL_0018: ldarg.1
IL_0019: ldfld ""int C.<Z>k__BackingField""
IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)""
IL_0023: ret
IL_0024: ldc.i4.0
IL_0025: ret
IL_0026: ldc.i4.1
IL_0027: ret
}");
}
[Fact]
public void Equality_11()
{
var source =
@"using System;
record A
{
protected virtual Type EqualityContract => typeof(object);
}
record B1(object P) : A;
record B2(object P) : A;
class Program
{
static void Main()
{
Console.WriteLine(new A().Equals(new A()));
Console.WriteLine(new A().Equals(new B1((object)null)));
Console.WriteLine(new B1((object)null).Equals(new A()));
Console.WriteLine(new B1((object)null).Equals(new B1((object)null)));
Console.WriteLine(new B1((object)null).Equals(new B2((object)null)));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
// init-only is unverifiable
CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput:
@"True
False
False
True
False").VerifyDiagnostics();
}
[Fact]
public void Equality_12()
{
var source =
@"using System;
abstract record A
{
public A() { }
protected abstract Type EqualityContract { get; }
}
record B1(object P) : A;
record B2(object P) : A;
class Program
{
static void Main()
{
var b1 = new B1((object)null);
var b2 = new B2((object)null);
Console.WriteLine(b1.Equals(b1));
Console.WriteLine(b1.Equals(b2));
Console.WriteLine(((A)b1).Equals(b1));
Console.WriteLine(((A)b1).Equals(b2));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
// init-only is unverifiable
CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput:
@"True
False
True
False").VerifyDiagnostics();
}
[Fact]
public void Equality_13()
{
var source =
@"record A
{
protected System.Type EqualityContract => typeof(A);
}
record B : A;
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (3,27): error CS8872: 'A.EqualityContract' must allow overriding because the containing record is not sealed.
// protected System.Type EqualityContract => typeof(A);
Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(3, 27),
// (5,8): error CS0506: 'B.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override
// record B : A;
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.EqualityContract", "A.EqualityContract").WithLocation(5, 8));
}
[Fact]
public void Equality_14()
{
var source =
@"record A;
record B : A
{
protected sealed override System.Type EqualityContract => typeof(B);
}
record C : B;
";
var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardLatest);
comp.VerifyDiagnostics(
// (4,43): error CS8872: 'B.EqualityContract' must allow overriding because the containing record is not sealed.
// protected sealed override System.Type EqualityContract => typeof(B);
Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("B.EqualityContract").WithLocation(4, 43),
// (6,8): error CS0239: 'C.EqualityContract': cannot override inherited member 'B.EqualityContract' because it is sealed
// record C : B;
Diagnostic(ErrorCode.ERR_CantOverrideSealed, "C").WithArguments("C.EqualityContract", "B.EqualityContract").WithLocation(6, 8));
Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses);
string expectedClone = comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses
? "B B." + WellKnownMemberNames.CloneMethodName + "()"
: "A B." + WellKnownMemberNames.CloneMethodName + "()";
var actualMembers = comp.GetMember<NamedTypeSymbol>("B").GetMembers().ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type B.EqualityContract { get; }",
"System.Type B.EqualityContract.get",
"System.String B.ToString()",
"System.Boolean B." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)",
"System.Boolean B.op_Inequality(B? left, B? right)",
"System.Boolean B.op_Equality(B? left, B? right)",
"System.Int32 B.GetHashCode()",
"System.Boolean B.Equals(System.Object? obj)",
"System.Boolean B.Equals(A? other)",
"System.Boolean B.Equals(B? other)",
expectedClone,
"B..ctor(B original)",
"B..ctor()",
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void Equality_15()
{
var source =
@"using System;
record A;
record B1 : A
{
public B1(int p) { P = p; }
public int P { get; set; }
protected override Type EqualityContract => typeof(A);
public virtual bool Equals(B1 o) => base.Equals((A)o);
}
record B2 : A
{
public B2(int p) { P = p; }
public int P { get; set; }
protected override Type EqualityContract => typeof(B2);
public virtual bool Equals(B2 o) => base.Equals((A)o);
}
class Program
{
static void Main()
{
Console.WriteLine(new B1(1).Equals(new B1(2)));
Console.WriteLine(new B1(1).Equals(new B2(1)));
Console.WriteLine(new B2(1).Equals(new B2(2)));
}
}";
CompileAndVerify(source, expectedOutput:
@"True
False
True").VerifyDiagnostics(
// (8,25): warning CS8851: 'B1' defines 'Equals' but not 'GetHashCode'
// public virtual bool Equals(B1 o) => base.Equals((A)o);
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B1").WithLocation(8, 25),
// (15,25): warning CS8851: 'B2' defines 'Equals' but not 'GetHashCode'
// public virtual bool Equals(B2 o) => base.Equals((A)o);
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B2").WithLocation(15, 25)
);
}
[Fact]
public void Equality_16()
{
var source =
@"using System;
record A;
record B1 : A
{
public B1(int p) { P = p; }
public int P { get; set; }
protected override Type EqualityContract => typeof(string);
public virtual bool Equals(B1 b) => base.Equals((A)b);
}
record B2 : A
{
public B2(int p) { P = p; }
public int P { get; set; }
protected override Type EqualityContract => typeof(string);
public virtual bool Equals(B2 b) => base.Equals((A)b);
}
class Program
{
static void Main()
{
Console.WriteLine(new B1(1).Equals(new B1(2)));
Console.WriteLine(new B1(1).Equals(new B2(2)));
Console.WriteLine(new B2(1).Equals(new B2(2)));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"True
False
True").VerifyDiagnostics(
// (8,25): warning CS8851: 'B1' defines 'Equals' but not 'GetHashCode'
// public virtual bool Equals(B1 b) => base.Equals((A)b);
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B1").WithLocation(8, 25),
// (15,25): warning CS8851: 'B2' defines 'Equals' but not 'GetHashCode'
// public virtual bool Equals(B2 b) => base.Equals((A)b);
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B2").WithLocation(15, 25)
);
}
[Fact]
public void Equality_17()
{
var source =
@"using static System.Console;
record A;
record B1(int P) : A
{
}
record B2(int P) : A
{
}
class Program
{
static void Main()
{
WriteLine(new B1(1).Equals(new B1(1)));
WriteLine(new B1(1).Equals(new B1(2)));
WriteLine(new B2(3).Equals(new B2(3)));
WriteLine(new B2(3).Equals(new B2(4)));
WriteLine(((A)new B1(1)).Equals(new B1(1)));
WriteLine(((A)new B1(1)).Equals(new B1(2)));
WriteLine(((A)new B2(3)).Equals(new B2(3)));
WriteLine(((A)new B2(3)).Equals(new B2(4)));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
// init-only is unverifiable
CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput:
@"True
False
True
False
True
False
True
False").VerifyDiagnostics();
var actualMembers = comp.GetMember<NamedTypeSymbol>("B1").GetMembers().ToTestDisplayStrings();
var expectedMembers = new[]
{
"B1..ctor(System.Int32 P)",
"System.Type B1.EqualityContract.get",
"System.Type B1.EqualityContract { get; }",
"System.Int32 B1.<P>k__BackingField",
"System.Int32 B1.P.get",
"void modreq(System.Runtime.CompilerServices.IsExternalInit) B1.P.init",
"System.Int32 B1.P { get; init; }",
"System.String B1.ToString()",
"System.Boolean B1." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)",
"System.Boolean B1.op_Inequality(B1? left, B1? right)",
"System.Boolean B1.op_Equality(B1? left, B1? right)",
"System.Int32 B1.GetHashCode()",
"System.Boolean B1.Equals(System.Object? obj)",
"System.Boolean B1.Equals(A? other)",
"System.Boolean B1.Equals(B1? other)",
"A B1." + WellKnownMemberNames.CloneMethodName + "()",
"B1..ctor(B1 original)",
"void B1.Deconstruct(out System.Int32 P)"
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Equality_18(bool useCompilationReference)
{
var sourceA = @"public record A;";
var comp = CreateCompilation(sourceA);
comp.VerifyDiagnostics();
var refA = useCompilationReference ? comp.ToMetadataReference() : comp.EmitToImageReference();
VerifyVirtualMethod(comp.GetMember<MethodSymbol>("A.get_EqualityContract"), isOverride: false);
VerifyVirtualMethods(comp.GetMembers("A.Equals"), ("System.Boolean A.Equals(A? other)", false), ("System.Boolean A.Equals(System.Object? obj)", true));
var sourceB = @"record B : A;";
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
VerifyVirtualMethod(comp.GetMember<MethodSymbol>("B.get_EqualityContract"), isOverride: true);
VerifyVirtualMethods(comp.GetMembers("B.Equals"), ("System.Boolean B.Equals(B? other)", false), ("System.Boolean B.Equals(A? other)", true), ("System.Boolean B.Equals(System.Object? obj)", true));
}
[Fact]
public void Equality_19()
{
var source =
@"using static System.Console;
record A<T>;
record B : A<int>;
class Program
{
static void Main()
{
WriteLine(new A<int>().Equals(new A<int>()));
WriteLine(new A<int>().Equals(new B()));
WriteLine(new B().Equals(new A<int>()));
WriteLine(new B().Equals(new B()));
WriteLine(((A<int>)new B()).Equals(new A<int>()));
WriteLine(((A<int>)new B()).Equals(new B()));
WriteLine(new B().Equals((A<int>)new B()));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
var verifier = CompileAndVerify(comp, expectedOutput:
@"True
False
False
True
False
True
True").VerifyDiagnostics();
verifier.VerifyIL("A<T>.Equals(A<T>)",
@"{
// Code size 29 (0x1d)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_001b
IL_0004: ldarg.1
IL_0005: brfalse.s IL_0019
IL_0007: ldarg.0
IL_0008: callvirt ""System.Type A<T>.EqualityContract.get""
IL_000d: ldarg.1
IL_000e: callvirt ""System.Type A<T>.EqualityContract.get""
IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)""
IL_0018: ret
IL_0019: ldc.i4.0
IL_001a: ret
IL_001b: ldc.i4.1
IL_001c: ret
}");
verifier.VerifyIL("B.Equals(A<int>)",
@"{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: callvirt ""bool object.Equals(object)""
IL_0007: ret
}");
verifier.VerifyIL("B.Equals(B)",
@"{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_000c
IL_0004: ldarg.0
IL_0005: ldarg.1
IL_0006: call ""bool A<int>.Equals(A<int>)""
IL_000b: ret
IL_000c: ldc.i4.1
IL_000d: ret
}");
}
[Fact]
public void Equality_20()
{
var source =
@"
record C;
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.MakeMemberMissing(WellKnownMember.System_Collections_Generic_EqualityComparer_T__GetHashCode);
comp.VerifyEmitDiagnostics(
// (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.GetHashCode'
// record C;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C;").WithArguments("System.Collections.Generic.EqualityComparer`1", "GetHashCode").WithLocation(2, 1)
);
}
[Fact]
public void Equality_21()
{
var source =
@"
record C;
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.MakeMemberMissing(WellKnownMember.System_Collections_Generic_EqualityComparer_T__get_Default);
comp.VerifyEmitDiagnostics(
// (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.get_Default'
// record C;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C;").WithArguments("System.Collections.Generic.EqualityComparer`1", "get_Default").WithLocation(2, 1)
);
}
[Fact]
[WorkItem(44988, "https://github.com/dotnet/roslyn/issues/44988")]
public void Equality_22()
{
var source =
@"
record C
{
int x = 0;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.MakeMemberMissing(WellKnownMember.System_Collections_Generic_EqualityComparer_T__get_Default);
comp.VerifyEmitDiagnostics(
// (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.get_Default'
// record C
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"record C
{
int x = 0;
}").WithArguments("System.Collections.Generic.EqualityComparer`1", "get_Default").WithLocation(2, 1),
// (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.get_Default'
// record C
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"record C
{
int x = 0;
}").WithArguments("System.Collections.Generic.EqualityComparer`1", "get_Default").WithLocation(2, 1),
// (4,9): warning CS0414: The field 'C.x' is assigned but its value is never used
// int x = 0;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x").WithArguments("C.x").WithLocation(4, 9)
);
}
[Fact]
public void IEquatableT_01()
{
var source =
@"record A<T>;
record B : A<int>;
class Program
{
static void F<T>(System.IEquatable<T> t)
{
}
static void M<T>()
{
F(new A<T>());
F(new B());
F<A<int>>(new B());
F<B>(new B());
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (11,9): error CS0411: The type arguments for method 'Program.F<T>(IEquatable<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// F(new B());
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(System.IEquatable<T>)").WithLocation(11, 9));
}
[Fact]
public void IEquatableT_02()
{
var source =
@"using System;
record A;
record B<T> : A;
record C : B<int>;
class Program
{
static string F<T>(IEquatable<T> t)
{
return typeof(T).Name;
}
static void Main()
{
Console.WriteLine(F(new A()));
Console.WriteLine(F<A>(new C()));
Console.WriteLine(F<B<int>>(new C()));
Console.WriteLine(F<C>(new C()));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"A
A
B`1
C").VerifyDiagnostics();
}
[Fact]
public void IEquatableT_03()
{
var source =
@"#nullable enable
using System;
record A<T> : IEquatable<A<T>>
{
}
record B : A<object>, IEquatable<A<object>>, IEquatable<B?>;
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var type = comp.GetMember<NamedTypeSymbol>("A");
AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
type = comp.GetMember<NamedTypeSymbol>("B");
AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B?>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B?>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
}
[Fact]
public void IEquatableT_04()
{
var source =
@"using System;
record A<T>
{
internal static bool Report(string s) { Console.WriteLine(s); return false; }
public virtual bool Equals(A<T> other) => Report(""A<T>.Equals(A<T>)"");
}
record B : A<object>
{
public virtual bool Equals(B other) => Report(""B.Equals(B)"");
}
class Program
{
static void Main()
{
var a = new A<object>();
var b = new B();
_ = a.Equals(b);
_ = ((A<object>)b).Equals(b);
_ = b.Equals(a);
_ = b.Equals(b);
_ = ((IEquatable<A<object>>)a).Equals(b);
_ = ((IEquatable<A<object>>)b).Equals(b);
_ = ((IEquatable<B>)b).Equals(b);
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"A<T>.Equals(A<T>)
B.Equals(B)
B.Equals(B)
B.Equals(B)
A<T>.Equals(A<T>)
B.Equals(B)
B.Equals(B)").VerifyDiagnostics(
// (5,25): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode'
// public virtual bool Equals(A<T> other) => Report("A<T>.Equals(A<T>)");
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(5, 25),
// (9,25): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode'
// public virtual bool Equals(B other) => Report("B.Equals(B)");
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 25)
);
var type = comp.GetMember<NamedTypeSymbol>("A");
AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
type = comp.GetMember<NamedTypeSymbol>("B");
AssertEx.Equal(new[] { "System.IEquatable<B>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
}
[Fact]
public void IEquatableT_05()
{
var source =
@"using System;
record A<T> : IEquatable<A<T>>
{
internal static bool Report(string s) { Console.WriteLine(s); return false; }
public virtual bool Equals(A<T> other) => Report(""A<T>.Equals(A<T>)"");
}
record B : A<object>, IEquatable<A<object>>, IEquatable<B>
{
public virtual bool Equals(B other) => Report(""B.Equals(B)"");
}
record C : A<object>, IEquatable<A<object>>, IEquatable<C>
{
}
class Program
{
static void Main()
{
var a = new A<object>();
var b = new B();
_ = a.Equals(b);
_ = ((A<object>)b).Equals(b);
_ = b.Equals(a);
_ = b.Equals(b);
_ = ((IEquatable<A<object>>)a).Equals(b);
_ = ((IEquatable<A<object>>)b).Equals(b);
_ = ((IEquatable<B>)b).Equals(b);
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"A<T>.Equals(A<T>)
B.Equals(B)
B.Equals(B)
B.Equals(B)
A<T>.Equals(A<T>)
B.Equals(B)
B.Equals(B)",
symbolValidator: m =>
{
var b = m.GlobalNamespace.GetTypeMember("B");
Assert.Equal("B.Equals(B)", b.FindImplementationForInterfaceMember(b.InterfacesNoUseSiteDiagnostics()[1].GetMember("Equals")).ToDisplayString());
var c = m.GlobalNamespace.GetTypeMember("C");
Assert.Equal("C.Equals(C?)", c.FindImplementationForInterfaceMember(c.InterfacesNoUseSiteDiagnostics()[1].GetMember("Equals")).ToDisplayString());
}).VerifyDiagnostics(
// (5,25): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode'
// public virtual bool Equals(A<T> other) => Report("A<T>.Equals(A<T>)");
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(5, 25),
// (9,25): warning CS8851: '{B}' defines 'Equals' but not 'GetHashCode'
// public virtual bool Equals(B other) => Report("B.Equals(B)");
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 25)
);
var type = comp.GetMember<NamedTypeSymbol>("A");
AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
type = comp.GetMember<NamedTypeSymbol>("B");
AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
}
[Fact]
public void IEquatableT_06()
{
var source =
@"using System;
record A<T> : IEquatable<A<T>>
{
internal static bool Report(string s) { Console.WriteLine(s); return false; }
bool IEquatable<A<T>>.Equals(A<T> other) => Report(""A<T>.Equals(A<T>)"");
}
record B : A<object>, IEquatable<A<object>>, IEquatable<B>
{
bool IEquatable<A<object>>.Equals(A<object> other) => Report(""B.Equals(A<object>)"");
bool IEquatable<B>.Equals(B other) => Report(""B.Equals(B)"");
}
class Program
{
static void Main()
{
var a = new A<object>();
var b = new B();
_ = a.Equals(b);
_ = ((A<object>)b).Equals(b);
_ = b.Equals(a);
_ = b.Equals(b);
_ = ((IEquatable<A<object>>)a).Equals(b);
_ = ((IEquatable<A<object>>)b).Equals(b);
_ = ((IEquatable<B>)b).Equals(b);
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"A<T>.Equals(A<T>)
B.Equals(A<object>)
B.Equals(B)").VerifyDiagnostics();
var type = comp.GetMember<NamedTypeSymbol>("A");
AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
type = comp.GetMember<NamedTypeSymbol>("B");
AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
}
[Fact]
public void IEquatableT_07()
{
var source =
@"using System;
record A<T> : IEquatable<B1>, IEquatable<B2>
{
bool IEquatable<B1>.Equals(B1 other) => false;
bool IEquatable<B2>.Equals(B2 other) => false;
}
record B1 : A<object>;
record B2 : A<int>;
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var type = comp.GetMember<NamedTypeSymbol>("A");
AssertEx.Equal(new[] { "System.IEquatable<B1>", "System.IEquatable<B2>", "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<B1>", "System.IEquatable<B2>", "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
type = comp.GetMember<NamedTypeSymbol>("B1");
AssertEx.Equal(new[] { "System.IEquatable<B1>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<B2>", "System.IEquatable<A<System.Object>>", "System.IEquatable<B1>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
type = comp.GetMember<NamedTypeSymbol>("B2");
AssertEx.Equal(new[] { "System.IEquatable<B2>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<B1>", "System.IEquatable<A<System.Int32>>", "System.IEquatable<B2>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
}
[Fact]
public void IEquatableT_08()
{
var source =
@"interface I<T>
{
}
record A<T> : I<A<T>>
{
}
record B : A<object>, I<A<object>>, I<B>
{
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var type = comp.GetMember<NamedTypeSymbol>("A");
AssertEx.Equal(new[] { "I<A<T>>", "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "I<A<T>>", "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
type = comp.GetMember<NamedTypeSymbol>("B");
AssertEx.Equal(new[] { "I<A<System.Object>>", "I<B>", "System.IEquatable<B>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "I<A<System.Object>>", "I<B>", "System.IEquatable<B>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
}
[Fact]
public void IEquatableT_09()
{
var source0 =
@"namespace System
{
public class Object
{
public virtual bool Equals(object other) => false;
public virtual int GetHashCode() => 0;
public virtual string ToString() => """";
}
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
}
namespace System.Text
{
public class StringBuilder
{
public StringBuilder Append(string s) => null;
public StringBuilder Append(object s) => null;
}
}";
var comp = CreateEmptyCompilation(source0);
comp.VerifyDiagnostics();
var ref0 = comp.EmitToImageReference();
var source1 =
@"record A<T>;
record B : A<int>;
";
comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (1,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported
// record A<T>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(1, 8),
// (1,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported
// record A<T>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(1, 8),
// (1,8): error CS0518: Predefined type 'System.Type' is not defined or imported
// record A<T>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(1, 8),
// (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported
// record B : A<int>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(2, 8),
// (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported
// record B : A<int>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(2, 8),
// (2,8): error CS0518: Predefined type 'System.Type' is not defined or imported
// record B : A<int>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.Type").WithLocation(2, 8)
);
var type = comp.GetMember<NamedTypeSymbol>("A");
AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
type = comp.GetMember<NamedTypeSymbol>("B");
AssertEx.Equal(new[] { "System.IEquatable<B>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<A<System.Int32>>[missing]", "System.IEquatable<B>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
}
[Fact]
public void IEquatableT_10()
{
var source0 =
@"namespace System
{
public class Object
{
public virtual bool Equals(object other) => false;
public virtual int GetHashCode() => 0;
public virtual string ToString() => """";
}
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
}
namespace System.Text
{
public class StringBuilder
{
public StringBuilder Append(string s) => null;
public StringBuilder Append(object s) => null;
}
}";
var comp = CreateEmptyCompilation(source0);
comp.VerifyDiagnostics();
var ref0 = comp.EmitToImageReference();
var source1 =
@"record A<T> : System.IEquatable<A<T>>;
record B : A<int>, System.IEquatable<B>;
";
comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (1,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported
// record A<T> : System.IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(1, 8),
// (1,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported
// record A<T> : System.IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(1, 8),
// (1,8): error CS0518: Predefined type 'System.Type' is not defined or imported
// record A<T> : System.IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(1, 8),
// (1,8): error CS0115: 'A<T>.ToString()': no suitable method found to override
// record A<T> : System.IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.ToString()").WithLocation(1, 8),
// (1,8): error CS0115: 'A<T>.EqualityContract': no suitable method found to override
// record A<T> : System.IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.EqualityContract").WithLocation(1, 8),
// (1,8): error CS0115: 'A<T>.Equals(object?)': no suitable method found to override
// record A<T> : System.IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.Equals(object?)").WithLocation(1, 8),
// (1,8): error CS0115: 'A<T>.GetHashCode()': no suitable method found to override
// record A<T> : System.IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.GetHashCode()").WithLocation(1, 8),
// (1,8): error CS0115: 'A<T>.PrintMembers(StringBuilder)': no suitable method found to override
// record A<T> : System.IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.PrintMembers(System.Text.StringBuilder)").WithLocation(1, 8),
// (1,22): error CS0234: The type or namespace name 'IEquatable<>' does not exist in the namespace 'System' (are you missing an assembly reference?)
// record A<T> : System.IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "IEquatable<A<T>>").WithArguments("IEquatable<>", "System").WithLocation(1, 22),
// (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported
// record B : A<int>, System.IEquatable<B>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(2, 8),
// (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported
// record B : A<int>, System.IEquatable<B>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(2, 8),
// (2,8): error CS0518: Predefined type 'System.Type' is not defined or imported
// record B : A<int>, System.IEquatable<B>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.Type").WithLocation(2, 8),
// (2,27): error CS0234: The type or namespace name 'IEquatable<>' does not exist in the namespace 'System' (are you missing an assembly reference?)
// record B : A<int>, System.IEquatable<B>;
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "IEquatable<B>").WithArguments("IEquatable<>", "System").WithLocation(2, 27));
var type = comp.GetMember<NamedTypeSymbol>("A");
AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
type = comp.GetMember<NamedTypeSymbol>("B");
AssertEx.Equal(new[] { "System.IEquatable<B>", "System.IEquatable<B>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<A<System.Int32>>[missing]", "System.IEquatable<B>", "System.IEquatable<B>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
}
[Fact]
public void IEquatableT_11()
{
var source0 =
@"namespace System
{
public class Object
{
public virtual bool Equals(object other) => false;
public virtual int GetHashCode() => 0;
public virtual string ToString() => """";
}
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
}
namespace System.Text
{
public class StringBuilder
{
public StringBuilder Append(string s) => null;
public StringBuilder Append(object s) => null;
}
}";
var comp = CreateEmptyCompilation(source0);
comp.VerifyDiagnostics();
var ref0 = comp.EmitToImageReference();
var source1 =
@"using System;
record A<T> : IEquatable<A<T>>;
record B : A<int>, IEquatable<B>;
";
comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (1,1): hidden CS8019: Unnecessary using directive.
// using System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;").WithLocation(1, 1),
// (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported
// record A<T> : IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(2, 8),
// (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported
// record A<T> : IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(2, 8),
// (2,8): error CS0518: Predefined type 'System.Type' is not defined or imported
// record A<T> : IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 8),
// (2,8): error CS0115: 'A<T>.ToString()': no suitable method found to override
// record A<T> : IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.ToString()").WithLocation(2, 8),
// (2,8): error CS0115: 'A<T>.EqualityContract': no suitable method found to override
// record A<T> : IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.EqualityContract").WithLocation(2, 8),
// (2,8): error CS0115: 'A<T>.Equals(object?)': no suitable method found to override
// record A<T> : IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.Equals(object?)").WithLocation(2, 8),
// (2,8): error CS0115: 'A<T>.GetHashCode()': no suitable method found to override
// record A<T> : IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.GetHashCode()").WithLocation(2, 8),
// (2,8): error CS0115: 'A<T>.PrintMembers(StringBuilder)': no suitable method found to override
// record A<T> : IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8),
// (2,15): error CS0246: The type or namespace name 'IEquatable<>' could not be found (are you missing a using directive or an assembly reference?)
// record A<T> : IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IEquatable<A<T>>").WithArguments("IEquatable<>").WithLocation(2, 15),
// (3,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported
// record B : A<int>, IEquatable<B>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(3, 8),
// (3,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported
// record B : A<int>, IEquatable<B>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(3, 8),
// (3,8): error CS0518: Predefined type 'System.Type' is not defined or imported
// record B : A<int>, IEquatable<B>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.Type").WithLocation(3, 8),
// (3,20): error CS0246: The type or namespace name 'IEquatable<>' could not be found (are you missing a using directive or an assembly reference?)
// record B : A<int>, IEquatable<B>;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IEquatable<B>").WithArguments("IEquatable<>").WithLocation(3, 20));
var type = comp.GetMember<NamedTypeSymbol>("A");
AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
type = comp.GetMember<NamedTypeSymbol>("B");
AssertEx.Equal(new[] { "IEquatable<B>", "System.IEquatable<B>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<A<System.Int32>>[missing]", "IEquatable<B>", "System.IEquatable<B>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
}
[Fact]
public void IEquatableT_12()
{
var source0 =
@"namespace System
{
public class Object
{
public virtual bool Equals(object other) => false;
public virtual int GetHashCode() => 0;
public virtual string ToString() => """";
}
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public interface IEquatable<T>
{
bool Equals(T other);
void Other();
}
}
namespace System.Text
{
public class StringBuilder
{
public StringBuilder Append(string s) => null;
public StringBuilder Append(object s) => null;
}
}";
var comp = CreateEmptyCompilation(source0);
comp.VerifyDiagnostics();
var ref0 = comp.EmitToImageReference();
var source1 =
@"record A;
class Program
{
static void Main()
{
System.IEquatable<A> a = new A();
_ = a.Equals(null);
}
}";
comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (1,8): error CS0518: Predefined type 'System.Type' is not defined or imported
// record A;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(1, 8),
// (1,8): error CS0535: 'A' does not implement interface member 'IEquatable<A>.Other()'
// record A;
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "A").WithArguments("A", "System.IEquatable<A>.Other()").WithLocation(1, 8));
}
[Fact]
public void IEquatableT_13()
{
var source =
@"record A
{
internal virtual bool Equals(A other) => false;
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (1,8): error CS0737: 'A' does not implement interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement an interface member because it is not public.
// record A
Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)").WithLocation(1, 8),
// (3,27): error CS8873: Record member 'A.Equals(A)' must be public.
// internal virtual bool Equals(A other) => false;
Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(3, 27),
// (3,27): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode'
// internal virtual bool Equals(A other) => false;
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(3, 27)
);
}
[Fact]
public void IEquatableT_14()
{
var source =
@"record A
{
public bool Equals(A other) => false;
}
record B : A
{
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (3,17): error CS8872: 'A.Equals(A)' must allow overriding because the containing record is not sealed.
// public bool Equals(A other) => false;
Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(3, 17),
// (3,17): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode'
// public bool Equals(A other) => false;
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(3, 17),
// (5,8): error CS0506: 'B.Equals(A?)': cannot override inherited member 'A.Equals(A)' because it is not marked virtual, abstract, or override
// record B : A
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.Equals(A?)", "A.Equals(A)").WithLocation(5, 8));
}
[WorkItem(45026, "https://github.com/dotnet/roslyn/issues/45026")]
[Fact]
public void IEquatableT_15()
{
var source =
@"using System;
record R
{
bool IEquatable<R>.Equals(R other) => false;
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void IEquatableT_16()
{
var source =
@"using System;
class A<T>
{
record B<U> : IEquatable<B<T>>
{
bool IEquatable<B<T>>.Equals(B<T> other) => false;
bool IEquatable<B<U>>.Equals(B<U> other) => false;
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,12): error CS0695: 'A<T>.B<U>' cannot implement both 'IEquatable<A<T>.B<T>>' and 'IEquatable<A<T>.B<U>>' because they may unify for some type parameter substitutions
// record B<U> : IEquatable<B<T>>
Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "B").WithArguments("A<T>.B<U>", "System.IEquatable<A<T>.B<T>>", "System.IEquatable<A<T>.B<U>>").WithLocation(4, 12));
}
[Fact]
public void InterfaceImplementation()
{
var source = @"
interface I
{
int P1 { get; init; }
int P2 { get; init; }
int P3 { get; set; }
}
record R(int P1) : I
{
public int P2 { get; init; }
int I.P3 { get; set; }
public static void Main()
{
I r = new R(42) { P2 = 43 };
r.P3 = 44;
System.Console.Write((r.P1, r.P2, r.P3));
}
}
";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "(42, 43, 44)", verify: Verification.Skipped /* init-only */);
}
[Fact]
public void Initializers_01()
{
var src = @"
using System;
record C(int X)
{
int Z = X + 1;
public static void Main()
{
var c = new C(1);
Console.WriteLine(c.Z);
}
}";
var verifier = CompileAndVerify(src, expectedOutput: @"2").VerifyDiagnostics();
var comp = CreateCompilation(src);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First();
Assert.Equal("= X + 1", x.Parent!.Parent!.ToString());
var symbol = model.GetSymbolInfo(x).Symbol;
Assert.Equal(SymbolKind.Parameter, symbol!.Kind);
Assert.Equal("System.Int32 X", symbol.ToTestDisplayString());
Assert.Equal("C..ctor(System.Int32 X)", symbol.ContainingSymbol.ToTestDisplayString());
Assert.Equal("System.Int32 C.Z", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString());
Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X"));
Assert.Contains("X", model.LookupNames(x.SpanStart));
var recordDeclaration = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Single();
Assert.Equal("C", recordDeclaration.Identifier.ValueText);
Assert.Null(model.GetOperation(recordDeclaration));
}
[Fact]
public void Initializers_02()
{
var src = @"
record C(int X)
{
static int Z = X + 1;
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (4,20): error CS0236: A field initializer cannot reference the non-static field, method, or property 'C.X'
// static int Z = X + 1;
Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "X").WithArguments("C.X").WithLocation(4, 20)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First();
Assert.Equal("= X + 1", x.Parent!.Parent!.ToString());
var symbol = model.GetSymbolInfo(x).Symbol;
Assert.Equal(SymbolKind.Property, symbol!.Kind);
Assert.Equal("System.Int32 C.X { get; init; }", symbol.ToTestDisplayString());
Assert.Equal("C", symbol.ContainingSymbol.ToTestDisplayString());
Assert.Equal("System.Int32 C.Z", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString());
Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X"));
Assert.Contains("X", model.LookupNames(x.SpanStart));
}
[Fact]
public void Initializers_03()
{
var src = @"
record C(int X)
{
const int Z = X + 1;
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (4,19): error CS0236: A field initializer cannot reference the non-static field, method, or property 'C.X'
// const int Z = X + 1;
Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "X").WithArguments("C.X").WithLocation(4, 19)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First();
Assert.Equal("= X + 1", x.Parent!.Parent!.ToString());
var symbol = model.GetSymbolInfo(x).Symbol;
Assert.Equal(SymbolKind.Property, symbol!.Kind);
Assert.Equal("System.Int32 C.X { get; init; }", symbol.ToTestDisplayString());
Assert.Equal("C", symbol.ContainingSymbol.ToTestDisplayString());
Assert.Equal("System.Int32 C.Z", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString());
Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X"));
Assert.Contains("X", model.LookupNames(x.SpanStart));
}
[Fact]
public void Initializers_04()
{
var src = @"
using System;
record C(int X)
{
Func<int> Z = () => X + 1;
public static void Main()
{
var c = new C(1);
Console.WriteLine(c.Z());
}
}";
var verifier = CompileAndVerify(src, expectedOutput: @"2").VerifyDiagnostics();
var comp = CreateCompilation(src);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First();
Assert.Equal("() => X + 1", x.Parent!.Parent!.ToString());
var symbol = model.GetSymbolInfo(x).Symbol;
Assert.Equal(SymbolKind.Parameter, symbol!.Kind);
Assert.Equal("System.Int32 X", symbol.ToTestDisplayString());
Assert.Equal("C..ctor(System.Int32 X)", symbol.ContainingSymbol.ToTestDisplayString());
Assert.Equal("lambda expression", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString());
Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X"));
Assert.Contains("X", model.LookupNames(x.SpanStart));
}
[Fact]
public void Initializers_05()
{
var src = @"
using System;
record Base
{
public Base(Func<int> X)
{
Console.WriteLine(X());
}
public Base() {}
}
record C(int X) : Base(() => 100 + X++)
{
Func<int> Y = () => 200 + X++;
Func<int> Z = () => 300 + X++;
public static void Main()
{
var c = new C(1);
Console.WriteLine(c.Y());
Console.WriteLine(c.Z());
}
}";
var verifier = CompileAndVerify(src, expectedOutput: @"
101
202
303
").VerifyDiagnostics();
}
[Fact]
public void SynthesizedRecordPointerProperty()
{
var src = @"
record R(int P1, int* P2, delegate*<int> P3);";
var comp = CreateCompilation(src);
var p = comp.GlobalNamespace.GetTypeMember("R").GetMember<SourcePropertySymbolBase>("P1");
Assert.False(p.HasPointerType);
p = comp.GlobalNamespace.GetTypeMember("R").GetMember<SourcePropertySymbolBase>("P2");
Assert.True(p.HasPointerType);
p = comp.GlobalNamespace.GetTypeMember("R").GetMember<SourcePropertySymbolBase>("P3");
Assert.True(p.HasPointerType);
}
[Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")]
public void PositionalMemberModifiers_RefOrOut()
{
var src = @"
record R(ref int P1, out int P2);
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (2,8): error CS0177: The out parameter 'P2' must be assigned to before control leaves the current method
// record R(ref int P1, out int P2);
Diagnostic(ErrorCode.ERR_ParamUnassigned, "R").WithArguments("P2").WithLocation(2, 8),
// (2,10): error CS0631: ref and out are not valid in this context
// record R(ref int P1, out int P2);
Diagnostic(ErrorCode.ERR_IllegalRefParam, "ref").WithLocation(2, 10),
// (2,22): error CS0631: ref and out are not valid in this context
// record R(ref int P1, out int P2);
Diagnostic(ErrorCode.ERR_IllegalRefParam, "out").WithLocation(2, 22)
);
}
[Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")]
public void PositionalMemberModifiers_RefOrOut_WithBase()
{
var src = @"
record Base(int I);
record R(ref int P1, out int P2) : Base(P2 = 1);
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (3,10): error CS0631: ref and out are not valid in this context
// record R(ref int P1, out int P2) : Base(P2 = 1);
Diagnostic(ErrorCode.ERR_IllegalRefParam, "ref").WithLocation(3, 10),
// (3,22): error CS0631: ref and out are not valid in this context
// record R(ref int P1, out int P2) : Base(P2 = 1);
Diagnostic(ErrorCode.ERR_IllegalRefParam, "out").WithLocation(3, 22)
);
}
[Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")]
public void PositionalMemberModifiers_In()
{
var src = @"
record R(in int P1);
public class C
{
public static void Main()
{
var r = new R(42);
int i = 43;
var r2 = new R(in i);
System.Console.Write((r.P1, r2.P1));
}
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "(42, 43)", verify: Verification.Skipped /* init-only */);
var actualMembers = comp.GetMember<NamedTypeSymbol>("R").Constructors.ToTestDisplayStrings();
var expectedMembers = new[]
{
"R..ctor(in System.Int32 P1)",
"R..ctor(R original)"
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")]
public void PositionalMemberModifiers_This()
{
var src = @"
record R(this int i);
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (2,10): error CS0027: Keyword 'this' is not available in the current context
// record R(this int i);
Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(2, 10)
);
}
[Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")]
public void PositionalMemberModifiers_Params()
{
var src = @"
record R(params int[] Array);
public class C
{
public static void Main()
{
var r = new R(42, 43);
var r2 = new R(new[] { 44, 45 });
System.Console.Write((r.Array[0], r.Array[1], r2.Array[0], r2.Array[1]));
}
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "(42, 43, 44, 45)", verify: Verification.Skipped /* init-only */);
var actualMembers = comp.GetMember<NamedTypeSymbol>("R").Constructors.ToTestDisplayStrings();
var expectedMembers = new[]
{
"R..ctor(params System.Int32[] Array)",
"R..ctor(R original)"
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")]
public void PositionalMemberDefaultValue()
{
var src = @"
record R(int P = 42)
{
public static void Main()
{
var r = new R();
System.Console.Write(r.P);
}
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */);
}
[Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")]
public void PositionalMemberDefaultValue_AndPropertyWithInitializer()
{
var src = @"
record R(int P = 1)
{
public int P { get; init; } = 42;
public static void Main()
{
var r = new R();
System.Console.Write(r.P);
}
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (2,14): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name?
// record R(int P = 1)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 14)
);
var verifier = CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */);
verifier.VerifyIL("R..ctor(int)", @"
{
// Code size 16 (0x10)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 42
IL_0003: stfld ""int R.<P>k__BackingField""
IL_0008: ldarg.0
IL_0009: call ""object..ctor()""
IL_000e: nop
IL_000f: ret
}");
}
[Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")]
public void PositionalMemberDefaultValue_AndPropertyWithoutInitializer()
{
var src = @"
record R(int P = 42)
{
public int P { get; init; }
public static void Main()
{
var r = new R();
System.Console.Write(r.P);
}
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (2,14): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name?
// record R(int P = 42)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 14)
);
var verifier = CompileAndVerify(comp, expectedOutput: "0", verify: Verification.Skipped /* init-only */);
verifier.VerifyIL("R..ctor(int)", @"
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: nop
IL_0007: ret
}");
}
[Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")]
public void PositionalMemberDefaultValue_AndPropertyWithInitializer_CopyingParameter()
{
var src = @"
record R(int P = 42)
{
public int P { get; init; } = P;
public static void Main()
{
var r = new R();
System.Console.Write(r.P);
}
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */);
verifier.VerifyIL("R..ctor(int)", @"
{
// Code size 15 (0xf)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld ""int R.<P>k__BackingField""
IL_0007: ldarg.0
IL_0008: call ""object..ctor()""
IL_000d: nop
IL_000e: ret
}");
}
[Fact]
public void AttributesOnPrimaryConstructorParameters_01()
{
string source = @"
[System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ]
public class A : System.Attribute
{
}
[System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = true) ]
public class B : System.Attribute
{
}
[System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ]
public class C : System.Attribute
{
}
[System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ]
public class D : System.Attribute
{
}
public record Test(
[field: A]
[property: B]
[param: C]
[D]
int P1)
{
}
";
Action<ModuleSymbol> symbolValidator = moduleSymbol =>
{
var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test");
var prop1 = @class.GetMember<PropertySymbol>("P1");
AssertEx.SetEqual(new[] { "B" }, getAttributeStrings(prop1));
var field1 = @class.GetMember<FieldSymbol>("<P1>k__BackingField");
AssertEx.SetEqual(new[] { "A" }, getAttributeStrings(field1));
var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0];
AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1));
};
var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator,
parseOptions: TestOptions.Regular9,
// init-only is unverifiable
verify: Verification.Skipped,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
comp.VerifyDiagnostics();
IEnumerable<string> getAttributeStrings(Symbol symbol)
{
return GetAttributeStrings(symbol.GetAttributes().Where(a => a.AttributeClass!.Name is "A" or "B" or "C" or "D"));
}
}
[Fact]
public void AttributesOnPrimaryConstructorParameters_02()
{
string source = @"
[System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true) ]
public class A : System.Attribute
{
}
[System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true) ]
public class B : System.Attribute
{
}
[System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true) ]
public class C : System.Attribute
{
}
[System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true) ]
public class D : System.Attribute
{
}
public record Test(
[field: A]
[property: B]
[param: C]
[D]
int P1)
{
}
";
Action<ModuleSymbol> symbolValidator = moduleSymbol =>
{
var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test");
var prop1 = @class.GetMember<PropertySymbol>("P1");
AssertEx.SetEqual(new[] { "B" }, getAttributeStrings(prop1));
var field1 = @class.GetMember<FieldSymbol>("<P1>k__BackingField");
AssertEx.SetEqual(new[] { "A" }, getAttributeStrings(field1));
var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0];
AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1));
};
var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator,
parseOptions: TestOptions.Regular9,
// init-only is unverifiable
verify: Verification.Skipped,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
comp.VerifyDiagnostics();
IEnumerable<string> getAttributeStrings(Symbol symbol)
{
return GetAttributeStrings(symbol.GetAttributes().Where(a =>
{
switch (a.AttributeClass!.Name)
{
case "A":
case "B":
case "C":
case "D":
return true;
}
return false;
}));
}
}
[Fact]
public void AttributesOnPrimaryConstructorParameters_03()
{
string source = @"
[System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ]
public class A : System.Attribute
{
}
[System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = true) ]
public class B : System.Attribute
{
}
[System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ]
public class C : System.Attribute
{
}
[System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ]
public class D : System.Attribute
{
}
public abstract record Base
{
public abstract int P1 { get; init; }
}
public record Test(
[field: A]
[property: B]
[param: C]
[D]
int P1) : Base
{
}
";
Action<ModuleSymbol> symbolValidator = moduleSymbol =>
{
var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test");
var prop1 = @class.GetMember<PropertySymbol>("P1");
AssertEx.SetEqual(new[] { "B" }, getAttributeStrings(prop1));
var field1 = @class.GetMember<FieldSymbol>("<P1>k__BackingField");
AssertEx.SetEqual(new[] { "A" }, getAttributeStrings(field1));
var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0];
AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1));
};
var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator,
parseOptions: TestOptions.Regular9,
// init-only is unverifiable
verify: Verification.Skipped,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
comp.VerifyDiagnostics();
IEnumerable<string> getAttributeStrings(Symbol symbol)
{
return GetAttributeStrings(symbol.GetAttributes().Where(a =>
{
switch (a.AttributeClass!.Name)
{
case "A":
case "B":
case "C":
case "D":
return true;
}
return false;
}));
}
}
[Fact]
public void AttributesOnPrimaryConstructorParameters_04()
{
string source = @"
[System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple = true) ]
public class A : System.Attribute
{
}
public record Test(
[method: A]
int P1)
{
[method: A]
void M1() {}
}
";
Action<ModuleSymbol> symbolValidator = moduleSymbol =>
{
var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test");
var prop1 = @class.GetMember<PropertySymbol>("P1");
AssertEx.SetEqual(new string[] { }, getAttributeStrings(prop1));
var field1 = @class.GetMember<FieldSymbol>("<P1>k__BackingField");
AssertEx.SetEqual(new string[] { }, getAttributeStrings(field1));
var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0];
AssertEx.SetEqual(new string[] { }, getAttributeStrings(param1));
};
var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator,
parseOptions: TestOptions.Regular9,
// init-only is unverifiable
verify: Verification.Skipped,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
comp.VerifyDiagnostics(
// (8,6): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property, param'. All attributes in this block will be ignored.
// [method: A]
Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "field, property, param").WithLocation(8, 6)
);
IEnumerable<string> getAttributeStrings(Symbol symbol)
{
return GetAttributeStrings(symbol.GetAttributes().Where(a =>
{
switch (a.AttributeClass!.Name)
{
case "A":
return true;
}
return false;
}));
}
}
[Fact]
public void AttributesOnPrimaryConstructorParameters_05()
{
string source = @"
[System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ]
public class A : System.Attribute
{
}
[System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = true) ]
public class B : System.Attribute
{
}
[System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ]
public class C : System.Attribute
{
}
[System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ]
public class D : System.Attribute
{
}
public abstract record Base
{
public virtual int P1 { get; init; }
}
public record Test(
[field: A]
[property: B]
[param: C]
[D]
int P1) : Base
{
}
";
Action<ModuleSymbol> symbolValidator = moduleSymbol =>
{
var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test");
Assert.Null(@class.GetMember<PropertySymbol>("P1"));
Assert.Null(@class.GetMember<FieldSymbol>("<P1>k__BackingField"));
var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0];
AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1));
};
var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator,
parseOptions: TestOptions.Regular9,
// init-only is unverifiable
verify: Verification.Skipped,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
comp.VerifyDiagnostics(
// (27,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored.
// [field: A]
Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "param").WithLocation(27, 6),
// (28,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored.
// [property: B]
Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "param").WithLocation(28, 6),
// (31,9): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// int P1) : Base
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(31, 9)
);
IEnumerable<string> getAttributeStrings(Symbol symbol)
{
return GetAttributeStrings(symbol.GetAttributes().Where(a =>
{
switch (a.AttributeClass!.Name)
{
case "A":
case "B":
case "C":
case "D":
return true;
}
return false;
}));
}
}
[Fact]
public void AttributesOnPrimaryConstructorParameters_06()
{
string source = @"
[System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ]
public class A : System.Attribute
{
}
[System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = true) ]
public class B : System.Attribute
{
}
[System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ]
public class C : System.Attribute
{
}
[System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ]
public class D : System.Attribute
{
}
public abstract record Base
{
public int P1 { get; init; }
}
public record Test(
[field: A]
[property: B]
[param: C]
[D]
int P1) : Base
{
}
";
Action<ModuleSymbol> symbolValidator = moduleSymbol =>
{
var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test");
Assert.Null(@class.GetMember<PropertySymbol>("P1"));
Assert.Null(@class.GetMember<FieldSymbol>("<P1>k__BackingField"));
var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0];
AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1));
};
var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator,
parseOptions: TestOptions.Regular9,
// init-only is unverifiable
verify: Verification.Skipped,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
comp.VerifyDiagnostics(
// (27,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored.
// [field: A]
Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "param").WithLocation(27, 6),
// (28,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored.
// [property: B]
Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "param").WithLocation(28, 6),
// (31,9): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// int P1) : Base
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(31, 9)
);
IEnumerable<string> getAttributeStrings(Symbol symbol)
{
return GetAttributeStrings(symbol.GetAttributes().Where(a =>
{
switch (a.AttributeClass!.Name)
{
case "A":
case "B":
case "C":
case "D":
return true;
}
return false;
}));
}
}
[Fact]
public void AttributesOnPrimaryConstructorParameters_07()
{
string source = @"
[System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ]
public class C : System.Attribute
{
}
[System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ]
public class D : System.Attribute
{
}
public abstract record Base
{
public int P1 { get; init; }
}
public record Test(
[param: C]
[D]
int P1) : Base
{
}
";
Action<ModuleSymbol> symbolValidator = moduleSymbol =>
{
var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test");
var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0];
AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1));
};
var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator,
parseOptions: TestOptions.Regular9,
// init-only is unverifiable
verify: Verification.Skipped,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
comp.VerifyDiagnostics(
// (20,9): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// int P1) : Base
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(20, 9)
);
IEnumerable<string> getAttributeStrings(Symbol symbol)
{
return GetAttributeStrings(symbol.GetAttributes().Where(a =>
{
switch (a.AttributeClass!.Name)
{
case "C":
case "D":
return true;
}
return false;
}));
}
}
[Fact]
public void AttributesOnPrimaryConstructorParameters_08()
{
string source = @"
#nullable enable
using System.Diagnostics.CodeAnalysis;
record C<T>([property: NotNull] T? P1, T? P2) where T : class
{
protected C(C<T> other)
{
T x = P1;
T y = P2;
}
}
";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition, NotNullAttributeDefinition }, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (10,15): warning CS8600: Converting null literal or possible null value to non-nullable type.
// T y = P2;
Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "P2").WithLocation(10, 15)
);
}
[Fact]
public void AttributesOnPrimaryConstructorParameters_09_CallerMemberName()
{
string source = @"
using System.Runtime.CompilerServices;
record R([CallerMemberName] string S = """");
class C
{
public static void Main()
{
var r = new R();
System.Console.Write(r.S);
}
}
";
var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, expectedOutput: "Main",
parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe, verify: Verification.Skipped /* init-only */);
comp.VerifyDiagnostics();
}
[Fact]
public void RecordWithConstraints_NullableWarning()
{
var src = @"
#nullable enable
record R<T>(T P) where T : class;
record R2<T>(T P) where T : class { }
public class C
{
public static void Main()
{
var r = new R<string?>(""R"");
var r2 = new R2<string?>(""R2"");
System.Console.Write((r.P, r2.P));
}
}";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (10,23): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'R<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint.
// var r = new R<string?>("R");
Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("R<T>", "T", "string?").WithLocation(10, 23),
// (11,25): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'R2<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint.
// var r2 = new R2<string?>("R2");
Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("R2<T>", "T", "string?").WithLocation(11, 25)
);
CompileAndVerify(comp, expectedOutput: "(R, R2)", verify: Verification.Skipped /* init-only */);
}
[Fact]
public void RecordWithConstraints_ConstraintError()
{
var src = @"
record R<T>(T P) where T : class;
record R2<T>(T P) where T : class { }
public class C
{
public static void Main()
{
_ = new R<int>(1);
_ = new R2<int>(2);
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (9,19): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'R<T>'
// _ = new R<int>(1);
Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("R<T>", "T", "int").WithLocation(9, 19),
// (10,20): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'R2<T>'
// _ = new R2<int>(2);
Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("R2<T>", "T", "int").WithLocation(10, 20)
);
}
[Fact]
public void AccessCheckProtected03()
{
CSharpCompilation c = CreateCompilation(@"
record X<T> { }
record A { }
record B
{
record C : X<C.D.E>
{
protected record D : A
{
public record E { }
}
}
}
", targetFramework: TargetFramework.StandardLatest);
Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, c.Assembly.RuntimeSupportsCovariantReturnsOfClasses);
if (c.Assembly.RuntimeSupportsCovariantReturnsOfClasses)
{
c.VerifyDiagnostics(
// (8,12): error CS0060: Inconsistent accessibility: base type 'X<B.C.D.E>' is less accessible than class 'B.C'
// record C : X<C.D.E>
Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C").WithArguments("B.C", "X<B.C.D.E>").WithLocation(8, 12),
// (8,12): error CS0051: Inconsistent accessibility: parameter type 'X<B.C.D.E>' is less accessible than method 'B.C.Equals(X<B.C.D.E>?)'
// record C : X<C.D.E>
Diagnostic(ErrorCode.ERR_BadVisParamType, "C").WithArguments("B.C.Equals(X<B.C.D.E>?)", "X<B.C.D.E>").WithLocation(8, 12)
);
}
else
{
c.VerifyDiagnostics(
// (8,12): error CS0060: Inconsistent accessibility: base type 'X<B.C.D.E>' is less accessible than class 'B.C'
// record C : X<C.D.E>
Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C").WithArguments("B.C", "X<B.C.D.E>").WithLocation(8, 12),
// (8,12): error CS0050: Inconsistent accessibility: return type 'X<B.C.D.E>' is less accessible than method 'B.C.<Clone>$()'
// record C : X<C.D.E>
Diagnostic(ErrorCode.ERR_BadVisReturnType, "C").WithArguments("B.C.<Clone>$()", "X<B.C.D.E>").WithLocation(8, 12),
// (8,12): error CS0051: Inconsistent accessibility: parameter type 'X<B.C.D.E>' is less accessible than method 'B.C.Equals(X<B.C.D.E>?)'
// record C : X<C.D.E>
Diagnostic(ErrorCode.ERR_BadVisParamType, "C").WithArguments("B.C.Equals(X<B.C.D.E>?)", "X<B.C.D.E>").WithLocation(8, 12)
);
}
}
[Fact]
public void TestTargetType_Abstract()
{
var source = @"
abstract record C
{
void M()
{
C x0 = new();
var x1 = (C)new();
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,16): error CS0144: Cannot create an instance of the abstract type or interface 'C'
// C x0 = new();
Diagnostic(ErrorCode.ERR_NoNewAbstract, "new()").WithArguments("C").WithLocation(6, 16),
// (7,21): error CS0144: Cannot create an instance of the abstract type or interface 'C'
// var x1 = (C)new();
Diagnostic(ErrorCode.ERR_NoNewAbstract, "new()").WithArguments("C").WithLocation(7, 21)
);
}
[Fact]
public void CyclicBases4()
{
var text =
@"
record A<T> : B<A<T>> { }
record B<T> : A<B<T>> {
A<T> F() { return null; }
}
";
var comp = CreateCompilation(text);
comp.GetDeclarationDiagnostics().Verify(
// (2,8): error CS0146: Circular base type dependency involving 'B<A<T>>' and 'A<T>'
// record A<T> : B<A<T>> { }
Diagnostic(ErrorCode.ERR_CircularBase, "A").WithArguments("B<A<T>>", "A<T>").WithLocation(2, 8),
// (3,8): error CS0146: Circular base type dependency involving 'A<B<T>>' and 'B<T>'
// record B<T> : A<B<T>> {
Diagnostic(ErrorCode.ERR_CircularBase, "B").WithArguments("A<B<T>>", "B<T>").WithLocation(3, 8),
// (2,8): error CS0115: 'A<T>.ToString()': no suitable method found to override
// record A<T> : B<A<T>> { }
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.ToString()").WithLocation(2, 8),
// (2,8): error CS0115: 'A<T>.EqualityContract': no suitable method found to override
// record A<T> : B<A<T>> { }
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.EqualityContract").WithLocation(2, 8),
// (2,8): error CS0115: 'A<T>.Equals(object?)': no suitable method found to override
// record A<T> : B<A<T>> { }
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.Equals(object?)").WithLocation(2, 8),
// (2,8): error CS0115: 'A<T>.GetHashCode()': no suitable method found to override
// record A<T> : B<A<T>> { }
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.GetHashCode()").WithLocation(2, 8),
// (2,8): error CS0115: 'A<T>.PrintMembers(StringBuilder)': no suitable method found to override
// record A<T> : B<A<T>> { }
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8),
// (3,8): error CS0115: 'B<T>.EqualityContract': no suitable method found to override
// record B<T> : A<B<T>> {
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B<T>.EqualityContract").WithLocation(3, 8),
// (3,8): error CS0115: 'B<T>.Equals(object?)': no suitable method found to override
// record B<T> : A<B<T>> {
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B<T>.Equals(object?)").WithLocation(3, 8),
// (3,8): error CS0115: 'B<T>.GetHashCode()': no suitable method found to override
// record B<T> : A<B<T>> {
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B<T>.GetHashCode()").WithLocation(3, 8),
// (3,8): error CS0115: 'B<T>.PrintMembers(StringBuilder)': no suitable method found to override
// record B<T> : A<B<T>> {
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B<T>.PrintMembers(System.Text.StringBuilder)").WithLocation(3, 8),
// (3,8): error CS0115: 'B<T>.ToString()': no suitable method found to override
// record B<T> : A<B<T>> {
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B<T>.ToString()").WithLocation(3, 8)
);
}
[Fact]
public void CS0250ERR_CallingBaseFinalizeDeprecated()
{
var text = @"
record B
{
}
record C : B
{
~C()
{
base.Finalize(); // CS0250
}
public static void Main()
{
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (10,7): error CS0250: Do not directly call your base type Finalize method. It is called automatically from your destructor.
Diagnostic(ErrorCode.ERR_CallingBaseFinalizeDeprecated, "base.Finalize()")
);
}
[Fact]
public void PartialClassWithDifferentTupleNamesInBaseTypes()
{
var source = @"
public record Base<T> { }
public partial record C1 : Base<(int a, int b)> { }
public partial record C1 : Base<(int notA, int notB)> { }
public partial record C2 : Base<(int a, int b)> { }
public partial record C2 : Base<(int, int)> { }
public partial record C3 : Base<(int a, int b)> { }
public partial record C3 : Base<(int a, int b)> { }
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (5,23): error CS0263: Partial declarations of 'C2' must not specify different base classes
// public partial record C2 : Base<(int a, int b)> { }
Diagnostic(ErrorCode.ERR_PartialMultipleBases, "C2").WithArguments("C2").WithLocation(5, 23),
// (3,23): error CS0263: Partial declarations of 'C1' must not specify different base classes
// public partial record C1 : Base<(int a, int b)> { }
Diagnostic(ErrorCode.ERR_PartialMultipleBases, "C1").WithArguments("C1").WithLocation(3, 23),
// (5,23): error CS0115: 'C2.ToString()': no suitable method found to override
// public partial record C2 : Base<(int a, int b)> { }
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.ToString()").WithLocation(5, 23),
// (5,23): error CS0115: 'C2.EqualityContract': no suitable method found to override
// public partial record C2 : Base<(int a, int b)> { }
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.EqualityContract").WithLocation(5, 23),
// (5,23): error CS0115: 'C2.Equals(object?)': no suitable method found to override
// public partial record C2 : Base<(int a, int b)> { }
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.Equals(object?)").WithLocation(5, 23),
// (5,23): error CS0115: 'C2.GetHashCode()': no suitable method found to override
// public partial record C2 : Base<(int a, int b)> { }
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.GetHashCode()").WithLocation(5, 23),
// (5,23): error CS0115: 'C2.PrintMembers(StringBuilder)': no suitable method found to override
// public partial record C2 : Base<(int a, int b)> { }
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.PrintMembers(System.Text.StringBuilder)").WithLocation(5, 23),
// (3,23): error CS0115: 'C1.ToString()': no suitable method found to override
// public partial record C1 : Base<(int a, int b)> { }
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C1").WithArguments("C1.ToString()").WithLocation(3, 23),
// (3,23): error CS0115: 'C1.EqualityContract': no suitable method found to override
// public partial record C1 : Base<(int a, int b)> { }
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C1").WithArguments("C1.EqualityContract").WithLocation(3, 23),
// (3,23): error CS0115: 'C1.Equals(object?)': no suitable method found to override
// public partial record C1 : Base<(int a, int b)> { }
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C1").WithArguments("C1.Equals(object?)").WithLocation(3, 23),
// (3,23): error CS0115: 'C1.GetHashCode()': no suitable method found to override
// public partial record C1 : Base<(int a, int b)> { }
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C1").WithArguments("C1.GetHashCode()").WithLocation(3, 23),
// (3,23): error CS0115: 'C1.PrintMembers(StringBuilder)': no suitable method found to override
// public partial record C1 : Base<(int a, int b)> { }
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C1").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(3, 23)
);
}
[Fact]
public void CS0267ERR_PartialMisplaced()
{
var test = @"
partial public record C // CS0267
{
}
";
CreateCompilation(test).VerifyDiagnostics(
// (2,1): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type.
// partial public class C // CS0267
Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(2, 1));
}
[Fact]
public void AttributeContainsGeneric()
{
string source = @"
[Goo<int>]
class G
{
}
record Goo<T>
{
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (2,2): error CS0404: Cannot apply attribute class 'Goo<T>' because it is generic
// [Goo<int>]
Diagnostic(ErrorCode.ERR_AttributeCantBeGeneric, "Goo<int>").WithArguments("Goo<T>").WithLocation(2, 2)
);
}
[Fact]
public void CS0406ERR_ClassBoundNotFirst()
{
var source =
@"interface I { }
record A { }
record B { }
class C<T, U>
where T : I, A
where U : A, B
{
void M<V>() where V : U, A, B { }
}";
CreateCompilation(source).VerifyDiagnostics(
// (5,18): error CS0406: The class type constraint 'A' must come before any other constraints
Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "A").WithArguments("A").WithLocation(5, 18),
// (6,18): error CS0406: The class type constraint 'B' must come before any other constraints
Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "B").WithArguments("B").WithLocation(6, 18),
// (8,30): error CS0406: The class type constraint 'A' must come before any other constraints
Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "A").WithArguments("A").WithLocation(8, 30),
// (8,33): error CS0406: The class type constraint 'B' must come before any other constraints
Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "B").WithArguments("B").WithLocation(8, 33));
}
[Fact]
public void SealedStaticRecord()
{
var source = @"
sealed static record R;
";
CreateCompilation(source).VerifyDiagnostics(
// (2,22): error CS0106: The modifier 'static' is not valid for this item
// sealed static record R;
Diagnostic(ErrorCode.ERR_BadMemberFlag, "R").WithArguments("static").WithLocation(2, 22)
);
}
[Fact]
public void CS0513ERR_AbstractInConcreteClass02()
{
var text = @"
record C
{
public abstract event System.Action E;
public abstract int this[int x] { get; set; }
}
";
CreateCompilation(text).VerifyDiagnostics(
// (4,41): error CS0513: 'C.E' is abstract but it is contained in non-abstract type 'C'
// public abstract event System.Action E;
Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "E").WithArguments("C.E", "C"),
// (5,39): error CS0513: 'C.this[int].get' is abstract but it is contained in non-abstract type 'C'
// public abstract int this[int x] { get; set; }
Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "get").WithArguments("C.this[int].get", "C"),
// (5,44): error CS0513: 'C.this[int].set' is abstract but it is contained in non-abstract type 'C'
// public abstract int this[int x] { get; set; }
Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "set").WithArguments("C.this[int].set", "C"));
}
[Fact]
public void ConversionToBase()
{
var source = @"
public record Base<T> { }
public record Derived : Base<(int a, int b)>
{
public static explicit operator Base<(int, int)>(Derived x)
{
return null;
}
public static explicit operator Derived(Base<(int, int)> x)
{
return null;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (9,37): error CS0553: 'Derived.explicit operator Derived(Base<(int, int)>)': user-defined conversions to or from a base type are not allowed
// public static explicit operator Derived(Base<(int, int)> x)
Diagnostic(ErrorCode.ERR_ConversionWithBase, "Derived").WithArguments("Derived.explicit operator Derived(Base<(int, int)>)").WithLocation(9, 37),
// (5,37): error CS0553: 'Derived.explicit operator Base<(int, int)>(Derived)': user-defined conversions to or from a base type are not allowed
// public static explicit operator Base<(int, int)>(Derived x)
Diagnostic(ErrorCode.ERR_ConversionWithBase, "Base<(int, int)>").WithArguments("Derived.explicit operator Base<(int, int)>(Derived)").WithLocation(5, 37)
);
}
[Fact]
public void CS0554ERR_ConversionWithDerived()
{
var text = @"
public record B
{
public static implicit operator B(D d) // CS0554
{
return null;
}
}
public record D : B {}
";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (4,37): error CS0554: 'B.implicit operator B(D)': user-defined conversions to or from a derived type are not allowed
// public static implicit operator B(D d) // CS0554
Diagnostic(ErrorCode.ERR_ConversionWithDerived, "B").WithArguments("B.implicit operator B(D)")
);
}
[Fact]
public void CS0574ERR_BadDestructorName()
{
var test = @"
namespace x
{
public record iii
{
~iiii(){}
public static void Main()
{
}
}
}
";
CreateCompilation(test).VerifyDiagnostics(
// (6,10): error CS0574: Name of destructor must match name of type
// ~iiii(){}
Diagnostic(ErrorCode.ERR_BadDestructorName, "iiii").WithLocation(6, 10));
}
[Fact]
public void StaticBasePartial()
{
var text = @"
static record NV
{
}
public partial record C1
{
}
partial record C1 : NV
{
}
public partial record C1
{
}
";
var comp = CreateCompilation(text, targetFramework: TargetFramework.StandardLatest);
Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses);
if (comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses)
{
comp.VerifyDiagnostics(
// (2,15): error CS0106: The modifier 'static' is not valid for this item
// static record NV
Diagnostic(ErrorCode.ERR_BadMemberFlag, "NV").WithArguments("static").WithLocation(2, 15),
// (6,23): error CS0051: Inconsistent accessibility: parameter type 'NV' is less accessible than method 'C1.Equals(NV?)'
// public partial record C1
Diagnostic(ErrorCode.ERR_BadVisParamType, "C1").WithArguments("C1.Equals(NV?)", "NV").WithLocation(6, 23),
// (10,16): error CS0060: Inconsistent accessibility: base class 'NV' is less accessible than class 'C1'
// partial record C1 : NV
Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C1").WithArguments("C1", "NV").WithLocation(10, 16)
);
}
else
{
comp.VerifyDiagnostics(
// (2,15): error CS0106: The modifier 'static' is not valid for this item
// static record NV
Diagnostic(ErrorCode.ERR_BadMemberFlag, "NV").WithArguments("static").WithLocation(2, 15),
// (6,23): error CS0050: Inconsistent accessibility: return type 'NV' is less accessible than method 'C1.<Clone>$()'
// public partial record C1
Diagnostic(ErrorCode.ERR_BadVisReturnType, "C1").WithArguments("C1.<Clone>$()", "NV").WithLocation(6, 23),
// (6,23): error CS0051: Inconsistent accessibility: parameter type 'NV' is less accessible than method 'C1.Equals(NV?)'
// public partial record C1
Diagnostic(ErrorCode.ERR_BadVisParamType, "C1").WithArguments("C1.Equals(NV?)", "NV").WithLocation(6, 23),
// (10,16): error CS0060: Inconsistent accessibility: base class 'NV' is less accessible than class 'C1'
// partial record C1 : NV
Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C1").WithArguments("C1", "NV").WithLocation(10, 16)
);
}
}
[Fact]
public void StaticRecordWithConstructorAndDestructor()
{
var text = @"
static record R(int I)
{
R() : this(0) { }
~R() { }
}
";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (2,15): error CS0106: The modifier 'static' is not valid for this item
// static record R(int I)
Diagnostic(ErrorCode.ERR_BadMemberFlag, "R").WithArguments("static").WithLocation(2, 15)
);
}
[Fact]
public void RecordWithPartialMethodExplicitImplementation()
{
var source =
@"record R
{
partial void M();
}";
CreateCompilation(source).VerifyDiagnostics(
// (3,18): error CS0751: A partial method must be declared within a partial type
// partial void M();
Diagnostic(ErrorCode.ERR_PartialMethodOnlyInPartialClass, "M").WithLocation(3, 18)
);
}
[Fact]
public void RecordWithMultipleBaseTypes()
{
var source = @"
record Base1;
record Base2;
record R : Base1, Base2
{
}";
CreateCompilation(source).VerifyDiagnostics(
// (4,19): error CS1721: Class 'R' cannot have multiple base classes: 'Base1' and 'Base2'
// record R : Base1, Base2
Diagnostic(ErrorCode.ERR_NoMultipleInheritance, "Base2").WithArguments("R", "Base1", "Base2").WithLocation(4, 19)
);
}
[Fact]
public void RecordWithInterfaceBeforeBase()
{
var source = @"
record Base;
interface I { }
record R : I, Base;
";
CreateCompilation(source).VerifyDiagnostics(
// (4,15): error CS1722: Base class 'Base' must come before any interfaces
// record R : I, Base;
Diagnostic(ErrorCode.ERR_BaseClassMustBeFirst, "Base").WithArguments("Base").WithLocation(4, 15)
);
}
[Fact]
public void RecordLoadedInVisualBasicDisplaysAsClass()
{
var src = @"
public record A;
";
var compRef = CreateCompilation(src).EmitToImageReference();
var vbComp = CreateVisualBasicCompilation("", referencedAssemblies: new[] { compRef });
var symbol = vbComp.GlobalNamespace.GetTypeMember("A");
Assert.False(symbol.IsRecord);
Assert.Equal("class A",
SymbolDisplay.ToDisplayString(symbol, SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword)));
}
[Fact]
public void AnalyzerActions_01()
{
var text1 = @"
record A([Attr1]int X = 0) : I1
{}
record B([Attr2]int Y = 1) : A(2), I1
{
int M() => 3;
}
record C : A, I1
{
C([Attr3]int Z = 4) : base(5)
{}
}
interface I1 {}
class Attr1 : System.Attribute {}
class Attr2 : System.Attribute {}
class Attr3 : System.Attribute {}
";
var analyzer = new AnalyzerActions_01_Analyzer();
var comp = CreateCompilation(text1);
comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify();
Assert.Equal(1, analyzer.FireCount0);
Assert.Equal(1, analyzer.FireCount1);
Assert.Equal(1, analyzer.FireCount2);
Assert.Equal(1, analyzer.FireCount3);
Assert.Equal(1, analyzer.FireCount4);
Assert.Equal(1, analyzer.FireCount5);
Assert.Equal(1, analyzer.FireCount6);
Assert.Equal(1, analyzer.FireCount7);
Assert.Equal(1, analyzer.FireCount8);
Assert.Equal(1, analyzer.FireCount9);
Assert.Equal(1, analyzer.FireCount10);
Assert.Equal(1, analyzer.FireCount11);
Assert.Equal(1, analyzer.FireCount12);
Assert.Equal(1, analyzer.FireCount13);
Assert.Equal(1, analyzer.FireCount14);
Assert.Equal(1, analyzer.FireCount15);
Assert.Equal(1, analyzer.FireCount16);
Assert.Equal(1, analyzer.FireCount17);
Assert.Equal(1, analyzer.FireCount18);
Assert.Equal(1, analyzer.FireCount19);
Assert.Equal(1, analyzer.FireCount20);
Assert.Equal(1, analyzer.FireCount21);
Assert.Equal(1, analyzer.FireCount22);
Assert.Equal(1, analyzer.FireCount23);
Assert.Equal(1, analyzer.FireCount24);
Assert.Equal(1, analyzer.FireCount25);
Assert.Equal(1, analyzer.FireCount26);
Assert.Equal(1, analyzer.FireCount27);
Assert.Equal(1, analyzer.FireCount28);
Assert.Equal(1, analyzer.FireCount29);
Assert.Equal(1, analyzer.FireCount30);
Assert.Equal(1, analyzer.FireCount31);
}
private class AnalyzerActions_01_Analyzer : DiagnosticAnalyzer
{
public int FireCount0;
public int FireCount1;
public int FireCount2;
public int FireCount3;
public int FireCount4;
public int FireCount5;
public int FireCount6;
public int FireCount7;
public int FireCount8;
public int FireCount9;
public int FireCount10;
public int FireCount11;
public int FireCount12;
public int FireCount13;
public int FireCount14;
public int FireCount15;
public int FireCount16;
public int FireCount17;
public int FireCount18;
public int FireCount19;
public int FireCount20;
public int FireCount21;
public int FireCount22;
public int FireCount23;
public int FireCount24;
public int FireCount25;
public int FireCount26;
public int FireCount27;
public int FireCount28;
public int FireCount29;
public int FireCount30;
public int FireCount31;
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.NumericLiteralExpression);
context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.EqualsValueClause);
context.RegisterSyntaxNodeAction(Handle3, SyntaxKind.BaseConstructorInitializer);
context.RegisterSyntaxNodeAction(Handle4, SyntaxKind.ConstructorDeclaration);
context.RegisterSyntaxNodeAction(Handle5, SyntaxKind.PrimaryConstructorBaseType);
context.RegisterSyntaxNodeAction(Handle6, SyntaxKind.RecordDeclaration);
context.RegisterSyntaxNodeAction(Handle7, SyntaxKind.IdentifierName);
context.RegisterSyntaxNodeAction(Handle8, SyntaxKind.SimpleBaseType);
context.RegisterSyntaxNodeAction(Handle9, SyntaxKind.ParameterList);
context.RegisterSyntaxNodeAction(Handle10, SyntaxKind.ArgumentList);
}
protected void Handle1(SyntaxNodeAnalysisContext context)
{
var literal = (LiteralExpressionSyntax)context.Node;
switch (literal.ToString())
{
case "0":
Interlocked.Increment(ref FireCount0);
Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString());
break;
case "1":
Interlocked.Increment(ref FireCount1);
Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString());
break;
case "2":
Interlocked.Increment(ref FireCount2);
Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString());
break;
case "3":
Interlocked.Increment(ref FireCount3);
Assert.Equal("System.Int32 B.M()", context.ContainingSymbol.ToTestDisplayString());
break;
case "4":
Interlocked.Increment(ref FireCount4);
Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString());
break;
case "5":
Interlocked.Increment(ref FireCount5);
Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString());
break;
default:
Assert.True(false);
break;
}
Assert.Same(literal.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree);
}
protected void Handle2(SyntaxNodeAnalysisContext context)
{
var equalsValue = (EqualsValueClauseSyntax)context.Node;
switch (equalsValue.ToString())
{
case "= 0":
Interlocked.Increment(ref FireCount15);
Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString());
break;
case "= 1":
Interlocked.Increment(ref FireCount16);
Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString());
break;
case "= 4":
Interlocked.Increment(ref FireCount6);
Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString());
break;
default:
Assert.True(false);
break;
}
Assert.Same(equalsValue.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree);
}
protected void Handle3(SyntaxNodeAnalysisContext context)
{
var initializer = (ConstructorInitializerSyntax)context.Node;
switch (initializer.ToString())
{
case ": base(5)":
Interlocked.Increment(ref FireCount7);
Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString());
break;
default:
Assert.True(false);
break;
}
Assert.Same(initializer.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree);
}
protected void Handle4(SyntaxNodeAnalysisContext context)
{
Interlocked.Increment(ref FireCount8);
Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString());
}
protected void Handle5(SyntaxNodeAnalysisContext context)
{
var baseType = (PrimaryConstructorBaseTypeSyntax)context.Node;
switch (baseType.ToString())
{
case "A(2)":
switch (context.ContainingSymbol.ToTestDisplayString())
{
case "B..ctor([System.Int32 Y = 1])":
Interlocked.Increment(ref FireCount9);
break;
case "B":
Interlocked.Increment(ref FireCount17);
break;
default:
Assert.True(false);
break;
}
break;
default:
Assert.True(false);
break;
}
Assert.Same(baseType.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree);
}
protected void Handle6(SyntaxNodeAnalysisContext context)
{
var record = (RecordDeclarationSyntax)context.Node;
switch (context.ContainingSymbol.ToTestDisplayString())
{
case "B..ctor([System.Int32 Y = 1])":
Interlocked.Increment(ref FireCount10);
break;
case "B":
Interlocked.Increment(ref FireCount11);
break;
case "A":
Interlocked.Increment(ref FireCount12);
break;
case "C":
Interlocked.Increment(ref FireCount13);
break;
case "A..ctor([System.Int32 X = 0])":
Interlocked.Increment(ref FireCount14);
break;
default:
Assert.True(false);
break;
}
Assert.Same(record.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree);
}
protected void Handle7(SyntaxNodeAnalysisContext context)
{
var identifier = (IdentifierNameSyntax)context.Node;
switch (identifier.Identifier.ValueText)
{
case "A":
switch (identifier.Parent!.ToString())
{
case "A(2)":
Interlocked.Increment(ref FireCount18);
Assert.Equal("B", context.ContainingSymbol.ToTestDisplayString());
break;
case "A":
Interlocked.Increment(ref FireCount19);
Assert.Equal(SyntaxKind.SimpleBaseType, identifier.Parent.Kind());
Assert.Equal("C", context.ContainingSymbol.ToTestDisplayString());
break;
default:
Assert.True(false);
break;
}
break;
case "Attr1":
Interlocked.Increment(ref FireCount24);
Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString());
break;
case "Attr2":
Interlocked.Increment(ref FireCount25);
Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString());
break;
case "Attr3":
Interlocked.Increment(ref FireCount26);
Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString());
break;
}
}
protected void Handle8(SyntaxNodeAnalysisContext context)
{
var baseType = (SimpleBaseTypeSyntax)context.Node;
switch (baseType.ToString())
{
case "I1":
switch (context.ContainingSymbol.ToTestDisplayString())
{
case "A":
Interlocked.Increment(ref FireCount20);
break;
case "B":
Interlocked.Increment(ref FireCount21);
break;
case "C":
Interlocked.Increment(ref FireCount22);
break;
default:
Assert.True(false);
break;
}
break;
case "A":
switch (context.ContainingSymbol.ToTestDisplayString())
{
case "C":
Interlocked.Increment(ref FireCount23);
break;
default:
Assert.True(false);
break;
}
break;
case "System.Attribute":
break;
default:
Assert.True(false);
break;
}
}
protected void Handle9(SyntaxNodeAnalysisContext context)
{
var parameterList = (ParameterListSyntax)context.Node;
switch (parameterList.ToString())
{
case "([Attr1]int X = 0)":
Interlocked.Increment(ref FireCount27);
Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString());
break;
case "([Attr2]int Y = 1)":
Interlocked.Increment(ref FireCount28);
Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString());
break;
case "([Attr3]int Z = 4)":
Interlocked.Increment(ref FireCount29);
Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString());
break;
case "()":
break;
default:
Assert.True(false);
break;
}
}
protected void Handle10(SyntaxNodeAnalysisContext context)
{
var argumentList = (ArgumentListSyntax)context.Node;
switch (argumentList.ToString())
{
case "(2)":
Interlocked.Increment(ref FireCount30);
Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString());
break;
case "(5)":
Interlocked.Increment(ref FireCount31);
Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString());
break;
default:
Assert.True(false);
break;
}
}
}
[Fact]
public void AnalyzerActions_02()
{
var text1 = @"
record A(int X = 0)
{}
record C
{
C(int Z = 4)
{}
}
";
var analyzer = new AnalyzerActions_02_Analyzer();
var comp = CreateCompilation(text1);
comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify();
Assert.Equal(1, analyzer.FireCount1);
Assert.Equal(1, analyzer.FireCount2);
Assert.Equal(1, analyzer.FireCount3);
Assert.Equal(1, analyzer.FireCount4);
Assert.Equal(1, analyzer.FireCount5);
Assert.Equal(1, analyzer.FireCount6);
Assert.Equal(1, analyzer.FireCount7);
}
private class AnalyzerActions_02_Analyzer : DiagnosticAnalyzer
{
public int FireCount1;
public int FireCount2;
public int FireCount3;
public int FireCount4;
public int FireCount5;
public int FireCount6;
public int FireCount7;
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterSymbolAction(Handle, SymbolKind.Method);
context.RegisterSymbolAction(Handle, SymbolKind.Property);
context.RegisterSymbolAction(Handle, SymbolKind.Parameter);
context.RegisterSymbolAction(Handle, SymbolKind.NamedType);
}
private void Handle(SymbolAnalysisContext context)
{
switch (context.Symbol.ToTestDisplayString())
{
case "A..ctor([System.Int32 X = 0])":
Interlocked.Increment(ref FireCount1);
break;
case "System.Int32 A.X { get; init; }":
Interlocked.Increment(ref FireCount2);
break;
case "[System.Int32 X = 0]":
Interlocked.Increment(ref FireCount3);
break;
case "C..ctor([System.Int32 Z = 4])":
Interlocked.Increment(ref FireCount4);
break;
case "[System.Int32 Z = 4]":
Interlocked.Increment(ref FireCount5);
break;
case "A":
Interlocked.Increment(ref FireCount6);
break;
case "C":
Interlocked.Increment(ref FireCount7);
break;
case "System.Runtime.CompilerServices.IsExternalInit":
break;
default:
Assert.True(false);
break;
}
}
}
[Fact]
public void AnalyzerActions_03()
{
var text1 = @"
record A(int X = 0)
{}
record C
{
C(int Z = 4)
{}
}
";
var analyzer = new AnalyzerActions_03_Analyzer();
var comp = CreateCompilation(text1);
comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify();
Assert.Equal(1, analyzer.FireCount1);
Assert.Equal(1, analyzer.FireCount2);
Assert.Equal(0, analyzer.FireCount3);
Assert.Equal(1, analyzer.FireCount4);
Assert.Equal(0, analyzer.FireCount5);
Assert.Equal(1, analyzer.FireCount6);
Assert.Equal(1, analyzer.FireCount7);
Assert.Equal(1, analyzer.FireCount8);
Assert.Equal(1, analyzer.FireCount9);
Assert.Equal(1, analyzer.FireCount10);
Assert.Equal(1, analyzer.FireCount11);
Assert.Equal(1, analyzer.FireCount12);
}
private class AnalyzerActions_03_Analyzer : DiagnosticAnalyzer
{
public int FireCount1;
public int FireCount2;
public int FireCount3;
public int FireCount4;
public int FireCount5;
public int FireCount6;
public int FireCount7;
public int FireCount8;
public int FireCount9;
public int FireCount10;
public int FireCount11;
public int FireCount12;
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterSymbolStartAction(Handle1, SymbolKind.Method);
context.RegisterSymbolStartAction(Handle1, SymbolKind.Property);
context.RegisterSymbolStartAction(Handle1, SymbolKind.Parameter);
context.RegisterSymbolStartAction(Handle1, SymbolKind.NamedType);
}
private void Handle1(SymbolStartAnalysisContext context)
{
switch (context.Symbol.ToTestDisplayString())
{
case "A..ctor([System.Int32 X = 0])":
Interlocked.Increment(ref FireCount1);
context.RegisterSymbolEndAction(Handle2);
break;
case "System.Int32 A.X { get; init; }":
Interlocked.Increment(ref FireCount2);
context.RegisterSymbolEndAction(Handle3);
break;
case "[System.Int32 X = 0]":
Interlocked.Increment(ref FireCount3);
break;
case "C..ctor([System.Int32 Z = 4])":
Interlocked.Increment(ref FireCount4);
context.RegisterSymbolEndAction(Handle4);
break;
case "[System.Int32 Z = 4]":
Interlocked.Increment(ref FireCount5);
break;
case "A":
Interlocked.Increment(ref FireCount9);
Assert.Equal(0, FireCount1);
Assert.Equal(0, FireCount2);
Assert.Equal(0, FireCount6);
Assert.Equal(0, FireCount7);
context.RegisterSymbolEndAction(Handle5);
break;
case "C":
Interlocked.Increment(ref FireCount10);
Assert.Equal(0, FireCount4);
Assert.Equal(0, FireCount8);
context.RegisterSymbolEndAction(Handle6);
break;
case "System.Runtime.CompilerServices.IsExternalInit":
break;
default:
Assert.True(false);
break;
}
}
private void Handle2(SymbolAnalysisContext context)
{
Assert.Equal("A..ctor([System.Int32 X = 0])", context.Symbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount6);
}
private void Handle3(SymbolAnalysisContext context)
{
Assert.Equal("System.Int32 A.X { get; init; }", context.Symbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount7);
}
private void Handle4(SymbolAnalysisContext context)
{
Assert.Equal("C..ctor([System.Int32 Z = 4])", context.Symbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount8);
}
private void Handle5(SymbolAnalysisContext context)
{
Assert.Equal("A", context.Symbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount11);
Assert.Equal(1, FireCount1);
Assert.Equal(1, FireCount2);
Assert.Equal(1, FireCount6);
Assert.Equal(1, FireCount7);
}
private void Handle6(SymbolAnalysisContext context)
{
Assert.Equal("C", context.Symbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount12);
Assert.Equal(1, FireCount4);
Assert.Equal(1, FireCount8);
}
}
[Fact]
public void AnalyzerActions_04()
{
var text1 = @"
record A([Attr1(100)]int X = 0) : I1
{}
record B([Attr2(200)]int Y = 1) : A(2), I1
{
int M() => 3;
}
record C : A, I1
{
C([Attr3(300)]int Z = 4) : base(5)
{}
}
interface I1 {}
";
var analyzer = new AnalyzerActions_04_Analyzer();
var comp = CreateCompilation(text1);
comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify();
Assert.Equal(0, analyzer.FireCount1);
Assert.Equal(1, analyzer.FireCount2);
Assert.Equal(1, analyzer.FireCount3);
Assert.Equal(1, analyzer.FireCount4);
Assert.Equal(1, analyzer.FireCount5);
Assert.Equal(1, analyzer.FireCount6);
Assert.Equal(1, analyzer.FireCount7);
Assert.Equal(1, analyzer.FireCount8);
Assert.Equal(1, analyzer.FireCount9);
Assert.Equal(1, analyzer.FireCount10);
Assert.Equal(1, analyzer.FireCount11);
Assert.Equal(1, analyzer.FireCount12);
Assert.Equal(1, analyzer.FireCount13);
Assert.Equal(1, analyzer.FireCount14);
Assert.Equal(1, analyzer.FireCount15);
Assert.Equal(1, analyzer.FireCount16);
Assert.Equal(1, analyzer.FireCount17);
}
private class AnalyzerActions_04_Analyzer : DiagnosticAnalyzer
{
public int FireCount1;
public int FireCount2;
public int FireCount3;
public int FireCount4;
public int FireCount5;
public int FireCount6;
public int FireCount7;
public int FireCount8;
public int FireCount9;
public int FireCount10;
public int FireCount11;
public int FireCount12;
public int FireCount13;
public int FireCount14;
public int FireCount15;
public int FireCount16;
public int FireCount17;
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(Handle1, OperationKind.ConstructorBody);
context.RegisterOperationAction(Handle2, OperationKind.Invocation);
context.RegisterOperationAction(Handle3, OperationKind.Literal);
context.RegisterOperationAction(Handle4, OperationKind.ParameterInitializer);
context.RegisterOperationAction(Handle5, OperationKind.PropertyInitializer);
context.RegisterOperationAction(Handle5, OperationKind.FieldInitializer);
}
protected void Handle1(OperationAnalysisContext context)
{
switch (context.ContainingSymbol.ToTestDisplayString())
{
case "A..ctor([System.Int32 X = 0])":
Interlocked.Increment(ref FireCount1);
Assert.Equal(SyntaxKind.RecordDeclaration, context.Operation.Syntax.Kind());
break;
case "B..ctor([System.Int32 Y = 1])":
Interlocked.Increment(ref FireCount2);
Assert.Equal(SyntaxKind.RecordDeclaration, context.Operation.Syntax.Kind());
break;
case "C..ctor([System.Int32 Z = 4])":
Interlocked.Increment(ref FireCount3);
Assert.Equal(SyntaxKind.ConstructorDeclaration, context.Operation.Syntax.Kind());
break;
default:
Assert.True(false);
break;
}
}
protected void Handle2(OperationAnalysisContext context)
{
switch (context.ContainingSymbol.ToTestDisplayString())
{
case "B..ctor([System.Int32 Y = 1])":
Interlocked.Increment(ref FireCount4);
Assert.Equal(SyntaxKind.PrimaryConstructorBaseType, context.Operation.Syntax.Kind());
VerifyOperationTree((CSharpCompilation)context.Compilation, context.Operation,
@"
IInvocationOperation ( A..ctor([System.Int32 X = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'A(2)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'A(2)')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
break;
case "C..ctor([System.Int32 Z = 4])":
Interlocked.Increment(ref FireCount5);
Assert.Equal(SyntaxKind.BaseConstructorInitializer, context.Operation.Syntax.Kind());
VerifyOperationTree((CSharpCompilation)context.Compilation, context.Operation,
@"
IInvocationOperation ( A..ctor([System.Int32 X = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: ': base(5)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: ': base(5)')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: '5')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
break;
default:
Assert.True(false);
break;
}
}
protected void Handle3(OperationAnalysisContext context)
{
switch (context.Operation.Syntax.ToString())
{
case "100":
Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount6);
break;
case "0":
Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount7);
break;
case "200":
Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount8);
break;
case "1":
Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount9);
break;
case "2":
Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount10);
break;
case "300":
Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount11);
break;
case "4":
Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount12);
break;
case "5":
Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount13);
break;
case "3":
Assert.Equal("System.Int32 B.M()", context.ContainingSymbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount17);
break;
default:
Assert.True(false);
break;
}
}
protected void Handle4(OperationAnalysisContext context)
{
switch (context.Operation.Syntax.ToString())
{
case "= 0":
Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount14);
break;
case "= 1":
Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount15);
break;
case "= 4":
Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount16);
break;
default:
Assert.True(false);
break;
}
}
protected void Handle5(OperationAnalysisContext context)
{
Assert.True(false);
}
}
[Fact]
public void AnalyzerActions_05()
{
var text1 = @"
record A([Attr1(100)]int X = 0) : I1
{}
record B([Attr2(200)]int Y = 1) : A(2), I1
{
int M() => 3;
}
record C : A, I1
{
C([Attr3(300)]int Z = 4) : base(5)
{}
}
interface I1 {}
";
var analyzer = new AnalyzerActions_05_Analyzer();
var comp = CreateCompilation(text1);
comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify();
Assert.Equal(1, analyzer.FireCount1);
Assert.Equal(1, analyzer.FireCount2);
Assert.Equal(1, analyzer.FireCount3);
Assert.Equal(1, analyzer.FireCount4);
}
private class AnalyzerActions_05_Analyzer : DiagnosticAnalyzer
{
public int FireCount1;
public int FireCount2;
public int FireCount3;
public int FireCount4;
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterOperationBlockAction(Handle);
}
private void Handle(OperationBlockAnalysisContext context)
{
switch (context.OwningSymbol.ToTestDisplayString())
{
case "A..ctor([System.Int32 X = 0])":
Interlocked.Increment(ref FireCount1);
Assert.Equal(2, context.OperationBlocks.Length);
Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind);
Assert.Equal("= 0", context.OperationBlocks[0].Syntax.ToString());
Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind);
Assert.Equal("Attr1(100)", context.OperationBlocks[1].Syntax.ToString());
break;
case "B..ctor([System.Int32 Y = 1])":
Interlocked.Increment(ref FireCount2);
Assert.Equal(3, context.OperationBlocks.Length);
Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind);
Assert.Equal("= 1", context.OperationBlocks[0].Syntax.ToString());
Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind);
Assert.Equal("Attr2(200)", context.OperationBlocks[1].Syntax.ToString());
Assert.Equal(OperationKind.Invocation, context.OperationBlocks[2].Kind);
Assert.Equal("A(2)", context.OperationBlocks[2].Syntax.ToString());
break;
case "C..ctor([System.Int32 Z = 4])":
Interlocked.Increment(ref FireCount3);
Assert.Equal(4, context.OperationBlocks.Length);
Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind);
Assert.Equal("= 4", context.OperationBlocks[0].Syntax.ToString());
Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind);
Assert.Equal("Attr3(300)", context.OperationBlocks[1].Syntax.ToString());
Assert.Equal(OperationKind.Block, context.OperationBlocks[2].Kind);
Assert.Equal(OperationKind.Invocation, context.OperationBlocks[3].Kind);
Assert.Equal(": base(5)", context.OperationBlocks[3].Syntax.ToString());
break;
case "System.Int32 B.M()":
Interlocked.Increment(ref FireCount4);
Assert.Equal(1, context.OperationBlocks.Length);
Assert.Equal(OperationKind.Block, context.OperationBlocks[0].Kind);
break;
default:
Assert.True(false);
break;
}
}
}
[Fact]
public void AnalyzerActions_06()
{
var text1 = @"
record A([Attr1(100)]int X = 0) : I1
{}
record B([Attr2(200)]int Y = 1) : A(2), I1
{
int M() => 3;
}
record C : A, I1
{
C([Attr3(300)]int Z = 4) : base(5)
{}
}
interface I1 {}
";
var analyzer = new AnalyzerActions_06_Analyzer();
var comp = CreateCompilation(text1);
comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify();
Assert.Equal(1, analyzer.FireCount100);
Assert.Equal(1, analyzer.FireCount200);
Assert.Equal(1, analyzer.FireCount300);
Assert.Equal(1, analyzer.FireCount400);
Assert.Equal(0, analyzer.FireCount1);
Assert.Equal(1, analyzer.FireCount2);
Assert.Equal(1, analyzer.FireCount3);
Assert.Equal(1, analyzer.FireCount4);
Assert.Equal(1, analyzer.FireCount5);
Assert.Equal(1, analyzer.FireCount6);
Assert.Equal(1, analyzer.FireCount7);
Assert.Equal(1, analyzer.FireCount8);
Assert.Equal(1, analyzer.FireCount9);
Assert.Equal(1, analyzer.FireCount10);
Assert.Equal(1, analyzer.FireCount11);
Assert.Equal(1, analyzer.FireCount12);
Assert.Equal(1, analyzer.FireCount13);
Assert.Equal(1, analyzer.FireCount14);
Assert.Equal(1, analyzer.FireCount15);
Assert.Equal(1, analyzer.FireCount16);
Assert.Equal(1, analyzer.FireCount17);
Assert.Equal(1, analyzer.FireCount1000);
Assert.Equal(1, analyzer.FireCount2000);
Assert.Equal(1, analyzer.FireCount3000);
Assert.Equal(1, analyzer.FireCount4000);
}
private class AnalyzerActions_06_Analyzer : AnalyzerActions_04_Analyzer
{
public int FireCount100;
public int FireCount200;
public int FireCount300;
public int FireCount400;
public int FireCount1000;
public int FireCount2000;
public int FireCount3000;
public int FireCount4000;
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterOperationBlockStartAction(Handle);
}
private void Handle(OperationBlockStartAnalysisContext context)
{
switch (context.OwningSymbol.ToTestDisplayString())
{
case "A..ctor([System.Int32 X = 0])":
Interlocked.Increment(ref FireCount100);
Assert.Equal(2, context.OperationBlocks.Length);
Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind);
Assert.Equal("= 0", context.OperationBlocks[0].Syntax.ToString());
Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind);
Assert.Equal("Attr1(100)", context.OperationBlocks[1].Syntax.ToString());
RegisterOperationAction(context);
context.RegisterOperationBlockEndAction(Handle6);
break;
case "B..ctor([System.Int32 Y = 1])":
Interlocked.Increment(ref FireCount200);
Assert.Equal(3, context.OperationBlocks.Length);
Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind);
Assert.Equal("= 1", context.OperationBlocks[0].Syntax.ToString());
Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind);
Assert.Equal("Attr2(200)", context.OperationBlocks[1].Syntax.ToString());
Assert.Equal(OperationKind.Invocation, context.OperationBlocks[2].Kind);
Assert.Equal("A(2)", context.OperationBlocks[2].Syntax.ToString());
RegisterOperationAction(context);
context.RegisterOperationBlockEndAction(Handle6);
break;
case "C..ctor([System.Int32 Z = 4])":
Interlocked.Increment(ref FireCount300);
Assert.Equal(4, context.OperationBlocks.Length);
Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind);
Assert.Equal("= 4", context.OperationBlocks[0].Syntax.ToString());
Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind);
Assert.Equal("Attr3(300)", context.OperationBlocks[1].Syntax.ToString());
Assert.Equal(OperationKind.Block, context.OperationBlocks[2].Kind);
Assert.Equal(OperationKind.Invocation, context.OperationBlocks[3].Kind);
Assert.Equal(": base(5)", context.OperationBlocks[3].Syntax.ToString());
RegisterOperationAction(context);
context.RegisterOperationBlockEndAction(Handle6);
break;
case "System.Int32 B.M()":
Interlocked.Increment(ref FireCount400);
Assert.Equal(1, context.OperationBlocks.Length);
Assert.Equal(OperationKind.Block, context.OperationBlocks[0].Kind);
RegisterOperationAction(context);
context.RegisterOperationBlockEndAction(Handle6);
break;
default:
Assert.True(false);
break;
}
}
private void RegisterOperationAction(OperationBlockStartAnalysisContext context)
{
context.RegisterOperationAction(Handle1, OperationKind.ConstructorBody);
context.RegisterOperationAction(Handle2, OperationKind.Invocation);
context.RegisterOperationAction(Handle3, OperationKind.Literal);
context.RegisterOperationAction(Handle4, OperationKind.ParameterInitializer);
context.RegisterOperationAction(Handle5, OperationKind.PropertyInitializer);
context.RegisterOperationAction(Handle5, OperationKind.FieldInitializer);
}
private void Handle6(OperationBlockAnalysisContext context)
{
switch (context.OwningSymbol.ToTestDisplayString())
{
case "A..ctor([System.Int32 X = 0])":
Interlocked.Increment(ref FireCount1000);
Assert.Equal(2, context.OperationBlocks.Length);
Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind);
Assert.Equal("= 0", context.OperationBlocks[0].Syntax.ToString());
Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind);
Assert.Equal("Attr1(100)", context.OperationBlocks[1].Syntax.ToString());
break;
case "B..ctor([System.Int32 Y = 1])":
Interlocked.Increment(ref FireCount2000);
Assert.Equal(3, context.OperationBlocks.Length);
Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind);
Assert.Equal("= 1", context.OperationBlocks[0].Syntax.ToString());
Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind);
Assert.Equal("Attr2(200)", context.OperationBlocks[1].Syntax.ToString());
Assert.Equal(OperationKind.Invocation, context.OperationBlocks[2].Kind);
Assert.Equal("A(2)", context.OperationBlocks[2].Syntax.ToString());
break;
case "C..ctor([System.Int32 Z = 4])":
Interlocked.Increment(ref FireCount3000);
Assert.Equal(4, context.OperationBlocks.Length);
Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind);
Assert.Equal("= 4", context.OperationBlocks[0].Syntax.ToString());
Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind);
Assert.Equal("Attr3(300)", context.OperationBlocks[1].Syntax.ToString());
Assert.Equal(OperationKind.Block, context.OperationBlocks[2].Kind);
Assert.Equal(OperationKind.Invocation, context.OperationBlocks[3].Kind);
Assert.Equal(": base(5)", context.OperationBlocks[3].Syntax.ToString());
break;
case "System.Int32 B.M()":
Interlocked.Increment(ref FireCount4000);
Assert.Equal(1, context.OperationBlocks.Length);
Assert.Equal(OperationKind.Block, context.OperationBlocks[0].Kind);
break;
default:
Assert.True(false);
break;
}
}
}
[Fact]
public void AnalyzerActions_07()
{
var text1 = @"
record A([Attr1(100)]int X = 0) : I1
{}
record B([Attr2(200)]int Y = 1) : A(2), I1
{
int M() => 3;
}
record C : A, I1
{
C([Attr3(300)]int Z = 4) : base(5)
{}
}
interface I1 {}
";
var analyzer = new AnalyzerActions_07_Analyzer();
var comp = CreateCompilation(text1);
comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify();
Assert.Equal(1, analyzer.FireCount1);
Assert.Equal(1, analyzer.FireCount2);
Assert.Equal(1, analyzer.FireCount3);
Assert.Equal(1, analyzer.FireCount4);
}
private class AnalyzerActions_07_Analyzer : DiagnosticAnalyzer
{
public int FireCount1;
public int FireCount2;
public int FireCount3;
public int FireCount4;
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterCodeBlockAction(Handle);
}
private void Handle(CodeBlockAnalysisContext context)
{
switch (context.OwningSymbol.ToTestDisplayString())
{
case "A..ctor([System.Int32 X = 0])":
switch (context.CodeBlock)
{
case RecordDeclarationSyntax { Identifier: { ValueText: "A" } }:
Interlocked.Increment(ref FireCount1);
break;
default:
Assert.True(false);
break;
}
break;
case "B..ctor([System.Int32 Y = 1])":
switch (context.CodeBlock)
{
case RecordDeclarationSyntax { Identifier: { ValueText: "B" } }:
Interlocked.Increment(ref FireCount2);
break;
default:
Assert.True(false);
break;
}
break;
case "C..ctor([System.Int32 Z = 4])":
switch (context.CodeBlock)
{
case ConstructorDeclarationSyntax { Identifier: { ValueText: "C" } }:
Interlocked.Increment(ref FireCount3);
break;
default:
Assert.True(false);
break;
}
break;
case "System.Int32 B.M()":
switch (context.CodeBlock)
{
case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }:
Interlocked.Increment(ref FireCount4);
break;
default:
Assert.True(false);
break;
}
break;
default:
Assert.True(false);
break;
}
}
}
[Fact]
public void AnalyzerActions_08()
{
var text1 = @"
record A([Attr1]int X = 0) : I1
{}
record B([Attr2]int Y = 1) : A(2), I1
{
int M() => 3;
}
record C : A, I1
{
C([Attr3]int Z = 4) : base(5)
{}
}
interface I1 {}
";
var analyzer = new AnalyzerActions_08_Analyzer();
var comp = CreateCompilation(text1);
comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify();
Assert.Equal(1, analyzer.FireCount100);
Assert.Equal(1, analyzer.FireCount200);
Assert.Equal(1, analyzer.FireCount300);
Assert.Equal(1, analyzer.FireCount400);
Assert.Equal(1, analyzer.FireCount0);
Assert.Equal(1, analyzer.FireCount1);
Assert.Equal(1, analyzer.FireCount2);
Assert.Equal(1, analyzer.FireCount3);
Assert.Equal(1, analyzer.FireCount4);
Assert.Equal(1, analyzer.FireCount5);
Assert.Equal(1, analyzer.FireCount6);
Assert.Equal(1, analyzer.FireCount7);
Assert.Equal(0, analyzer.FireCount8);
Assert.Equal(1, analyzer.FireCount9);
Assert.Equal(0, analyzer.FireCount10);
Assert.Equal(0, analyzer.FireCount11);
Assert.Equal(0, analyzer.FireCount12);
Assert.Equal(0, analyzer.FireCount13);
Assert.Equal(0, analyzer.FireCount14);
Assert.Equal(1, analyzer.FireCount15);
Assert.Equal(1, analyzer.FireCount16);
Assert.Equal(0, analyzer.FireCount17);
Assert.Equal(0, analyzer.FireCount18);
Assert.Equal(0, analyzer.FireCount19);
Assert.Equal(0, analyzer.FireCount20);
Assert.Equal(0, analyzer.FireCount21);
Assert.Equal(0, analyzer.FireCount22);
Assert.Equal(0, analyzer.FireCount23);
Assert.Equal(1, analyzer.FireCount24);
Assert.Equal(1, analyzer.FireCount25);
Assert.Equal(1, analyzer.FireCount26);
Assert.Equal(0, analyzer.FireCount27);
Assert.Equal(0, analyzer.FireCount28);
Assert.Equal(0, analyzer.FireCount29);
Assert.Equal(1, analyzer.FireCount30);
Assert.Equal(1, analyzer.FireCount31);
Assert.Equal(1, analyzer.FireCount1000);
Assert.Equal(1, analyzer.FireCount2000);
Assert.Equal(1, analyzer.FireCount3000);
Assert.Equal(1, analyzer.FireCount4000);
}
private class AnalyzerActions_08_Analyzer : AnalyzerActions_01_Analyzer
{
public int FireCount100;
public int FireCount200;
public int FireCount300;
public int FireCount400;
public int FireCount1000;
public int FireCount2000;
public int FireCount3000;
public int FireCount4000;
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterCodeBlockStartAction<SyntaxKind>(Handle);
}
private void Handle(CodeBlockStartAnalysisContext<SyntaxKind> context)
{
switch (context.OwningSymbol.ToTestDisplayString())
{
case "A..ctor([System.Int32 X = 0])":
switch (context.CodeBlock)
{
case RecordDeclarationSyntax { Identifier: { ValueText: "A" } }:
Interlocked.Increment(ref FireCount100);
break;
default:
Assert.True(false);
break;
}
break;
case "B..ctor([System.Int32 Y = 1])":
switch (context.CodeBlock)
{
case RecordDeclarationSyntax { Identifier: { ValueText: "B" } }:
Interlocked.Increment(ref FireCount200);
break;
default:
Assert.True(false);
break;
}
break;
case "C..ctor([System.Int32 Z = 4])":
switch (context.CodeBlock)
{
case ConstructorDeclarationSyntax { Identifier: { ValueText: "C" } }:
Interlocked.Increment(ref FireCount300);
break;
default:
Assert.True(false);
break;
}
break;
case "System.Int32 B.M()":
switch (context.CodeBlock)
{
case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }:
Interlocked.Increment(ref FireCount400);
break;
default:
Assert.True(false);
break;
}
break;
default:
Assert.True(false);
break;
}
context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.NumericLiteralExpression);
context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.EqualsValueClause);
context.RegisterSyntaxNodeAction(Handle3, SyntaxKind.BaseConstructorInitializer);
context.RegisterSyntaxNodeAction(Handle4, SyntaxKind.ConstructorDeclaration);
context.RegisterSyntaxNodeAction(Handle5, SyntaxKind.PrimaryConstructorBaseType);
context.RegisterSyntaxNodeAction(Handle6, SyntaxKind.RecordDeclaration);
context.RegisterSyntaxNodeAction(Handle7, SyntaxKind.IdentifierName);
context.RegisterSyntaxNodeAction(Handle8, SyntaxKind.SimpleBaseType);
context.RegisterSyntaxNodeAction(Handle9, SyntaxKind.ParameterList);
context.RegisterSyntaxNodeAction(Handle10, SyntaxKind.ArgumentList);
context.RegisterCodeBlockEndAction(Handle11);
}
private void Handle11(CodeBlockAnalysisContext context)
{
switch (context.OwningSymbol.ToTestDisplayString())
{
case "A..ctor([System.Int32 X = 0])":
switch (context.CodeBlock)
{
case RecordDeclarationSyntax { Identifier: { ValueText: "A" } }:
Interlocked.Increment(ref FireCount1000);
break;
default:
Assert.True(false);
break;
}
break;
case "B..ctor([System.Int32 Y = 1])":
switch (context.CodeBlock)
{
case RecordDeclarationSyntax { Identifier: { ValueText: "B" } }:
Interlocked.Increment(ref FireCount2000);
break;
default:
Assert.True(false);
break;
}
break;
case "C..ctor([System.Int32 Z = 4])":
switch (context.CodeBlock)
{
case ConstructorDeclarationSyntax { Identifier: { ValueText: "C" } }:
Interlocked.Increment(ref FireCount3000);
break;
default:
Assert.True(false);
break;
}
break;
case "System.Int32 B.M()":
switch (context.CodeBlock)
{
case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }:
Interlocked.Increment(ref FireCount4000);
break;
default:
Assert.True(false);
break;
}
break;
default:
Assert.True(false);
break;
}
}
}
[Fact]
public void AnalyzerActions_09()
{
var text1 = @"
record A([Attr1(100)]int X = 0) : I1
{}
record B([Attr2(200)]int Y = 1) : A(2), I1
{
int M() => 3;
}
record C : A, I1
{
C([Attr3(300)]int Z = 4) : base(5)
{}
}
interface I1 {}
";
var analyzer = new AnalyzerActions_09_Analyzer();
var comp = CreateCompilation(text1);
comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify();
Assert.Equal(1, analyzer.FireCount1);
Assert.Equal(1, analyzer.FireCount2);
Assert.Equal(1, analyzer.FireCount3);
Assert.Equal(1, analyzer.FireCount4);
Assert.Equal(1, analyzer.FireCount5);
Assert.Equal(1, analyzer.FireCount6);
Assert.Equal(1, analyzer.FireCount7);
Assert.Equal(1, analyzer.FireCount8);
Assert.Equal(1, analyzer.FireCount9);
}
private class AnalyzerActions_09_Analyzer : DiagnosticAnalyzer
{
public int FireCount1;
public int FireCount2;
public int FireCount3;
public int FireCount4;
public int FireCount5;
public int FireCount6;
public int FireCount7;
public int FireCount8;
public int FireCount9;
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterSymbolAction(Handle1, SymbolKind.Method);
context.RegisterSymbolAction(Handle2, SymbolKind.Property);
context.RegisterSymbolAction(Handle3, SymbolKind.Parameter);
}
private void Handle1(SymbolAnalysisContext context)
{
switch (context.Symbol.ToTestDisplayString())
{
case "A..ctor([System.Int32 X = 0])":
Interlocked.Increment(ref FireCount1);
break;
case "B..ctor([System.Int32 Y = 1])":
Interlocked.Increment(ref FireCount2);
break;
case "C..ctor([System.Int32 Z = 4])":
Interlocked.Increment(ref FireCount3);
break;
case "System.Int32 B.M()":
Interlocked.Increment(ref FireCount4);
break;
default:
Assert.True(false);
break;
}
}
private void Handle2(SymbolAnalysisContext context)
{
switch (context.Symbol.ToTestDisplayString())
{
case "System.Int32 A.X { get; init; }":
Interlocked.Increment(ref FireCount5);
break;
case "System.Int32 B.Y { get; init; }":
Interlocked.Increment(ref FireCount6);
break;
default:
Assert.True(false);
break;
}
}
private void Handle3(SymbolAnalysisContext context)
{
switch (context.Symbol.ToTestDisplayString())
{
case "[System.Int32 X = 0]":
Interlocked.Increment(ref FireCount7);
break;
case "[System.Int32 Y = 1]":
Interlocked.Increment(ref FireCount8);
break;
case "[System.Int32 Z = 4]":
Interlocked.Increment(ref FireCount9);
break;
default:
Assert.True(false);
break;
}
}
}
[Fact]
[WorkItem(46657, "https://github.com/dotnet/roslyn/issues/46657")]
public void CanDeclareIteratorInRecord()
{
var source = @"
using System.Collections.Generic;
public record X(int a)
{
public static void Main()
{
foreach(var i in new X(42).GetItems())
{
System.Console.Write(i);
}
}
public IEnumerable<int> GetItems() { yield return a; yield return a + 1; }
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9)
.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "4243", verify: Verification.Skipped /* init-only */);
}
[Fact]
public void DefaultCtor_01()
{
var src = @"
record C
{
}
class Program
{
static void Main()
{
var x = new C();
var y = new C();
System.Console.WriteLine(x == y);
}
}
";
var verifier = CompileAndVerify(src, expectedOutput: "True");
verifier.VerifyDiagnostics();
verifier.VerifyIL("C..ctor()", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ret
}
");
}
[Fact]
public void DefaultCtor_02()
{
var src = @"
record B(int x);
record C : B
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (4,8): error CS1729: 'B' does not contain a constructor that takes 0 arguments
// record C : B
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("B", "0").WithLocation(4, 8)
);
}
[Fact]
public void DefaultCtor_03()
{
var src = @"
record C
{
public C(C c){}
}
class Program
{
static void Main()
{
var x = new C();
var y = new C();
System.Console.WriteLine(x == y);
}
}
";
var verifier = CompileAndVerify(src, expectedOutput: "True");
verifier.VerifyDiagnostics();
verifier.VerifyIL("C..ctor()", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ret
}
");
}
[Fact]
public void DefaultCtor_04()
{
var src = @"
record B(int x);
record C : B
{
public C(C c) : base(c) {}
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (4,8): error CS1729: 'B' does not contain a constructor that takes 0 arguments
// record C : B
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("B", "0").WithLocation(4, 8)
);
}
[Fact]
public void DefaultCtor_05()
{
var src = @"
record C(int x);
class Program
{
static void Main()
{
_ = new C();
}
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (8,17): error CS7036: There is no argument given that corresponds to the required formal parameter 'x' of 'C.C(int)'
// _ = new C();
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("x", "C.C(int)").WithLocation(8, 17)
);
}
[Fact]
public void DefaultCtor_06()
{
var src = @"
record C
{
C(int x) {}
}
class Program
{
static void Main()
{
_ = new C();
}
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (11,17): error CS1729: 'C' does not contain a constructor that takes 0 arguments
// _ = new C();
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("C", "0").WithLocation(11, 17)
);
}
[Fact]
public void DefaultCtor_07()
{
var src = @"
class C
{
C(C x) {}
}
class Program
{
static void Main()
{
_ = new C();
}
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (11,17): error CS1729: 'C' does not contain a constructor that takes 0 arguments
// _ = new C();
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("C", "0").WithLocation(11, 17)
);
}
[Fact]
[WorkItem(47867, "https://github.com/dotnet/roslyn/issues/47867")]
public void ToString_RecordWithStaticMembers()
{
var src = @"
var c1 = new C1(42);
System.Console.Write(c1.ToString());
record C1(int I1)
{
public static int field1 = 44;
public const int field2 = 44;
public static int P1 { set { } }
public static int P2 { get { return 1; } set { } }
public static int P3 { get { return 1; } }
}
";
var compDebug = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe);
var compRelease = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.ReleaseExe);
CompileAndVerify(compDebug, expectedOutput: "C1 { I1 = 42 }", verify: Verification.Skipped /* init-only */);
compDebug.VerifyEmitDiagnostics();
CompileAndVerify(compRelease, expectedOutput: "C1 { I1 = 42 }", verify: Verification.Skipped /* init-only */);
compRelease.VerifyEmitDiagnostics();
}
[Fact]
[WorkItem(47867, "https://github.com/dotnet/roslyn/issues/47867")]
public void ToString_NestedRecord()
{
var src = @"
var c1 = new Outer.C1(42);
System.Console.Write(c1.ToString());
public class Outer
{
public record C1(int I1);
}
";
var compDebug = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe);
var compRelease = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.ReleaseExe);
CompileAndVerify(compDebug, expectedOutput: "C1 { I1 = 42 }", verify: Verification.Skipped /* init-only */);
compDebug.VerifyEmitDiagnostics();
CompileAndVerify(compRelease, expectedOutput: "C1 { I1 = 42 }", verify: Verification.Skipped /* init-only */);
compRelease.VerifyEmitDiagnostics();
}
[Fact]
[WorkItem(50040, "https://github.com/dotnet/roslyn/issues/50040")]
public void RaceConditionInAddMembers()
{
var src = @"
#nullable enable
using System;
using System.Linq.Expressions;
using System.Threading.Tasks;
var collection = new Collection<Hamster>();
Hamster h = null!;
await collection.MethodAsync(entity => entity.Name! == ""bar"", h);
public record Collection<T> where T : Document
{
public Task MethodAsync<TDerived>(Expression<Func<TDerived, bool>> filter, TDerived td) where TDerived : T
=> throw new NotImplementedException();
public Task MethodAsync<TDerived2>(Task<TDerived2> filterDefinition, TDerived2 td) where TDerived2 : T
=> throw new NotImplementedException();
}
public sealed record HamsterCollection : Collection<Hamster>
{
}
public abstract class Document
{
}
public sealed class Hamster : Document
{
public string? Name { get; private set; }
}
";
for (int i = 0; i < 100; i++)
{
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
}
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc()
{
var src = @"
/// <summary>Summary</summary>
/// <param name=""I1"">Description for I1</param>
public record C(int I1);
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics();
var cMember = comp.GetMember<NamedTypeSymbol>("C");
Assert.Equal(
@"<member name=""T:C"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", cMember.GetDocumentationCommentXml());
var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single();
Assert.Equal(
@"<member name=""M:C.#ctor(System.Int32)"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", constructor.GetDocumentationCommentXml());
Assert.Equal("", constructor.GetParameters()[0].GetDocumentationCommentXml());
var property = cMember.GetMembers("I1").Single();
Assert.Equal("", property.GetDocumentationCommentXml());
}
[Fact]
public void XmlDoc_RecordClass()
{
var src = @"
/// <summary>Summary</summary>
/// <param name=""I1"">Description for I1</param>
public record class C(int I1);
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics();
var cMember = comp.GetMember<NamedTypeSymbol>("C");
Assert.Equal(
@"<member name=""T:C"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", cMember.GetDocumentationCommentXml());
var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single();
Assert.Equal(
@"<member name=""M:C.#ctor(System.Int32)"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", constructor.GetDocumentationCommentXml());
Assert.Equal("", constructor.GetParameters()[0].GetDocumentationCommentXml());
var property = cMember.GetMembers("I1").Single();
Assert.Equal("", property.GetDocumentationCommentXml());
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_Cref()
{
var src = @"
/// <summary>Summary</summary>
/// <param name=""I1"">Description for <see cref=""I1""/></param>
public record C(int I1)
{
/// <summary>Summary</summary>
/// <param name=""x"">Description for <see cref=""x""/></param>
public void M(int x) { }
}
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics(
// (7,52): warning CS1574: XML comment has cref attribute 'x' that could not be resolved
// /// <param name="x">Description for <see cref="x"/></param>
Diagnostic(ErrorCode.WRN_BadXMLRef, "x").WithArguments("x").WithLocation(7, 52)
);
var tree = comp.SyntaxTrees.Single();
var docComments = tree.GetCompilationUnitRoot().DescendantTrivia().Select(trivia => trivia.GetStructure()).OfType<DocumentationCommentTriviaSyntax>();
var cref = docComments.First().DescendantNodes().OfType<XmlCrefAttributeSyntax>().First().Cref;
Assert.Equal("I1", cref.ToString());
var model = comp.GetSemanticModel(tree, ignoreAccessibility: false);
Assert.Equal(SymbolKind.Property, model.GetSymbolInfo(cref).Symbol!.Kind);
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_Error()
{
var src = @"
/// <summary>Summary</summary>
/// <param name=""Error""></param>
/// <param name=""I1""></param>
public record C(int I1);
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics(
// (3,18): warning CS1572: XML comment has a param tag for 'Error', but there is no parameter by that name
// /// <param name="Error"></param>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "Error").WithArguments("Error").WithLocation(3, 18),
// (3,18): warning CS1572: XML comment has a param tag for 'Error', but there is no parameter by that name
// /// <param name="Error"></param>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "Error").WithArguments("Error").WithLocation(3, 18)
);
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_Duplicate()
{
var src = @"
/// <summary>Summary</summary>
/// <param name=""I1""></param>
/// <param name=""I1""></param>
public record C(int I1);
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics(
// (4,12): warning CS1571: XML comment has a duplicate param tag for 'I1'
// /// <param name="I1"></param>
Diagnostic(ErrorCode.WRN_DuplicateParamTag, @"name=""I1""").WithArguments("I1").WithLocation(4, 12),
// (4,12): warning CS1571: XML comment has a duplicate param tag for 'I1'
// /// <param name="I1"></param>
Diagnostic(ErrorCode.WRN_DuplicateParamTag, @"name=""I1""").WithArguments("I1").WithLocation(4, 12)
);
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_ParamRef()
{
var src = @"
/// <summary>Summary <paramref name=""I1""/></summary>
/// <param name=""I1"">Description for I1</param>
public record C(int I1);
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics();
var cMember = comp.GetMember<NamedTypeSymbol>("C");
var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single();
Assert.Equal(
@"<member name=""M:C.#ctor(System.Int32)"">
<summary>Summary <paramref name=""I1""/></summary>
<param name=""I1"">Description for I1</param>
</member>
", constructor.GetDocumentationCommentXml());
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_ParamRef_Error()
{
var src = @"
/// <summary>Summary <paramref name=""Error""/></summary>
/// <param name=""I1"">Description for I1</param>
public record C(int I1);
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics(
// (2,38): warning CS1734: XML comment on 'C' has a paramref tag for 'Error', but there is no parameter by that name
// /// <summary>Summary <paramref name="Error"/></summary>
Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "Error").WithArguments("Error", "C").WithLocation(2, 38),
// (2,38): warning CS1734: XML comment on 'C.C(int)' has a paramref tag for 'Error', but there is no parameter by that name
// /// <summary>Summary <paramref name="Error"/></summary>
Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "Error").WithArguments("Error", "C.C(int)").WithLocation(2, 38)
);
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_WithExplicitProperty()
{
var src = @"
/// <summary>Summary</summary>
/// <param name=""I1"">Description for I1</param>
public record C(int I1)
{
/// <summary>Property summary</summary>
public int I1 { get; init; } = I1;
}
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics();
var cMember = comp.GetMember<NamedTypeSymbol>("C");
Assert.Equal(
@"<member name=""T:C"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", cMember.GetDocumentationCommentXml());
var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single();
Assert.Equal(
@"<member name=""M:C.#ctor(System.Int32)"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", constructor.GetDocumentationCommentXml());
Assert.Equal("", constructor.GetParameters()[0].GetDocumentationCommentXml());
var property = cMember.GetMembers("I1").Single();
Assert.Equal(
@"<member name=""P:C.I1"">
<summary>Property summary</summary>
</member>
", property.GetDocumentationCommentXml());
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_EmptyParameterList()
{
var src = @"
/// <summary>Summary</summary>
public record C();
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics();
var cMember = comp.GetMember<NamedTypeSymbol>("C");
Assert.Equal(
@"<member name=""T:C"">
<summary>Summary</summary>
</member>
", cMember.GetDocumentationCommentXml());
var constructor = cMember.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.IsEmpty).Single();
Assert.Equal(
@"<member name=""M:C.#ctor"">
<summary>Summary</summary>
</member>
", constructor.GetDocumentationCommentXml());
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_Partial_ParamListSecond()
{
var src = @"
public partial record C;
/// <summary>Summary</summary>
/// <param name=""I1"">Description for I1</param>
public partial record C(int I1);
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics();
var c = comp.GetMember<NamedTypeSymbol>("C");
Assert.Equal(
@"<member name=""T:C"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", c.GetDocumentationCommentXml());
var cConstructor = c.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single();
Assert.Equal(
@"<member name=""M:C.#ctor(System.Int32)"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", cConstructor.GetDocumentationCommentXml());
Assert.Equal("", cConstructor.GetParameters()[0].GetDocumentationCommentXml());
Assert.Equal("", c.GetMembers("I1").Single().GetDocumentationCommentXml());
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_Partial_ParamListFirst()
{
var src = @"
/// <summary>Summary</summary>
/// <param name=""I1"">Description for I1</param>
public partial record D(int I1);
public partial record D;
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics();
var d = comp.GetMember<NamedTypeSymbol>("D");
Assert.Equal(
@"<member name=""T:D"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", d.GetDocumentationCommentXml());
var dConstructor = d.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single();
Assert.Equal(
@"<member name=""M:D.#ctor(System.Int32)"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", dConstructor.GetDocumentationCommentXml());
Assert.Equal("", dConstructor.GetParameters()[0].GetDocumentationCommentXml());
Assert.Equal("", d.GetMembers("I1").Single().GetDocumentationCommentXml());
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_Partial_ParamListFirst_XmlDocSecond()
{
var src = @"
public partial record E(int I1);
/// <summary>Summary</summary>
/// <param name=""I1"">Description for I1</param>
public partial record E;
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics(
// (2,23): warning CS1591: Missing XML comment for publicly visible type or member 'E.E(int)'
// public partial record E(int I1);
Diagnostic(ErrorCode.WRN_MissingXMLComment, "E").WithArguments("E.E(int)").WithLocation(2, 23),
// (5,18): warning CS1572: XML comment has a param tag for 'I1', but there is no parameter by that name
// /// <param name="I1">Description for I1</param>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "I1").WithArguments("I1").WithLocation(5, 18)
);
var e = comp.GetMember<NamedTypeSymbol>("E");
Assert.Equal(
@"<member name=""T:E"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", e.GetDocumentationCommentXml());
var eConstructor = e.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single();
Assert.Equal("", eConstructor.GetDocumentationCommentXml());
Assert.Equal("", eConstructor.GetParameters()[0].GetDocumentationCommentXml());
Assert.Equal("", e.GetMembers("I1").Single().GetDocumentationCommentXml());
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_Partial_ParamListSecond_XmlDocFirst()
{
var src = @"
/// <summary>Summary</summary>
/// <param name=""I1"">Description for I1</param>
public partial record E;
public partial record E(int I1);
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics(
// (3,18): warning CS1572: XML comment has a param tag for 'I1', but there is no parameter by that name
// /// <param name="I1">Description for I1</param>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "I1").WithArguments("I1").WithLocation(3, 18),
// (6,23): warning CS1591: Missing XML comment for publicly visible type or member 'E.E(int)'
// public partial record E(int I1);
Diagnostic(ErrorCode.WRN_MissingXMLComment, "E").WithArguments("E.E(int)").WithLocation(6, 23)
);
var e = comp.GetMember<NamedTypeSymbol>("E");
Assert.Equal(
@"<member name=""T:E"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", e.GetDocumentationCommentXml());
var eConstructor = e.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single();
Assert.Equal("", eConstructor.GetDocumentationCommentXml());
Assert.Equal("", eConstructor.GetParameters()[0].GetDocumentationCommentXml());
Assert.Equal("", e.GetMembers("I1").Single().GetDocumentationCommentXml());
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_Partial_DuplicateParameterList_XmlDocSecond()
{
var src = @"
public partial record C(int I1);
/// <summary>Summary</summary>
/// <param name=""I1"">Description for I1</param>
public partial record C(int I1);
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics(
// (2,23): warning CS1591: Missing XML comment for publicly visible type or member 'C.C(int)'
// public partial record C(int I1);
Diagnostic(ErrorCode.WRN_MissingXMLComment, "C").WithArguments("C.C(int)").WithLocation(2, 23),
// (5,18): warning CS1572: XML comment has a param tag for 'I1', but there is no parameter by that name
// /// <param name="I1">Description for I1</param>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "I1").WithArguments("I1").WithLocation(5, 18),
// (6,24): error CS8863: Only a single record partial declaration may have a parameter list
// public partial record C(int I1);
Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(int I1)").WithLocation(6, 24)
);
var c = comp.GetMember<NamedTypeSymbol>("C");
Assert.Equal(
@"<member name=""T:C"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", c.GetDocumentationCommentXml());
var cConstructor = c.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single();
Assert.Equal(1, cConstructor.DeclaringSyntaxReferences.Count());
Assert.Equal("", cConstructor.GetDocumentationCommentXml());
Assert.Equal("", cConstructor.GetParameters()[0].GetDocumentationCommentXml());
Assert.Equal("", c.GetMembers("I1").Single().GetDocumentationCommentXml());
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_Partial_DuplicateParameterList_XmlDocFirst()
{
var src = @"
/// <summary>Summary</summary>
/// <param name=""I1"">Description for I1</param>
public partial record D(int I1);
public partial record D(int I1);
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics(
// (6,24): error CS8863: Only a single record partial declaration may have a parameter list
// public partial record D(int I1);
Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(int I1)").WithLocation(6, 24)
);
var d = comp.GetMember<NamedTypeSymbol>("D");
Assert.Equal(
@"<member name=""T:D"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", d.GetDocumentationCommentXml());
var dConstructor = d.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single();
Assert.Equal(
@"<member name=""M:D.#ctor(System.Int32)"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", dConstructor.GetDocumentationCommentXml());
Assert.Equal("", dConstructor.GetParameters()[0].GetDocumentationCommentXml());
Assert.Equal("", d.GetMembers("I1").Single().GetDocumentationCommentXml());
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_Partial_DuplicateParameterList_XmlDocOnBoth()
{
var src = @"
/// <summary>Summary1</summary>
/// <param name=""I1"">Description1 for I1</param>
public partial record E(int I1);
/// <summary>Summary2</summary>
/// <param name=""I1"">Description2 for I1</param>
public partial record E(int I1);
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics(
// (7,18): warning CS1572: XML comment has a param tag for 'I1', but there is no parameter by that name
// /// <param name="I1">Description2 for I1</param>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "I1").WithArguments("I1").WithLocation(7, 18),
// (8,24): error CS8863: Only a single record partial declaration may have a parameter list
// public partial record E(int I1);
Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(int I1)").WithLocation(8, 24)
);
var e = comp.GetMember<NamedTypeSymbol>("E");
Assert.Equal(
@"<member name=""T:E"">
<summary>Summary1</summary>
<param name=""I1"">Description1 for I1</param>
<summary>Summary2</summary>
<param name=""I1"">Description2 for I1</param>
</member>
", e.GetDocumentationCommentXml());
var eConstructor = e.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single();
Assert.Equal(1, eConstructor.DeclaringSyntaxReferences.Count());
Assert.Equal(
@"<member name=""M:E.#ctor(System.Int32)"">
<summary>Summary1</summary>
<param name=""I1"">Description1 for I1</param>
</member>
", eConstructor.GetDocumentationCommentXml());
Assert.Equal("", eConstructor.GetParameters()[0].GetDocumentationCommentXml());
Assert.Equal("", e.GetMembers("I1").Single().GetDocumentationCommentXml());
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_Partial_DifferentParameterLists_XmlDocSecond()
{
var src = @"
public partial record E(int I1);
/// <summary>Summary2</summary>
/// <param name=""S1"">Description2 for S1</param>
public partial record E(string S1);
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics(
// (2,23): warning CS1591: Missing XML comment for publicly visible type or member 'E.E(int)'
// public partial record E(int I1);
Diagnostic(ErrorCode.WRN_MissingXMLComment, "E").WithArguments("E.E(int)").WithLocation(2, 23),
// (5,18): warning CS1572: XML comment has a param tag for 'S1', but there is no parameter by that name
// /// <param name="S1">Description2 for S1</param>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "S1").WithArguments("S1").WithLocation(5, 18),
// (6,24): error CS8863: Only a single record partial declaration may have a parameter list
// public partial record E(string S1);
Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(string S1)").WithLocation(6, 24)
);
var e = comp.GetMember<NamedTypeSymbol>("E");
Assert.Equal(
@"<member name=""T:E"">
<summary>Summary2</summary>
<param name=""S1"">Description2 for S1</param>
</member>
", e.GetDocumentationCommentXml());
var eConstructor = e.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single();
Assert.Equal(1, eConstructor.DeclaringSyntaxReferences.Count());
Assert.Equal("", eConstructor.GetDocumentationCommentXml());
Assert.Equal("", eConstructor.GetParameters()[0].GetDocumentationCommentXml());
Assert.Equal("", e.GetMembers("I1").Single().GetDocumentationCommentXml());
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_Partial_DifferentParameterLists_XmlDocOnBoth()
{
var src = @"
/// <summary>Summary1</summary>
/// <param name=""I1"">Description1 for I1</param>
public partial record E(int I1);
/// <summary>Summary2</summary>
/// <param name=""S1"">Description2 for S1</param>
public partial record E(string S1);
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics(
// (7,18): warning CS1572: XML comment has a param tag for 'S1', but there is no parameter by that name
// /// <param name="S1">Description2 for S1</param>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "S1").WithArguments("S1").WithLocation(7, 18),
// (8,24): error CS8863: Only a single record partial declaration may have a parameter list
// public partial record E(string S1);
Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(string S1)").WithLocation(8, 24)
);
var e = comp.GetMember<NamedTypeSymbol>("E");
Assert.Equal(
@"<member name=""T:E"">
<summary>Summary1</summary>
<param name=""I1"">Description1 for I1</param>
<summary>Summary2</summary>
<param name=""S1"">Description2 for S1</param>
</member>
", e.GetDocumentationCommentXml());
var eConstructor = e.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single();
Assert.Equal(1, eConstructor.DeclaringSyntaxReferences.Count());
Assert.Equal(
@"<member name=""M:E.#ctor(System.Int32)"">
<summary>Summary1</summary>
<param name=""I1"">Description1 for I1</param>
</member>
", eConstructor.GetDocumentationCommentXml());
Assert.Equal("", eConstructor.GetParameters()[0].GetDocumentationCommentXml());
Assert.Equal("", e.GetMembers("I1").Single().GetDocumentationCommentXml());
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_Nested()
{
var src = @"
/// <summary>Summary</summary>
public class Outer
{
/// <summary>Summary</summary>
/// <param name=""I1"">Description for I1</param>
public record C(int I1);
}
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics();
var cMember = comp.GetMember<NamedTypeSymbol>("Outer.C");
Assert.Equal(
@"<member name=""T:Outer.C"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", cMember.GetDocumentationCommentXml());
var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single();
Assert.Equal(
@"<member name=""M:Outer.C.#ctor(System.Int32)"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", constructor.GetDocumentationCommentXml());
Assert.Equal("", constructor.GetParameters()[0].GetDocumentationCommentXml());
var property = cMember.GetMembers("I1").Single();
Assert.Equal("", property.GetDocumentationCommentXml());
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_Nested_ReferencingOuterParam()
{
var src = @"
/// <summary>Summary</summary>
/// <param name=""O1"">Description for O1</param>
public record Outer(object O1)
{
/// <summary>Summary</summary>
public int P1 { get; set; }
/// <summary>Summary</summary>
/// <param name=""I1"">Description for I1</param>
/// <param name=""O1"">Error O1</param>
/// <param name=""P1"">Error P1</param>
/// <param name=""C"">Error C</param>
public record C(int I1);
}
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics(
// (11,22): warning CS1572: XML comment has a param tag for 'O1', but there is no parameter by that name
// /// <param name="O1">Error</param>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "O1").WithArguments("O1").WithLocation(11, 22),
// (11,22): warning CS1572: XML comment has a param tag for 'O1', but there is no parameter by that name
// /// <param name="O1">Error</param>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "O1").WithArguments("O1").WithLocation(11, 22),
// (12,22): warning CS1572: XML comment has a param tag for 'P1', but there is no parameter by that name
// /// <param name="P1">Error</param>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "P1").WithArguments("P1").WithLocation(12, 22),
// (12,22): warning CS1572: XML comment has a param tag for 'P1', but there is no parameter by that name
// /// <param name="P1">Error</param>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "P1").WithArguments("P1").WithLocation(12, 22),
// (13,22): warning CS1572: XML comment has a param tag for 'C', but there is no parameter by that name
// /// <param name="C">Error</param>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "C").WithArguments("C").WithLocation(13, 22),
// (13,22): warning CS1572: XML comment has a param tag for 'C', but there is no parameter by that name
// /// <param name="C">Error</param>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "C").WithArguments("C").WithLocation(13, 22)
);
var cMember = comp.GetMember<NamedTypeSymbol>("Outer.C");
var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single();
Assert.Equal(
@"<member name=""M:Outer.C.#ctor(System.Int32)"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
<param name=""O1"">Error O1</param>
<param name=""P1"">Error P1</param>
<param name=""C"">Error C</param>
</member>
", constructor.GetDocumentationCommentXml());
}
[Fact, WorkItem(51590, "https://github.com/dotnet/roslyn/issues/51590")]
public void SealedIncomplete()
{
var source = @"
public sealed record(";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (2,21): error CS1001: Identifier expected
// public sealed record(
Diagnostic(ErrorCode.ERR_IdentifierExpected, "(").WithLocation(2, 21),
// (2,22): error CS1026: ) expected
// public sealed record(
Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(2, 22),
// (2,22): error CS1514: { expected
// public sealed record(
Diagnostic(ErrorCode.ERR_LbraceExpected, "").WithLocation(2, 22),
// (2,22): error CS1513: } expected
// public sealed record(
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(2, 22)
);
}
[Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")]
public void HiddenPositionalMember_Property()
{
var source = @"
public record Base
{
public int I { get; set; } = 42;
public Base(int ignored) { }
}
public record C(int I) : Base(I)
{
public void I() { } // hiding
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics(
// (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden.
// public record C(int I) : Base(I)
Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21),
// (9,17): warning CS0108: 'C.I()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended.
// public void I() { } // hiding
Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I()", "Base.I").WithLocation(9, 17)
);
}
[Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")]
public void HiddenPositionalMember_Field()
{
var source = @"
public record Base
{
public int I = 42;
public Base(int ignored) { }
}
public record C(int I) : Base(I)
{
public void I() { } // hiding
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics(
// (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden.
// public record C(int I) : Base(I)
Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21),
// (9,17): warning CS0108: 'C.I()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended.
// public void I() { } // hiding
Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I()", "Base.I").WithLocation(9, 17)
);
}
[Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")]
public void HiddenPositionalMember_Field_HiddenWithConstant()
{
var source = @"
public record Base
{
public int I = 0;
public Base(int ignored) { }
}
public record C(int I) : Base(I)
{
public const int I = 0;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics(
// (7,21): error CS8866: Record member 'C.I' must be a readable instance property or field of type 'int' to match positional parameter 'I'.
// public record C(int I) : Base(I)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "I").WithArguments("C.I", "int", "I").WithLocation(7, 21),
// (9,22): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended.
// public const int I = 0;
Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 22)
);
}
[Fact]
public void FieldAsPositionalMember()
{
var source = @"
var a = new A(42);
System.Console.Write(a.X);
System.Console.Write("" - "");
a.Deconstruct(out int x);
System.Console.Write(x);
record A(int X)
{
public int X = X;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (8,10): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater.
// record A(int X)
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int X").WithArguments("positional fields in records", "10.0").WithLocation(8, 10)
);
comp = CreateCompilation(source, parseOptions: TestOptions.Regular10);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "42 - 42");
verifier.VerifyIL("A.Deconstruct", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: ldfld ""int A.X""
IL_0007: stind.i4
IL_0008: ret
}
");
}
[Fact]
public void FieldAsPositionalMember_TwoParameters()
{
var source = @"
var a = new A(42, 43);
System.Console.Write(a.Y);
System.Console.Write("" - "");
a.Deconstruct(out int x, out int y);
System.Console.Write(y);
record A(int X, int Y)
{
public int X = X;
public int Y = Y;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "43 - 43");
verifier.VerifyIL("A.Deconstruct", @"
{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: ldfld ""int A.X""
IL_0007: stind.i4
IL_0008: ldarg.2
IL_0009: ldarg.0
IL_000a: ldfld ""int A.Y""
IL_000f: stind.i4
IL_0010: ret
}
");
}
[Fact]
public void FieldAsPositionalMember_Readonly()
{
var source = @"
var a = new A(42);
System.Console.Write(a.X);
System.Console.Write("" - "");
a.Deconstruct(out int x);
System.Console.Write(x);
record A(int X)
{
public readonly int X = X;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "42 - 42", verify: Verification.Skipped /* init-only */);
verifier.VerifyIL("A.Deconstruct", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: ldfld ""int A.X""
IL_0007: stind.i4
IL_0008: ret
}
");
}
[Fact]
public void FieldAsPositionalMember_UnusedParameter()
{
var source = @"
record A(int X)
{
public int X;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics(
// (2,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record A(int X)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 14),
// (4,16): warning CS0649: Field 'A.X' is never assigned to, and will always have its default value 0
// public int X;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "X").WithArguments("A.X", "0").WithLocation(4, 16)
);
}
[Fact]
public void FieldAsPositionalMember_CurrentTypeComesFirst()
{
var source = @"
var c = new C(42);
c.Deconstruct(out int i);
System.Console.Write(i);
public record Base
{
public int I { get; set; } = 0;
}
public record C(int I) : Base
{
public int I = I;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (12,16): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended.
// public int I = I;
Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(12, 16)
);
var verifier = CompileAndVerify(comp, expectedOutput: "42");
verifier.VerifyIL("C.Deconstruct", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: ldfld ""int C.I""
IL_0007: stind.i4
IL_0008: ret
}
");
}
[Fact]
public void FieldAsPositionalMember_CurrentTypeComesFirst_FieldInBase()
{
var source = @"
var c = new C(42);
c.Deconstruct(out int i);
System.Console.Write(i);
public record Base
{
public int I = 0;
}
public record C(int I) : Base
{
public int I { get; set; } = I;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (12,16): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended.
// public int I { get; set; } = I;
Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(12, 16)
);
var verifier = CompileAndVerify(comp, expectedOutput: "42");
verifier.VerifyIL("C.Deconstruct", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: call ""int C.I.get""
IL_0007: stind.i4
IL_0008: ret
}
");
}
[Fact]
public void FieldAsPositionalMember_FieldFromBase()
{
var source = @"
var c = new C(0);
c.Deconstruct(out int i);
System.Console.Write(i);
public record Base
{
public int I = 42;
public Base(int ignored) { }
}
public record C(int I) : Base(I)
{
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "42");
verifier.VerifyIL("C.Deconstruct", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: ldfld ""int Base.I""
IL_0007: stind.i4
IL_0008: ret
}
");
}
[Fact]
public void FieldAsPositionalMember_FieldFromBase_StaticFieldInDerivedType()
{
var source = @"
public record Base
{
public int I = 42;
public Base(int ignored) { }
}
public record C(int I) : Base(I)
{
public static int I = 42;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (7,21): error CS8866: Record member 'C.I' must be a readable instance property or field of type 'int' to match positional parameter 'I'.
// public record C(int I) : Base(I)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "I").WithArguments("C.I", "int", "I").WithLocation(7, 21),
// (9,23): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended.
// public static int I = 42;
Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 23)
);
comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (7,21): error CS8866: Record member 'C.I' must be a readable instance property or field of type 'int' to match positional parameter 'I'.
// public record C(int I) : Base(I)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "I").WithArguments("C.I", "int", "I").WithLocation(7, 21),
// (9,23): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended.
// public static int I = 42;
Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 23)
);
source = @"
public record Base
{
public int I { get; set; } = 42;
public Base(int ignored) { }
}
public record C(int I) : Base(I)
{
public static int I { get; set; } = 42;
}
";
comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (7,21): error CS8866: Record member 'C.I' must be a readable instance property or field of type 'int' to match positional parameter 'I'.
// public record C(int I) : Base(I)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "I").WithArguments("C.I", "int", "I").WithLocation(7, 21),
// (9,23): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended.
// public static int I { get; set; } = 42;
Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 23)
);
}
[Fact]
public void FieldAsPositionalMember_Static()
{
var source = @"
record A(int X)
{
public static int X = 0;
public int Y = X;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (2,14): error CS8866: Record member 'A.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'.
// record A(int X)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("A.X", "int", "X").WithLocation(2, 14)
);
}
[Fact]
public void FieldAsPositionalMember_Const()
{
var src = @"
record C(int P)
{
const int P = 4;
}
record C2(int P)
{
const int P = P;
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (2,14): error CS8866: Record member 'C.P' must be a readable instance property or field of type 'int' to match positional parameter 'P'.
// record C(int P)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("C.P", "int", "P").WithLocation(2, 14),
// (2,14): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name?
// record C(int P)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 14),
// (6,15): error CS8866: Record member 'C2.P' must be a readable instance property or field of type 'int' to match positional parameter 'P'.
// record C2(int P)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("C2.P", "int", "P").WithLocation(6, 15),
// (6,15): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name?
// record C2(int P)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(6, 15),
// (8,15): error CS0110: The evaluation of the constant value for 'C2.P' involves a circular definition
// const int P = P;
Diagnostic(ErrorCode.ERR_CircConstValue, "P").WithArguments("C2.P").WithLocation(8, 15)
);
}
[Fact]
public void FieldAsPositionalMember_Volatile()
{
var src = @"
record C(int P)
{
public volatile int P = P;
}";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics();
}
[Fact]
public void FieldAsPositionalMember_DifferentAccessibility()
{
var src = @"
record C(int P)
{
private int P = P;
}
record C2(int P)
{
protected int P = P;
}
record C3(int P)
{
internal int P = P;
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics();
}
[Fact]
public void FieldAsPositionalMember_WrongType()
{
var src = @"
record C(int P)
{
public string P = null;
public int Q = P;
}";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics(
// (2,14): error CS8866: Record member 'C.P' must be a readable instance property or field of type 'int' to match positional parameter 'P'.
// record C(int P)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("C.P", "int", "P").WithLocation(2, 14)
);
}
[Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")]
public void HiddenPositionalMember_Property_HiddenWithZeroArityMethod()
{
var source = @"
public record Base
{
public int I { get; set; } = 42;
public Base(int ignored) { }
}
public record C(int I) : Base(I)
{
public void I() { }
}
";
var expected = new[]
{
// (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden.
// public record C(int I) : Base(I)
Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21),
// (9,17): warning CS0108: 'C.I()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended.
// public void I() { }
Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I()", "Base.I").WithLocation(9, 17)
};
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(expected);
comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics(expected);
}
[Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")]
public void HiddenPositionalMember_Property_HiddenWithZeroArityMethod_DeconstructInSource()
{
var source = @"
public record Base
{
public int I { get; set; } = 42;
public Base(int ignored) { }
}
public record C(int I) : Base(I)
{
public void I() { }
public void Deconstruct(out int i) { i = 0; }
}
";
var expected = new[]
{
// (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden.
// public record C(int I) : Base(I)
Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21),
// (9,17): warning CS0108: 'C.I()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended.
// public void I() { }
Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I()", "Base.I").WithLocation(9, 17)
};
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(expected);
comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics(expected);
}
[Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")]
public void HiddenPositionalMember_Property_HiddenWithZeroArityMethod_WithNew()
{
var source = @"
public record Base
{
public int I { get; set; } = 42;
public Base(int ignored) { }
}
public record C(int I) : Base(I) // 1
{
public new void I() { }
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics(
// (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden.
// public record C(int I) : Base(I) // 1
Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21)
);
}
[Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")]
public void HiddenPositionalMember_Property_HiddenWithGenericMethod()
{
var source = @"
var c = new C(0);
c.Deconstruct(out int i);
System.Console.Write(i);
public record Base
{
public int I { get; set; } = 42;
public Base(int ignored) { }
}
public record C(int I) : Base(I)
{
public void I<T>() { }
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics(
// (11,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden.
// public record C(int I) : Base(I)
Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(11, 21),
// (13,17): warning CS0108: 'C.I<T>()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended.
// public void I<T>() { }
Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I<T>()", "Base.I").WithLocation(13, 17)
);
}
[Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")]
public void HiddenPositionalMember_Property_FromGrandBase()
{
var source = @"
public record GrandBase
{
public int I { get; set; } = 42;
}
public record Base : GrandBase
{
public Base(int ignored) { }
}
public record C(int I) : Base(I)
{
public void I() { }
}
";
var expected = new[]
{
// (10,21): error CS8913: The positional member 'GrandBase.I' found corresponding to this parameter is hidden.
// public record C(int I) : Base(I)
Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("GrandBase.I").WithLocation(10, 21),
// (12,17): warning CS0108: 'C.I()' hides inherited member 'GrandBase.I'. Use the new keyword if hiding was intended.
// public void I() { }
Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I()", "GrandBase.I").WithLocation(12, 17)
};
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics(expected);
}
[Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")]
public void HiddenPositionalMember_Property_NotHiddenByIndexer()
{
var source = @"
var c = new C(0);
c.Deconstruct(out int i);
System.Console.Write(i);
public record Base
{
public int Item { get; set; } = 42;
public Base(int ignored) { }
}
public record C(int Item) : Base(Item)
{
public int this[int x] { get => throw null; }
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "42");
verifier.VerifyIL("C.Deconstruct", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: call ""int Base.Item.get""
IL_0007: stind.i4
IL_0008: ret
}
");
}
[Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")]
public void HiddenPositionalMember_Property_NotHiddenByIndexer_WithIndexerName()
{
var source = @"
var c = new C(0);
c.Deconstruct(out int i);
System.Console.Write(i);
public record Base
{
public int I { get; set; } = 42;
public Base(int ignored) { }
}
public record C(int I) : Base(I)
{
[System.Runtime.CompilerServices.IndexerName(""I"")]
public int this[int x] { get => throw null; }
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "42");
verifier.VerifyIL("C.Deconstruct", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: call ""int Base.I.get""
IL_0007: stind.i4
IL_0008: ret
}
");
}
[Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")]
public void HiddenPositionalMember_Property_HiddenWithType()
{
var source = @"
public record Base
{
public int I { get; set; } = 42;
public Base(int ignored) { }
}
public record C(int I) : Base(I)
{
public class I { }
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics(
// (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden.
// public record C(int I) : Base(I)
Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21),
// (9,18): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended.
// public class I { }
Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 18)
);
}
[Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")]
public void HiddenPositionalMember_Property_HiddenWithEvent()
{
var source = @"
public record Base
{
public int I { get; set; } = 42;
public Base(int ignored) { }
}
public record C(int I) : Base(I)
{
public event System.Action I;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics(
// (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden.
// public record C(int I) : Base(I)
Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21),
// (9,32): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended.
// public event System.Action I;
Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 32),
// (9,32): warning CS0067: The event 'C.I' is never used
// public event System.Action I;
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "I").WithArguments("C.I").WithLocation(9, 32)
);
}
[Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")]
public void HiddenPositionalMember_Property_HiddenWithConstant()
{
var source = @"
public record Base
{
public int I { get; set; } = 42;
public Base(int ignored) { }
}
public record C(int I) : Base(I)
{
public const string I = null;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics(
// (7,21): error CS8866: Record member 'C.I' must be a readable instance property or field of type 'int' to match positional parameter 'I'.
// public record C(int I) : Base(I)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "I").WithArguments("C.I", "int", "I").WithLocation(7, 21),
// (9,25): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended.
// public const string I = null;
Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 25)
);
}
[Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")]
public void HiddenPositionalMember_Property_AbstractInBase()
{
var source = @"
abstract record Base
{
public abstract int I { get; init; }
}
record Derived(int I) : Base
{
public int I() { return 0; }
}
";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics(
// (8,16): warning CS0108: 'Derived.I()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended.
// public int I() { return 0; }
Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("Derived.I()", "Base.I").WithLocation(8, 16),
// (8,16): error CS0102: The type 'Derived' already contains a definition for 'I'
// public int I() { return 0; }
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "I").WithArguments("Derived", "I").WithLocation(8, 16)
);
}
[Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")]
public void HiddenPositionalMember_Property_AbstractInBase_AbstractInDerived()
{
var source = @"
abstract record Base
{
public abstract int I { get; init; }
}
abstract record Derived(int I) : Base
{
public int I() { return 0; }
}
";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics(
// (8,16): error CS0533: 'Derived.I()' hides inherited abstract member 'Base.I'
// public int I() { return 0; }
Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "I").WithArguments("Derived.I()", "Base.I").WithLocation(8, 16),
// (8,16): error CS0102: The type 'Derived' already contains a definition for 'I'
// public int I() { return 0; }
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "I").WithArguments("Derived", "I").WithLocation(8, 16)
);
}
[Fact]
public void InterfaceWithParameters()
{
var src = @"
public interface I
{
}
record R(int X) : I()
{
}
record R2(int X) : I(X)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (6,20): error CS8861: Unexpected argument list.
// record R(int X) : I()
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 20),
// (10,21): error CS8861: Unexpected argument list.
// record R2(int X) : I(X)
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(10, 21),
// (10,21): error CS1729: 'object' does not contain a constructor that takes 1 arguments
// record R2(int X) : I(X)
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(10, 21)
);
}
[Fact]
public void InterfaceWithParameters_RecordClass()
{
var src = @"
public interface I
{
}
record class R(int X) : I()
{
}
record class R2(int X) : I(X)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (6,26): error CS8861: Unexpected argument list.
// record class R(int X) : I()
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 26),
// (10,27): error CS8861: Unexpected argument list.
// record class R2(int X) : I(X)
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(10, 27),
// (10,27): error CS1729: 'object' does not contain a constructor that takes 1 arguments
// record class R2(int X) : I(X)
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(10, 27)
);
}
[Fact]
public void BaseErrorTypeWithParameters()
{
var src = @"
record R2(int X) : Error(X)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (2,8): error CS0115: 'R2.ToString()': no suitable method found to override
// record R2(int X) : Error(X)
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R2").WithArguments("R2.ToString()").WithLocation(2, 8),
// (2,8): error CS0115: 'R2.EqualityContract': no suitable method found to override
// record R2(int X) : Error(X)
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R2").WithArguments("R2.EqualityContract").WithLocation(2, 8),
// (2,8): error CS0115: 'R2.Equals(object?)': no suitable method found to override
// record R2(int X) : Error(X)
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R2").WithArguments("R2.Equals(object?)").WithLocation(2, 8),
// (2,8): error CS0115: 'R2.GetHashCode()': no suitable method found to override
// record R2(int X) : Error(X)
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R2").WithArguments("R2.GetHashCode()").WithLocation(2, 8),
// (2,8): error CS0115: 'R2.PrintMembers(StringBuilder)': no suitable method found to override
// record R2(int X) : Error(X)
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R2").WithArguments("R2.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8),
// (2,20): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?)
// record R2(int X) : Error(X)
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(2, 20),
// (2,25): error CS1729: 'Error' does not contain a constructor that takes 1 arguments
// record R2(int X) : Error(X)
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("Error", "1").WithLocation(2, 25)
);
}
[Fact]
public void BaseDynamicTypeWithParameters()
{
var src = @"
record R(int X) : dynamic(X)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (2,19): error CS1965: 'R': cannot derive from the dynamic type
// record R(int X) : dynamic(X)
Diagnostic(ErrorCode.ERR_DeriveFromDynamic, "dynamic").WithArguments("R").WithLocation(2, 19),
// (2,26): error CS1729: 'object' does not contain a constructor that takes 1 arguments
// record R(int X) : dynamic(X)
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(2, 26)
);
}
[Fact]
public void BaseTypeParameterTypeWithParameters()
{
var src = @"
class C<T>
{
record R(int X) : T(X)
{
}
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (4,23): error CS0689: Cannot derive from 'T' because it is a type parameter
// record R(int X) : T(X)
Diagnostic(ErrorCode.ERR_DerivingFromATyVar, "T").WithArguments("T").WithLocation(4, 23),
// (4,24): error CS1729: 'object' does not contain a constructor that takes 1 arguments
// record R(int X) : T(X)
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(4, 24)
);
}
[Fact]
public void BaseObjectTypeWithParameters()
{
var src = @"
record R(int X) : object(X)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (2,25): error CS1729: 'object' does not contain a constructor that takes 1 arguments
// record R(int X) : object(X)
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(2, 25)
);
}
[Fact]
public void BaseValueTypeTypeWithParameters()
{
var src = @"
record R(int X) : System.ValueType(X)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (2,19): error CS0644: 'R' cannot derive from special class 'ValueType'
// record R(int X) : System.ValueType(X)
Diagnostic(ErrorCode.ERR_DeriveFromEnumOrValueType, "System.ValueType").WithArguments("R", "System.ValueType").WithLocation(2, 19),
// (2,35): error CS1729: 'object' does not contain a constructor that takes 1 arguments
// record R(int X) : System.ValueType(X)
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(2, 35)
);
}
[Fact]
public void InterfaceWithParameters_NoPrimaryConstructor()
{
var src = @"
public interface I
{
}
record R : I()
{
}
record R2 : I(0)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (6,13): error CS8861: Unexpected argument list.
// record R : I()
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 13),
// (10,14): error CS8861: Unexpected argument list.
// record R2 : I(0)
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(0)").WithLocation(10, 14)
);
}
[Fact]
public void InterfaceWithParameters_Class()
{
var src = @"
public interface I
{
}
class C : I()
{
}
class C2 : I(0)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (6,12): error CS8861: Unexpected argument list.
// class C : I()
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 12),
// (10,13): error CS8861: Unexpected argument list.
// class C2 : I(0)
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(0)").WithLocation(10, 13)
);
}
[Theory, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
[CombinatorialData]
public void CrossAssemblySupportingAndNotSupportingCovariantReturns(bool useCompilationReference)
{
var sourceA =
@"public record B(int I)
{
}
public record C(int I) : B(I);";
var compA = CreateEmptyCompilation(new[] { sourceA, IsExternalInitTypeDefinition }, references: TargetFrameworkUtil.GetReferences(TargetFramework.NetStandard20));
compA.VerifyDiagnostics();
Assert.False(compA.Assembly.RuntimeSupportsCovariantReturnsOfClasses);
var actualMembers = compA.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings();
var expectedMembers = new[]
{
"C..ctor(System.Int32 I)",
"System.Type C.EqualityContract.get",
"System.Type C.EqualityContract { get; }",
"System.String C.ToString()",
"System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)",
"System.Boolean C.op_Inequality(C? left, C? right)",
"System.Boolean C.op_Equality(C? left, C? right)",
"System.Int32 C.GetHashCode()",
"System.Boolean C.Equals(System.Object? obj)",
"System.Boolean C.Equals(B? other)",
"System.Boolean C.Equals(C? other)",
"B C." + WellKnownMemberNames.CloneMethodName + "()",
"C..ctor(C original)",
"void C.Deconstruct(out System.Int32 I)",
};
AssertEx.Equal(expectedMembers, actualMembers);
var refA = useCompilationReference ? compA.ToMetadataReference() : compA.EmitToImageReference();
var sourceB = "record D(int I) : C(I);";
// CS1701: Assuming assembly reference '{0}' used by '{1}' matches identity '{2}' of '{3}', you may need to supply runtime policy
var compB = CreateCompilation(sourceB, references: new[] { refA }, options: TestOptions.ReleaseDll.WithSpecificDiagnosticOptions("CS1701", ReportDiagnostic.Suppress), parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp);
compB.VerifyDiagnostics();
Assert.True(compB.Assembly.RuntimeSupportsCovariantReturnsOfClasses);
actualMembers = compB.GetMember<NamedTypeSymbol>("D").GetMembers().ToTestDisplayStrings();
expectedMembers = new[]
{
"D..ctor(System.Int32 I)",
"System.Type D.EqualityContract.get",
"System.Type D.EqualityContract { get; }",
"System.String D.ToString()",
"System.Boolean D." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)",
"System.Boolean D.op_Inequality(D? left, D? right)",
"System.Boolean D.op_Equality(D? left, D? right)",
"System.Int32 D.GetHashCode()",
"System.Boolean D.Equals(System.Object? obj)",
"System.Boolean D.Equals(C? other)",
"System.Boolean D.Equals(D? other)",
"D D." + WellKnownMemberNames.CloneMethodName + "()",
"D..ctor(D original)",
"void D.Deconstruct(out System.Int32 I)"
};
AssertEx.Equal(expectedMembers, actualMembers);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics
{
public class RecordTests : CompilingTestBase
{
private static CSharpCompilation CreateCompilation(CSharpTestSource source)
=> CSharpTestBase.CreateCompilation(new[] { source, IsExternalInitTypeDefinition },
parseOptions: TestOptions.RegularPreview);
private CompilationVerifier CompileAndVerify(
CSharpTestSource src,
string? expectedOutput = null,
IEnumerable<MetadataReference>? references = null)
=> base.CompileAndVerify(
new[] { src, IsExternalInitTypeDefinition },
expectedOutput: expectedOutput,
parseOptions: TestOptions.RegularPreview,
references: references,
// init-only is unverifiable
verify: Verification.Skipped);
[Fact, WorkItem(45900, "https://github.com/dotnet/roslyn/issues/45900")]
public void RecordLanguageVersion()
{
var src1 = @"
class Point(int x, int y);
";
var src2 = @"
record Point { }
";
var src3 = @"
record Point(int x, int y);
";
var comp = CreateCompilation(src1, parseOptions: TestOptions.Regular8, options: TestOptions.ReleaseDll);
comp.VerifyDiagnostics(
// (2,12): error CS8805: Program using top-level statements must be an executable.
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int x, int y);").WithLocation(2, 12),
// (2,12): error CS1514: { expected
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(2, 12),
// (2,12): error CS1513: } expected
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(2, 12),
// (2,12): error CS8400: Feature 'top-level statements' is not available in C# 8.0. Please use language version 9.0 or greater.
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(int x, int y);").WithArguments("top-level statements", "9.0").WithLocation(2, 12),
// (2,12): error CS8803: Top-level statements must precede namespace and type declarations.
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int x, int y);").WithLocation(2, 12),
// (2,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x, int y)").WithLocation(2, 12),
// (2,13): error CS8185: A declaration is not allowed in this context.
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x").WithLocation(2, 13),
// (2,13): error CS0165: Use of unassigned local variable 'x'
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int x").WithArguments("x").WithLocation(2, 13),
// (2,20): error CS8185: A declaration is not allowed in this context.
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int y").WithLocation(2, 20),
// (2,20): error CS0165: Use of unassigned local variable 'y'
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int y").WithArguments("y").WithLocation(2, 20)
);
comp = CreateCompilation(src2, parseOptions: TestOptions.Regular8, options: TestOptions.ReleaseDll);
comp.VerifyDiagnostics(
// (2,1): error CS0246: The type or namespace name 'record' could not be found (are you missing a using directive or an assembly reference?)
// record Point { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "record").WithArguments("record").WithLocation(2, 1),
// (2,8): error CS0116: A namespace cannot directly contain members such as fields or methods
// record Point { }
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "Point").WithLocation(2, 8),
// (2,8): error CS0548: '<invalid-global-code>.Point': property or indexer must have at least one accessor
// record Point { }
Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "Point").WithArguments("<invalid-global-code>.Point").WithLocation(2, 8)
);
comp = CreateCompilation(src3, parseOptions: TestOptions.Regular8, options: TestOptions.ReleaseDll);
comp.VerifyDiagnostics(
// (2,1): error CS8805: Program using top-level statements must be an executable.
// record Point(int x, int y);
Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "record Point(int x, int y);").WithLocation(2, 1),
// (2,1): error CS8400: Feature 'top-level statements' is not available in C# 8.0. Please use language version 9.0 or greater.
// record Point(int x, int y);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "record Point(int x, int y);").WithArguments("top-level statements", "9.0").WithLocation(2, 1),
// (2,1): error CS0246: The type or namespace name 'record' could not be found (are you missing a using directive or an assembly reference?)
// record Point(int x, int y);
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "record").WithArguments("record").WithLocation(2, 1),
// (2,8): error CS8112: Local function 'Point(int, int)' must declare a body because it is not marked 'static extern'.
// record Point(int x, int y);
Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "Point").WithArguments("Point(int, int)").WithLocation(2, 8),
// (2,8): warning CS8321: The local function 'Point' is declared but never used
// record Point(int x, int y);
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Point").WithArguments("Point").WithLocation(2, 8)
);
comp = CreateCompilation(src1, options: TestOptions.ReleaseDll);
comp.VerifyDiagnostics(
// (2,12): error CS8805: Program using top-level statements must be an executable.
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int x, int y);").WithLocation(2, 12),
// (2,12): error CS1514: { expected
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(2, 12),
// (2,12): error CS1513: } expected
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(2, 12),
// (2,12): error CS8803: Top-level statements must precede namespace and type declarations.
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int x, int y);").WithLocation(2, 12),
// (2,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x, int y)").WithLocation(2, 12),
// (2,13): error CS8185: A declaration is not allowed in this context.
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x").WithLocation(2, 13),
// (2,13): error CS0165: Use of unassigned local variable 'x'
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int x").WithArguments("x").WithLocation(2, 13),
// (2,20): error CS8185: A declaration is not allowed in this context.
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int y").WithLocation(2, 20),
// (2,20): error CS0165: Use of unassigned local variable 'y'
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int y").WithArguments("y").WithLocation(2, 20)
);
comp = CreateCompilation(src2);
comp.VerifyDiagnostics();
comp = CreateCompilation(src3);
comp.VerifyDiagnostics();
var point = comp.GlobalNamespace.GetTypeMember("Point");
Assert.True(point.IsReferenceType);
Assert.False(point.IsValueType);
Assert.Equal(TypeKind.Class, point.TypeKind);
Assert.Equal(SpecialType.System_Object, point.BaseTypeNoUseSiteDiagnostics.SpecialType);
}
[Fact, WorkItem(45900, "https://github.com/dotnet/roslyn/issues/45900")]
public void RecordLanguageVersion_Nested()
{
var src1 = @"
class C
{
class Point(int x, int y);
}
";
var src2 = @"
class D
{
record Point { }
}
";
var src3 = @"
class E
{
record Point(int x, int y);
}
";
var comp = CreateCompilation(src1, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (4,16): error CS1514: { expected
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(4, 16),
// (4,16): error CS1513: } expected
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(4, 16),
// (4,30): error CS1519: Invalid token ';' in class, struct, or interface member declaration
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 30),
// (4,30): error CS1519: Invalid token ';' in class, struct, or interface member declaration
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 30)
);
comp = CreateCompilation(src2, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (4,5): error CS0246: The type or namespace name 'record' could not be found (are you missing a using directive or an assembly reference?)
// record Point { }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "record").WithArguments("record").WithLocation(4, 5),
// (4,12): error CS0548: 'D.Point': property or indexer must have at least one accessor
// record Point { }
Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "Point").WithArguments("D.Point").WithLocation(4, 12)
);
comp = CreateCompilation(src3, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (4,5): error CS0246: The type or namespace name 'record' could not be found (are you missing a using directive or an assembly reference?)
// record Point(int x, int y);
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "record").WithArguments("record").WithLocation(4, 5),
// (4,12): error CS0501: 'E.Point(int, int)' must declare a body because it is not marked abstract, extern, or partial
// record Point(int x, int y);
Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "Point").WithArguments("E.Point(int, int)").WithLocation(4, 12)
);
comp = CreateCompilation(src1);
comp.VerifyDiagnostics(
// (4,16): error CS1514: { expected
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(4, 16),
// (4,16): error CS1513: } expected
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(4, 16),
// (4,30): error CS1519: Invalid token ';' in class, struct, or interface member declaration
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 30),
// (4,30): error CS1519: Invalid token ';' in class, struct, or interface member declaration
// class Point(int x, int y);
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 30)
);
comp = CreateCompilation(src2);
comp.VerifyDiagnostics();
comp = CreateCompilation(src3);
comp.VerifyDiagnostics();
}
[Fact, WorkItem(45900, "https://github.com/dotnet/roslyn/issues/45900")]
public void RecordClassLanguageVersion()
{
var src = @"
record class Point(int x, int y);
";
var comp = CreateCompilation(src, parseOptions: TestOptions.Regular8, options: TestOptions.ReleaseDll);
comp.VerifyDiagnostics(
// (2,1): error CS0116: A namespace cannot directly contain members such as fields or methods
// record class Point(int x, int y);
Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "record").WithLocation(2, 1),
// (2,19): error CS1514: { expected
// record class Point(int x, int y);
Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(2, 19),
// (2,19): error CS1513: } expected
// record class Point(int x, int y);
Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(2, 19),
// (2,19): error CS8400: Feature 'top-level statements' is not available in C# 8.0. Please use language version 9.0 or greater.
// record class Point(int x, int y);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(int x, int y);").WithArguments("top-level statements", "9.0").WithLocation(2, 19),
// (2,19): error CS8803: Top-level statements must precede namespace and type declarations.
// record class Point(int x, int y);
Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int x, int y);").WithLocation(2, 19),
// (2,19): error CS8805: Program using top-level statements must be an executable.
// record class Point(int x, int y);
Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int x, int y);").WithLocation(2, 19),
// (2,19): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// record class Point(int x, int y);
Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x, int y)").WithLocation(2, 19),
// (2,20): error CS8185: A declaration is not allowed in this context.
// record class Point(int x, int y);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x").WithLocation(2, 20),
// (2,20): error CS0165: Use of unassigned local variable 'x'
// record class Point(int x, int y);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int x").WithArguments("x").WithLocation(2, 20),
// (2,27): error CS8185: A declaration is not allowed in this context.
// record class Point(int x, int y);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int y").WithLocation(2, 27),
// (2,27): error CS0165: Use of unassigned local variable 'y'
// record class Point(int x, int y);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int y").WithArguments("y").WithLocation(2, 27)
);
comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyDiagnostics(
// (2,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater.
// record class Point(int x, int y);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "class").WithArguments("record structs", "10.0").WithLocation(2, 8)
);
comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10, options: TestOptions.ReleaseDll);
comp.VerifyDiagnostics();
}
[CombinatorialData]
[Theory, WorkItem(49302, "https://github.com/dotnet/roslyn/issues/49302")]
public void GetSimpleNonTypeMembers(bool useCompilationReference)
{
var lib_src = @"
public record RecordA(RecordB B);
public record RecordB(int C);
";
var lib_comp = CreateCompilation(lib_src);
var src = @"
class C
{
void M(RecordA a, RecordB b)
{
_ = a.B == b;
}
}
";
var comp = CreateCompilation(src, references: new[] { AsReference(lib_comp, useCompilationReference) });
comp.VerifyEmitDiagnostics();
}
[Fact, WorkItem(49302, "https://github.com/dotnet/roslyn/issues/49302")]
public void GetSimpleNonTypeMembers_SingleCompilation()
{
var src = @"
public record RecordA(RecordB B);
public record RecordB(int C);
class C
{
void M(RecordA a, RecordB b)
{
_ = a.B == b;
}
}
";
var comp = CreateCompilation(src);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree, ignoreAccessibility: false);
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
Assert.Equal("System.Boolean RecordB.op_Equality(RecordB? left, RecordB? right)",
model.GetSymbolInfo(node).Symbol.ToTestDisplayString());
}
[Fact, WorkItem(49302, "https://github.com/dotnet/roslyn/issues/49302")]
public void GetSimpleNonTypeMembers_DirectApiCheck()
{
var src = @"
public record RecordB();
";
var comp = CreateCompilation(src);
var b = comp.GlobalNamespace.GetTypeMember("RecordB");
AssertEx.SetEqual(new[] { "System.Boolean RecordB.op_Equality(RecordB? left, RecordB? right)" },
b.GetSimpleNonTypeMembers("op_Equality").ToTestDisplayStrings());
}
[Fact, WorkItem(49628, "https://github.com/dotnet/roslyn/issues/49628")]
public void AmbigCtor()
{
var src = @"
record R(R x);
#nullable enable
record R2(R2? x) { }
record R3([System.Diagnostics.CodeAnalysis.NotNull] R3 x);
";
var comp = CreateCompilation(new[] { src, NotNullAttributeDefinition });
comp.VerifyEmitDiagnostics(
// (2,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor.
// record R(R x);
Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R").WithLocation(2, 8),
// (5,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor.
// record R2(R2? x) { }
Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R2").WithLocation(5, 8),
// (7,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor.
// record R3([System.Diagnostics.CodeAnalysis.NotNull] R3 x);
Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R3").WithLocation(7, 8)
);
var r = comp.GlobalNamespace.GetTypeMember("R");
Assert.Equal(new[] { "R..ctor(R x)", "R..ctor(R original)" }, r.GetMembers(".ctor").ToTestDisplayStrings());
}
[Fact, WorkItem(49628, "https://github.com/dotnet/roslyn/issues/49628")]
public void AmbigCtor_Generic()
{
var src = @"
record R<T>(R<T> x);
#nullable enable
record R2<T>(R2<T?> x) { }
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (2,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor.
// record R<T>(R<T> x);
Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R").WithLocation(2, 8),
// (5,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor.
// record R2<T>(R2<T?> x) { }
Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R2").WithLocation(5, 8)
);
}
[Fact, WorkItem(49628, "https://github.com/dotnet/roslyn/issues/49628")]
public void AmbigCtor_WithExplicitCopyCtor()
{
var src = @"
record R(R x)
{
public R(R x) => throw null;
}
";
var comp = CreateCompilation(new[] { src, NotNullAttributeDefinition });
comp.VerifyEmitDiagnostics(
// (4,12): error CS0111: Type 'R' already defines a member called 'R' with the same parameter types
// public R(R x) => throw null;
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "R").WithArguments("R", "R").WithLocation(4, 12)
);
var r = comp.GlobalNamespace.GetTypeMember("R");
Assert.Equal(new[] { "R..ctor(R x)", "R..ctor(R x)" }, r.GetMembers(".ctor").ToTestDisplayStrings());
}
[Fact, WorkItem(49628, "https://github.com/dotnet/roslyn/issues/49628")]
public void AmbigCtor_WithBase()
{
var src = @"
record Base;
record R(R x) : Base; // 1
record Derived(Derived y) : R(y) // 2
{
public Derived(Derived y) : base(y) => throw null; // 3, 4, 5
}
record Derived2(Derived2 y) : R(y); // 6, 7, 8
record R2(R2 x) : Base
{
public R2(R2 x) => throw null; // 9, 10
}
record R3(R3 x) : Base
{
public R3(R3 x) : base(x) => throw null; // 11
}
";
var comp = CreateCompilation(new[] { src, NotNullAttributeDefinition });
comp.VerifyEmitDiagnostics(
// (4,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor.
// record R(R x) : Base; // 1
Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R").WithLocation(4, 8),
// (6,30): error CS0121: The call is ambiguous between the following methods or properties: 'R.R(R)' and 'R.R(R)'
// record Derived(Derived y) : R(y) // 2
Diagnostic(ErrorCode.ERR_AmbigCall, "(y)").WithArguments("R.R(R)", "R.R(R)").WithLocation(6, 30),
// (8,12): error CS0111: Type 'Derived' already defines a member called 'Derived' with the same parameter types
// public Derived(Derived y) : base(y) => throw null; // 3, 4, 5
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Derived").WithArguments("Derived", "Derived").WithLocation(8, 12),
// (8,33): error CS0121: The call is ambiguous between the following methods or properties: 'R.R(R)' and 'R.R(R)'
// public Derived(Derived y) : base(y) => throw null; // 3, 4, 5
Diagnostic(ErrorCode.ERR_AmbigCall, "base").WithArguments("R.R(R)", "R.R(R)").WithLocation(8, 33),
// (8,33): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object.
// public Derived(Derived y) : base(y) => throw null; // 3, 4, 5
Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "base").WithLocation(8, 33),
// (11,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor.
// record Derived2(Derived2 y) : R(y); // 6, 7, 8
Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "Derived2").WithLocation(11, 8),
// (11,8): error CS8867: No accessible copy constructor found in base type 'R'.
// record Derived2(Derived2 y) : R(y); // 6, 7, 8
Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "Derived2").WithArguments("R").WithLocation(11, 8),
// (11,32): error CS0121: The call is ambiguous between the following methods or properties: 'R.R(R)' and 'R.R(R)'
// record Derived2(Derived2 y) : R(y); // 6, 7, 8
Diagnostic(ErrorCode.ERR_AmbigCall, "(y)").WithArguments("R.R(R)", "R.R(R)").WithLocation(11, 32),
// (15,12): error CS0111: Type 'R2' already defines a member called 'R2' with the same parameter types
// public R2(R2 x) => throw null; // 9, 10
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "R2").WithArguments("R2", "R2").WithLocation(15, 12),
// (15,12): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object.
// public R2(R2 x) => throw null; // 9, 10
Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "R2").WithLocation(15, 12),
// (20,12): error CS0111: Type 'R3' already defines a member called 'R3' with the same parameter types
// public R3(R3 x) : base(x) => throw null; // 11
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "R3").WithArguments("R3", "R3").WithLocation(20, 12)
);
}
[Fact, WorkItem(49628, "https://github.com/dotnet/roslyn/issues/49628")]
public void AmbigCtor_WithPropertyInitializer()
{
var src = @"
record R(R X)
{
public R X { get; init; } = X;
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (2,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor.
// record R(R X)
Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R").WithLocation(2, 8)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree, ignoreAccessibility: false);
var parameterSyntax = tree.GetRoot().DescendantNodes().OfType<ParameterSyntax>().Single();
var parameter = model.GetDeclaredSymbol(parameterSyntax)!;
Assert.Equal("R X", parameter.ToTestDisplayString());
Assert.Equal(SymbolKind.Parameter, parameter.Kind);
Assert.Equal("R..ctor(R X)", parameter.ContainingSymbol.ToTestDisplayString());
var initializerSyntax = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Single();
var initializer = model.GetSymbolInfo(initializerSyntax.Value).Symbol!;
Assert.Equal("R X", initializer.ToTestDisplayString());
Assert.Equal(SymbolKind.Parameter, initializer.Kind);
Assert.Equal("R..ctor(R X)", initializer.ContainingSymbol.ToTestDisplayString());
}
[Fact]
public void GetDeclaredSymbolOnAnOutLocalInPropertyInitializer()
{
var src = @"
record R(int I)
{
public int I { get; init; } = M(out int i) ? i : 0;
static bool M(out int i) => throw null;
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (2,14): warning CS8907: Parameter 'I' is unread. Did you forget to use it to initialize the property with that name?
// record R(int I)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "I").WithArguments("I").WithLocation(2, 14)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree, ignoreAccessibility: false);
var outVarSyntax = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Single();
var outVar = model.GetDeclaredSymbol(outVarSyntax)!;
Assert.Equal("System.Int32 i", outVar.ToTestDisplayString());
Assert.Equal(SymbolKind.Local, outVar.Kind);
Assert.Equal("System.Int32 R.<I>k__BackingField", outVar.ContainingSymbol.ToTestDisplayString());
}
[Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")]
public void IncompletePositionalRecord()
{
string source = @"
public record A(int i,) { }
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (2,23): error CS1031: Type expected
// public record A(int i,) { }
Diagnostic(ErrorCode.ERR_TypeExpected, ")").WithLocation(2, 23),
// (2,23): error CS1001: Identifier expected
// public record A(int i,) { }
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(2, 23)
);
var expectedMembers = new[]
{
"System.Type A.EqualityContract { get; }",
"System.Int32 A.i { get; init; }",
"? A. { get; init; }"
};
AssertEx.Equal(expectedMembers,
comp.GetMember<NamedTypeSymbol>("A").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings());
AssertEx.Equal(new[] { "A..ctor(System.Int32 i, ?)", "A..ctor(A original)" },
comp.GetMember<NamedTypeSymbol>("A").Constructors.ToTestDisplayStrings());
var primaryCtor = comp.GetMember<NamedTypeSymbol>("A").Constructors.First();
Assert.Equal("A..ctor(System.Int32 i, ?)", primaryCtor.ToTestDisplayString());
Assert.IsType<ParameterSyntax>(primaryCtor.Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax());
}
[Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")]
public void IncompletePositionalRecord_WithTrivia()
{
string source = @"
public record A(int i, // A
// B
, /* C */ ) { }
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (2,23): error CS1031: Type expected
// public record A(int i, // A
Diagnostic(ErrorCode.ERR_TypeExpected, "").WithLocation(2, 23),
// (2,23): error CS1001: Identifier expected
// public record A(int i, // A
Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(2, 23),
// (4,15): error CS1031: Type expected
// , /* C */ ) { }
Diagnostic(ErrorCode.ERR_TypeExpected, ")").WithLocation(4, 15),
// (4,15): error CS1001: Identifier expected
// , /* C */ ) { }
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(4, 15),
// (4,15): error CS0102: The type 'A' already contains a definition for ''
// , /* C */ ) { }
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("A", "").WithLocation(4, 15)
);
var primaryCtor = comp.GetMember<NamedTypeSymbol>("A").Constructors.First();
Assert.Equal("A..ctor(System.Int32 i, ?, ?)", primaryCtor.ToTestDisplayString());
Assert.IsType<ParameterSyntax>(primaryCtor.Parameters[0].DeclaringSyntaxReferences.Single().GetSyntax());
Assert.IsType<ParameterSyntax>(primaryCtor.Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax());
Assert.IsType<ParameterSyntax>(primaryCtor.Parameters[2].DeclaringSyntaxReferences.Single().GetSyntax());
}
[Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")]
public void IncompleteConstructor()
{
string source = @"
public class C
{
C(int i, ) { }
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (4,14): error CS1031: Type expected
// C(int i, ) { }
Diagnostic(ErrorCode.ERR_TypeExpected, ")").WithLocation(4, 14),
// (4,14): error CS1001: Identifier expected
// C(int i, ) { }
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(4, 14)
);
var ctor = comp.GetMember<NamedTypeSymbol>("C").Constructors.Single();
Assert.Equal("C..ctor(System.Int32 i, ?)", ctor.ToTestDisplayString());
Assert.IsType<ParameterSyntax>(ctor.Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax());
Assert.Equal(0, ctor.Parameters[1].Locations.Single().SourceSpan.Length);
}
[Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")]
public void IncompletePositionalRecord_WithType()
{
string source = @"
public record A(int i, int ) { }
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (2,28): error CS1001: Identifier expected
// public record A(int i, int ) { }
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(2, 28)
);
var expectedMembers = new[]
{
"System.Type A.EqualityContract { get; }",
"System.Int32 A.i { get; init; }",
"System.Int32 A. { get; init; }"
};
AssertEx.Equal(expectedMembers,
comp.GetMember<NamedTypeSymbol>("A").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings());
var ctor = comp.GetMember<NamedTypeSymbol>("A").Constructors[0];
Assert.Equal("A..ctor(System.Int32 i, System.Int32)", ctor.ToTestDisplayString());
Assert.IsType<ParameterSyntax>(ctor.Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax());
Assert.Equal(0, ctor.Parameters[1].Locations.Single().SourceSpan.Length);
}
[Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")]
public void IncompletePositionalRecord_WithTwoTypes()
{
string source = @"
public record A(int, string ) { }
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (2,20): error CS1001: Identifier expected
// public record A(int, string ) { }
Diagnostic(ErrorCode.ERR_IdentifierExpected, ",").WithLocation(2, 20),
// (2,29): error CS1001: Identifier expected
// public record A(int, string ) { }
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(2, 29),
// (2,29): error CS0102: The type 'A' already contains a definition for ''
// public record A(int, string ) { }
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("A", "").WithLocation(2, 29)
);
var expectedMembers = new[]
{
"System.Type A.EqualityContract { get; }",
"System.Int32 A. { get; init; }",
"System.String A. { get; init; }"
};
AssertEx.Equal(expectedMembers,
comp.GetMember<NamedTypeSymbol>("A").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings());
AssertEx.Equal(new[] { "A..ctor(System.Int32, System.String)", "A..ctor(A original)" },
comp.GetMember<NamedTypeSymbol>("A").Constructors.ToTestDisplayStrings());
Assert.IsType<ParameterSyntax>(comp.GetMember<NamedTypeSymbol>("A").Constructors[0].Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax());
}
[Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")]
public void IncompletePositionalRecord_WithTwoTypes_SameType()
{
string source = @"
public record A(int, int ) { }
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (2,20): error CS1001: Identifier expected
// public record A(int, int ) { }
Diagnostic(ErrorCode.ERR_IdentifierExpected, ",").WithLocation(2, 20),
// (2,26): error CS1001: Identifier expected
// public record A(int, int ) { }
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(2, 26),
// (2,26): error CS0102: The type 'A' already contains a definition for ''
// public record A(int, int ) { }
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("A", "").WithLocation(2, 26)
);
var expectedMembers = new[]
{
"System.Type A.EqualityContract { get; }",
"System.Int32 A. { get; init; }",
"System.Int32 A. { get; init; }"
};
AssertEx.Equal(expectedMembers,
comp.GetMember<NamedTypeSymbol>("A").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings());
AssertEx.Equal(new[] { "A..ctor(System.Int32, System.Int32)", "A..ctor(A original)" },
comp.GetMember<NamedTypeSymbol>("A").Constructors.ToTestDisplayStrings());
Assert.IsType<ParameterSyntax>(comp.GetMember<NamedTypeSymbol>("A").Constructors[0].Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax());
}
[Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")]
public void IncompletePositionalRecord_WithTwoTypes_WithTrivia()
{
string source = @"
public record A(int // A
// B
, int /* C */) { }
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (2,20): error CS1001: Identifier expected
// public record A(int // A
Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(2, 20),
// (4,18): error CS1001: Identifier expected
// , int /* C */) { }
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(4, 18),
// (4,18): error CS0102: The type 'A' already contains a definition for ''
// , int /* C */) { }
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("A", "").WithLocation(4, 18)
);
var ctor = comp.GetMember<NamedTypeSymbol>("A").Constructors[0];
Assert.IsType<ParameterSyntax>(ctor.Parameters[0].DeclaringSyntaxReferences.Single().GetSyntax());
Assert.IsType<ParameterSyntax>(ctor.Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax());
}
[Fact, WorkItem(46083, "https://github.com/dotnet/roslyn/issues/46083")]
public void IncompletePositionalRecord_SingleParameter()
{
string source = @"
record A(x)
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (2,10): error CS0246: The type or namespace name 'x' could not be found (are you missing a using directive or an assembly reference?)
// record A(x)
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "x").WithArguments("x").WithLocation(2, 10),
// (2,11): error CS1001: Identifier expected
// record A(x)
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(2, 11),
// (2,12): error CS1514: { expected
// record A(x)
Diagnostic(ErrorCode.ERR_LbraceExpected, "").WithLocation(2, 12),
// (2,12): error CS1513: } expected
// record A(x)
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(2, 12)
);
}
[Fact]
public void TestWithInExpressionTree()
{
var source = @"
using System;
using System.Linq.Expressions;
public record C(int i)
{
public static void M()
{
Expression<Func<C, C>> expr = c => c with { i = 5 };
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,44): error CS8849: An expression tree may not contain a with-expression.
// Expression<Func<C, C>> expr = c => c with { i = 5 };
Diagnostic(ErrorCode.ERR_ExpressionTreeContainsWithExpression, "c with { i = 5 }").WithLocation(8, 44)
);
}
[Fact]
public void PartialRecord_MixedWithClass()
{
var src = @"
partial record C(int X, int Y)
{
}
partial class C
{
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (5,15): error CS0261: Partial declarations of 'C' must be all classes, all record classes, all structs, all record structs, or all interfaces
// partial class C
Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "C").WithArguments("C").WithLocation(5, 15)
);
}
[Fact]
public void PartialRecord_ParametersInScopeOfBothParts()
{
var src = @"
var c = new C(2);
System.Console.Write((c.P1, c.P2));
public partial record C(int X)
{
public int P1 { get; set; } = X;
}
public partial record C
{
public int P2 { get; set; } = X;
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
CompileAndVerify(comp, expectedOutput: "(2, 2)", verify: Verification.Skipped /* init-only */).VerifyDiagnostics();
}
[Fact]
public void PartialRecord_ParametersInScopeOfBothParts_RecordClass()
{
var src = @"
var c = new C(2);
System.Console.Write((c.P1, c.P2));
public partial record C(int X)
{
public int P1 { get; set; } = X;
}
public partial record class C
{
public int P2 { get; set; } = X;
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular10);
CompileAndVerify(comp, expectedOutput: "(2, 2)", verify: Verification.Skipped /* init-only */).VerifyDiagnostics();
}
[Fact]
public void PartialRecord_DuplicateMemberNames()
{
var src = @"
public partial record C(int X)
{
public void M(int i) { }
}
public partial record C
{
public void M(string s) { }
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition });
var expectedMemberNames = new string[]
{
".ctor",
"get_EqualityContract",
"EqualityContract",
"<X>k__BackingField",
"get_X",
"set_X",
"X",
"M",
"M",
"ToString",
"PrintMembers",
"op_Inequality",
"op_Equality",
"GetHashCode",
"Equals",
"Equals",
"<Clone>$",
".ctor",
"Deconstruct"
};
AssertEx.Equal(expectedMemberNames, comp.GetMember<NamedTypeSymbol>("C").GetPublicSymbol().MemberNames);
}
[Fact]
public void RecordInsideGenericType()
{
var src = @"
var c = new C<int>.Nested(2);
System.Console.Write(c.T);
public class C<T>
{
public record Nested(T T);
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "2", verify: Verification.Skipped /* init-only */);
}
[Fact]
public void RecordProperties_01()
{
var src = @"
using System;
record C(int X, int Y)
{
int Z = 123;
public static void Main()
{
var c = new C(1, 2);
Console.WriteLine(c.X);
Console.WriteLine(c.Y);
Console.WriteLine(c.Z);
}
}";
var verifier = CompileAndVerify(src, expectedOutput: @"
1
2
123").VerifyDiagnostics();
verifier.VerifyIL("C..ctor(int, int)", @"
{
// Code size 29 (0x1d)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld ""int C.<X>k__BackingField""
IL_0007: ldarg.0
IL_0008: ldarg.2
IL_0009: stfld ""int C.<Y>k__BackingField""
IL_000e: ldarg.0
IL_000f: ldc.i4.s 123
IL_0011: stfld ""int C.Z""
IL_0016: ldarg.0
IL_0017: call ""object..ctor()""
IL_001c: ret
}
");
var c = verifier.Compilation.GlobalNamespace.GetTypeMember("C");
var x = (IPropertySymbol)c.GetMember("X");
Assert.Equal("System.Int32 C.X.get", x.GetMethod.ToTestDisplayString());
Assert.Equal("void modreq(System.Runtime.CompilerServices.IsExternalInit) C.X.init", x.SetMethod.ToTestDisplayString());
Assert.True(x.SetMethod!.IsInitOnly);
var xBackingField = (IFieldSymbol)c.GetMember("<X>k__BackingField");
Assert.Equal("System.Int32 C.<X>k__BackingField", xBackingField.ToTestDisplayString());
Assert.True(xBackingField.IsReadOnly);
}
[Fact]
public void RecordProperties_02()
{
var src = @"
using System;
record C(int X, int Y)
{
public C(int a, int b)
{
}
public static void Main()
{
var c = new C(1, 2);
Console.WriteLine(c.X);
Console.WriteLine(c.Y);
}
private int X1 = X;
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (5,12): error CS0111: Type 'C' already defines a member called 'C' with the same parameter types
// public C(int a, int b)
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments("C", "C").WithLocation(5, 12),
// (5,12): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer.
// public C(int a, int b)
Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "C").WithLocation(5, 12),
// (11,21): error CS0121: The call is ambiguous between the following methods or properties: 'C.C(int, int)' and 'C.C(int, int)'
// var c = new C(1, 2);
Diagnostic(ErrorCode.ERR_AmbigCall, "C").WithArguments("C.C(int, int)", "C.C(int, int)").WithLocation(11, 21)
);
}
[Fact]
public void RecordProperties_03()
{
var src = @"
using System;
record C(int X, int Y)
{
public int X { get; }
public static void Main()
{
var c = new C(1, 2);
Console.WriteLine(c.X);
Console.WriteLine(c.Y);
}
}";
CompileAndVerify(src, expectedOutput: @"
0
2").VerifyDiagnostics(
// (3,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X, int Y)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 14)
);
}
[Fact]
public void RecordProperties_04()
{
var src = @"
using System;
record C(int X, int Y)
{
public int X { get; } = 3;
public static void Main()
{
var c = new C(1, 2);
Console.WriteLine(c.X);
Console.WriteLine(c.Y);
}
}";
CompileAndVerify(src, expectedOutput: @"
3
2").VerifyDiagnostics(
// (3,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X, int Y)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 14)
);
}
[Fact, WorkItem(48947, "https://github.com/dotnet/roslyn/issues/48947")]
public void RecordProperties_05()
{
var src = @"
record C(int X, int X)
{
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (2,21): error CS0100: The parameter name 'X' is a duplicate
// record C(int X, int X)
Diagnostic(ErrorCode.ERR_DuplicateParamName, "X").WithArguments("X").WithLocation(2, 21),
// (2,21): error CS0102: The type 'C' already contains a definition for 'X'
// record C(int X, int X)
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("C", "X").WithLocation(2, 21)
);
var expectedMembers = new[]
{
"System.Type C.EqualityContract { get; }",
"System.Int32 C.X { get; init; }",
"System.Int32 C.X { get; init; }"
};
AssertEx.Equal(expectedMembers,
comp.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings());
var expectedMemberNames = new[] {
".ctor",
"get_EqualityContract",
"EqualityContract",
"<X>k__BackingField",
"get_X",
"set_X",
"X",
"<X>k__BackingField",
"get_X",
"set_X",
"X",
"ToString",
"PrintMembers",
"op_Inequality",
"op_Equality",
"GetHashCode",
"Equals",
"Equals",
"<Clone>$",
".ctor",
"Deconstruct"
};
AssertEx.Equal(expectedMemberNames, comp.GetMember<NamedTypeSymbol>("C").GetPublicSymbol().MemberNames);
}
[Fact]
public void RecordProperties_05_RecordClass()
{
var src = @"
record class C(int X, int X)
{
}";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10);
comp.VerifyDiagnostics(
// (2,27): error CS0100: The parameter name 'X' is a duplicate
// record class C(int X, int X)
Diagnostic(ErrorCode.ERR_DuplicateParamName, "X").WithArguments("X").WithLocation(2, 27),
// (2,27): error CS0102: The type 'C' already contains a definition for 'X'
// record class C(int X, int X)
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("C", "X").WithLocation(2, 27)
);
var expectedMembers = new[]
{
"System.Type C.EqualityContract { get; }",
"System.Int32 C.X { get; init; }",
"System.Int32 C.X { get; init; }"
};
AssertEx.Equal(expectedMembers,
comp.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings());
var expectedMemberNames = new[] {
".ctor",
"get_EqualityContract",
"EqualityContract",
"<X>k__BackingField",
"get_X",
"set_X",
"X",
"<X>k__BackingField",
"get_X",
"set_X",
"X",
"ToString",
"PrintMembers",
"op_Inequality",
"op_Equality",
"GetHashCode",
"Equals",
"Equals",
"<Clone>$",
".ctor",
"Deconstruct"
};
AssertEx.Equal(expectedMemberNames, comp.GetMember<NamedTypeSymbol>("C").GetPublicSymbol().MemberNames);
}
[Fact]
public void RecordProperties_06()
{
var src = @"
record C(int X, int Y)
{
public void get_X() { }
public void set_X() { }
int get_Y(int value) => value;
int set_Y(int value) => value;
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (2,14): error CS0082: Type 'C' already reserves a member called 'get_X' with the same parameter types
// record C(int X, int Y)
Diagnostic(ErrorCode.ERR_MemberReserved, "X").WithArguments("get_X", "C").WithLocation(2, 14),
// (2,21): error CS0082: Type 'C' already reserves a member called 'set_Y' with the same parameter types
// record C(int X, int Y)
Diagnostic(ErrorCode.ERR_MemberReserved, "Y").WithArguments("set_Y", "C").WithLocation(2, 21));
var actualMembers = comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings();
var expectedMembers = new[]
{
"C..ctor(System.Int32 X, System.Int32 Y)",
"System.Type C.EqualityContract.get",
"System.Type C.EqualityContract { get; }",
"System.Int32 C.<X>k__BackingField",
"System.Int32 C.X.get",
"void modreq(System.Runtime.CompilerServices.IsExternalInit) C.X.init",
"System.Int32 C.X { get; init; }",
"System.Int32 C.<Y>k__BackingField",
"System.Int32 C.Y.get",
"void modreq(System.Runtime.CompilerServices.IsExternalInit) C.Y.init",
"System.Int32 C.Y { get; init; }",
"void C.get_X()",
"void C.set_X()",
"System.Int32 C.get_Y(System.Int32 value)",
"System.Int32 C.set_Y(System.Int32 value)",
"System.String C.ToString()",
"System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)",
"System.Boolean C.op_Inequality(C? left, C? right)",
"System.Boolean C.op_Equality(C? left, C? right)",
"System.Int32 C.GetHashCode()",
"System.Boolean C.Equals(System.Object? obj)",
"System.Boolean C.Equals(C? other)",
"C C." + WellKnownMemberNames.CloneMethodName + "()",
"C..ctor(C original)",
"void C.Deconstruct(out System.Int32 X, out System.Int32 Y)"
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void RecordProperties_07()
{
var comp = CreateCompilation(@"
record C1(object P, object get_P);
record C2(object get_P, object P);");
comp.VerifyDiagnostics(
// (2,18): error CS0102: The type 'C1' already contains a definition for 'get_P'
// record C1(object P, object get_P);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C1", "get_P").WithLocation(2, 18),
// (3,32): error CS0102: The type 'C2' already contains a definition for 'get_P'
// record C2(object get_P, object P);
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C2", "get_P").WithLocation(3, 32)
);
}
[Fact]
public void RecordProperties_08()
{
var comp = CreateCompilation(@"
record C1(object O1)
{
public object O1 { get; } = O1;
public object O2 { get; } = O1;
}");
comp.VerifyDiagnostics();
}
[Fact]
public void RecordProperties_09()
{
var src =
@"record C(object P1, object P2, object P3, object P4)
{
class P1 { }
object P2 = 2;
int P3(object o) => 3;
int P4<T>(T t) => 4;
}";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (1,17): error CS0102: The type 'C' already contains a definition for 'P1'
// record C(object P1, object P2, object P3, object P4)
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P1").WithArguments("C", "P1").WithLocation(1, 17),
// (1,21): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater.
// record C(object P1, object P2, object P3, object P4)
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object P2").WithArguments("positional fields in records", "10.0").WithLocation(1, 21),
// (1,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, object P2, object P3, object P4)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 28),
// (5,9): error CS0102: The type 'C' already contains a definition for 'P3'
// int P3(object o) => 3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P3").WithArguments("C", "P3").WithLocation(5, 9),
// (6,9): error CS0102: The type 'C' already contains a definition for 'P4'
// int P4<T>(T t) => 4;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P4").WithArguments("C", "P4").WithLocation(6, 9)
);
comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10);
comp.VerifyDiagnostics(
// (1,17): error CS0102: The type 'C' already contains a definition for 'P1'
// record C(object P1, object P2, object P3, object P4)
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P1").WithArguments("C", "P1").WithLocation(1, 17),
// (1,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, object P2, object P3, object P4)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 28),
// (5,9): error CS0102: The type 'C' already contains a definition for 'P3'
// int P3(object o) => 3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P3").WithArguments("C", "P3").WithLocation(5, 9),
// (6,9): error CS0102: The type 'C' already contains a definition for 'P4'
// int P4<T>(T t) => 4;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P4").WithArguments("C", "P4").WithLocation(6, 9)
);
}
[ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)]
[WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")]
public void RestrictedTypesAndPointerTypes()
{
var src = @"
class C<T> { }
static class C2 { }
ref struct RefLike{}
unsafe record C( // 1
int* P1, // 2
int*[] P2, // 3
C<int*[]> P3,
delegate*<int, int> P4, // 4
void P5, // 5
C2 P6, // 6, 7
System.ArgIterator P7, // 8
System.TypedReference P8, // 9
RefLike P9); // 10
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugDll);
comp.VerifyEmitDiagnostics(
// (6,15): error CS0721: 'C2': static types cannot be used as parameters
// unsafe record C( // 1
Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "C").WithArguments("C2").WithLocation(6, 15),
// (7,10): error CS8908: The type 'int*' may not be used for a field of a record.
// int* P1, // 2
Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P1").WithArguments("int*").WithLocation(7, 10),
// (8,12): error CS8908: The type 'int*[]' may not be used for a field of a record.
// int*[] P2, // 3
Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P2").WithArguments("int*[]").WithLocation(8, 12),
// (10,25): error CS8908: The type 'delegate*<int, int>' may not be used for a field of a record.
// delegate*<int, int> P4, // 4
Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P4").WithArguments("delegate*<int, int>").WithLocation(10, 25),
// (11,5): error CS1536: Invalid parameter type 'void'
// void P5, // 5
Diagnostic(ErrorCode.ERR_NoVoidParameter, "void").WithLocation(11, 5),
// (12,8): error CS0722: 'C2': static types cannot be used as return types
// C2 P6, // 6, 7
Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "P6").WithArguments("C2").WithLocation(12, 8),
// (12,8): error CS0721: 'C2': static types cannot be used as parameters
// C2 P6, // 6, 7
Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "P6").WithArguments("C2").WithLocation(12, 8),
// (13,5): error CS0610: Field or property cannot be of type 'ArgIterator'
// System.ArgIterator P7, // 8
Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(13, 5),
// (14,5): error CS0610: Field or property cannot be of type 'TypedReference'
// System.TypedReference P8, // 9
Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(14, 5),
// (15,5): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct.
// RefLike P9); // 10
Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(15, 5)
);
}
[ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)]
[WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")]
public void RestrictedTypesAndPointerTypes_NominalMembers()
{
var src = @"
public class C<T> { }
public static class C2 { }
public ref struct RefLike{}
public unsafe record C
{
public int* f1; // 1
public int*[] f2; // 2
public C<int*[]> f3;
public delegate*<int, int> f4; // 3
public void f5; // 4
public C2 f6; // 5
public System.ArgIterator f7; // 6
public System.TypedReference f8; // 7
public RefLike f9; // 8
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugDll);
comp.VerifyEmitDiagnostics(
// (8,17): error CS8908: The type 'int*' may not be used for a field of a record.
// public int* f1; // 1
Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f1").WithArguments("int*").WithLocation(8, 17),
// (9,19): error CS8908: The type 'int*[]' may not be used for a field of a record.
// public int*[] f2; // 2
Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f2").WithArguments("int*[]").WithLocation(9, 19),
// (11,32): error CS8908: The type 'delegate*<int, int>' may not be used for a field of a record.
// public delegate*<int, int> f4; // 3
Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f4").WithArguments("delegate*<int, int>").WithLocation(11, 32),
// (12,12): error CS0670: Field cannot have void type
// public void f5; // 4
Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void").WithLocation(12, 12),
// (13,15): error CS0723: Cannot declare a variable of static type 'C2'
// public C2 f6; // 5
Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "f6").WithArguments("C2").WithLocation(13, 15),
// (14,12): error CS0610: Field or property cannot be of type 'ArgIterator'
// public System.ArgIterator f7; // 6
Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(14, 12),
// (15,12): error CS0610: Field or property cannot be of type 'TypedReference'
// public System.TypedReference f8; // 7
Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(15, 12),
// (16,12): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct.
// public RefLike f9; // 8
Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(16, 12)
);
}
[ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)]
[WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")]
public void RestrictedTypesAndPointerTypes_NominalMembers_AutoProperties()
{
var src = @"
public class C<T> { }
public static class C2 { }
public ref struct RefLike{}
public unsafe record C
{
public int* f1 { get; set; } // 1
public int*[] f2 { get; set; } // 2
public C<int*[]> f3 { get; set; }
public delegate*<int, int> f4 { get; set; } // 3
public void f5 { get; set; } // 4
public C2 f6 { get; set; } // 5, 6
public System.ArgIterator f7 { get; set; } // 6
public System.TypedReference f8 { get; set; } // 7
public RefLike f9 { get; set; } // 8
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugDll);
comp.VerifyEmitDiagnostics(
// (8,17): error CS8908: The type 'int*' may not be used for a field of a record.
// public int* f1 { get; set; } // 1
Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f1").WithArguments("int*").WithLocation(8, 17),
// (9,19): error CS8908: The type 'int*[]' may not be used for a field of a record.
// public int*[] f2 { get; set; } // 2
Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f2").WithArguments("int*[]").WithLocation(9, 19),
// (11,32): error CS8908: The type 'delegate*<int, int>' may not be used for a field of a record.
// public delegate*<int, int> f4 { get; set; } // 3
Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f4").WithArguments("delegate*<int, int>").WithLocation(11, 32),
// (12,17): error CS0547: 'C.f5': property or indexer cannot have void type
// public void f5 { get; set; } // 4
Diagnostic(ErrorCode.ERR_PropertyCantHaveVoidType, "f5").WithArguments("C.f5").WithLocation(12, 17),
// (13,20): error CS0722: 'C2': static types cannot be used as return types
// public C2 f6 { get; set; } // 5, 6
Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "get").WithArguments("C2").WithLocation(13, 20),
// (13,25): error CS0721: 'C2': static types cannot be used as parameters
// public C2 f6 { get; set; } // 5, 6
Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "set").WithArguments("C2").WithLocation(13, 25),
// (14,12): error CS0610: Field or property cannot be of type 'ArgIterator'
// public System.ArgIterator f7 { get; set; } // 6
Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(14, 12),
// (15,12): error CS0610: Field or property cannot be of type 'TypedReference'
// public System.TypedReference f8 { get; set; } // 7
Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(15, 12),
// (16,12): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct.
// public RefLike f9 { get; set; } // 8
Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(16, 12)
);
}
[Fact]
[WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")]
public void RestrictedTypesAndPointerTypes_PointerTypeAllowedForParameterAndProperty()
{
var src = @"
class C<T> { }
unsafe record C(int* P1, int*[] P2, C<int*[]> P3)
{
int* P1
{
get { System.Console.Write(""P1 ""); return null; }
init { }
}
int*[] P2
{
get { System.Console.Write(""P2 ""); return null; }
init { }
}
C<int*[]> P3
{
get { System.Console.Write(""P3 ""); return null; }
init { }
}
public unsafe static void Main()
{
var x = new C(null, null, null);
var (x1, x2, x3) = x;
System.Console.Write(""RAN"");
}
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugExe);
comp.VerifyEmitDiagnostics(
// (4,22): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// unsafe record C(int* P1, int*[] P2, C<int*[]> P3)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(4, 22),
// (4,33): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// unsafe record C(int* P1, int*[] P2, C<int*[]> P3)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(4, 33),
// (4,47): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name?
// unsafe record C(int* P1, int*[] P2, C<int*[]> P3)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(4, 47)
);
CompileAndVerify(comp, expectedOutput: "P1 P2 P3 RAN", verify: Verification.Skipped /* pointers */);
}
[ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)]
[WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")]
public void RestrictedTypesAndPointerTypes_StaticFields()
{
var src = @"
public class C<T> { }
public static class C2 { }
public ref struct RefLike{}
public unsafe record C
{
public static int* f1;
public static int*[] f2;
public static C<int*[]> f3;
public static delegate*<int, int> f4;
public static C2 f6; // 1
public static System.ArgIterator f7; // 2
public static System.TypedReference f8; // 3
public static RefLike f9; // 4
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugDll);
comp.VerifyEmitDiagnostics(
// (12,22): error CS0723: Cannot declare a variable of static type 'C2'
// public static C2 f6; // 1
Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "f6").WithArguments("C2").WithLocation(12, 22),
// (13,19): error CS0610: Field or property cannot be of type 'ArgIterator'
// public static System.ArgIterator f7; // 2
Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(13, 19),
// (14,19): error CS0610: Field or property cannot be of type 'TypedReference'
// public static System.TypedReference f8; // 3
Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(14, 19),
// (15,19): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct.
// public static RefLike f9; // 4
Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(15, 19)
);
}
[Fact, WorkItem(48584, "https://github.com/dotnet/roslyn/issues/48584")]
public void RecordProperties_11_UnreadPositionalParameter()
{
var comp = CreateCompilation(@"
record C1(object O1, object O2, object O3) // 1, 2
{
public object O1 { get; init; }
public object O2 { get; init; } = M(O2);
public object O3 { get; init; } = M(O3 = null);
private static object M(object o) => o;
}
record Base(object O);
record C2(object O4) : Base(O4) // we didn't complain because the parameter is read
{
public object O4 { get; init; }
}
record C3(object O5) : Base((System.Func<object, object>)(x => x)) // 3
{
public object O5 { get; init; }
}
record C4(object O6) : Base((System.Func<object, object>)(_ => O6))
{
public object O6 { get; init; }
}
record C5(object O7) : Base((System.Func<object, object>)(_ => (O7 = 42) )) // 4
{
public object O7 { get; init; }
}
");
comp.VerifyDiagnostics(
// (2,18): warning CS8907: Parameter 'O1' is unread. Did you forget to use it to initialize the property with that name?
// record C1(object O1, object O2, object O3) // 1, 2
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O1").WithArguments("O1").WithLocation(2, 18),
// (2,40): warning CS8907: Parameter 'O3' is unread. Did you forget to use it to initialize the property with that name?
// record C1(object O1, object O2, object O3) // 1, 2
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O3").WithArguments("O3").WithLocation(2, 40),
// (16,18): warning CS8907: Parameter 'O5' is unread. Did you forget to use it to initialize the property with that name?
// record C3(object O5) : Base((System.Func<object, object>)(x => x)) // 3
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O5").WithArguments("O5").WithLocation(16, 18),
// (26,18): warning CS8907: Parameter 'O7' is unread. Did you forget to use it to initialize the property with that name?
// record C5(object O7) : Base((System.Func<object, object>)(_ => (O7 = 42) )) // 4
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O7").WithArguments("O7").WithLocation(26, 18)
);
}
[Fact, WorkItem(48584, "https://github.com/dotnet/roslyn/issues/48584")]
public void RecordProperties_11_UnreadPositionalParameter_InRefOut()
{
var comp = CreateCompilation(@"
record C1(object O1, object O2, object O3) // 1
{
public object O1 { get; init; } = MIn(in O1);
public object O2 { get; init; } = MRef(ref O2);
public object O3 { get; init; } = MOut(out O3);
static object MIn(in object o) => o;
static object MRef(ref object o) => o;
static object MOut(out object o) => throw null;
}
");
comp.VerifyDiagnostics(
// (2,40): warning CS8907: Parameter 'O3' is unread. Did you forget to use it to initialize the property with that name?
// record C1(object O1, object O2, object O3) // 1
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O3").WithArguments("O3").WithLocation(2, 40)
);
}
[Fact]
public void EmptyRecord_01()
{
var src = @"
record C();
class Program
{
static void Main()
{
var x = new C();
var y = new C();
System.Console.WriteLine(x == y);
}
}
";
var verifier = CompileAndVerify(src, expectedOutput: "True");
verifier.VerifyDiagnostics();
verifier.VerifyIL("C..ctor()", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ret
}
");
var comp = (CSharpCompilation)verifier.Compilation;
var actualMembers = comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings();
var expectedMembers = new[]
{
"C..ctor()",
"System.Type C.EqualityContract.get",
"System.Type C.EqualityContract { get; }",
"System.String C.ToString()",
"System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)",
"System.Boolean C.op_Inequality(C? left, C? right)",
"System.Boolean C.op_Equality(C? left, C? right)",
"System.Int32 C.GetHashCode()",
"System.Boolean C.Equals(System.Object? obj)",
"System.Boolean C.Equals(C? other)",
"C C." + WellKnownMemberNames.CloneMethodName + "()",
"C..ctor(C original)"
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void EmptyRecord_01_RecordClass()
{
var src = @"
record class C();
class Program
{
static void Main()
{
var x = new C();
var y = new C();
System.Console.WriteLine(x == y);
}
}
";
var verifier = CompileAndVerify(src, expectedOutput: "True", parseOptions: TestOptions.Regular10);
verifier.VerifyDiagnostics();
verifier.VerifyIL("C..ctor()", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ret
}
");
var comp = (CSharpCompilation)verifier.Compilation;
var actualMembers = comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings();
var expectedMembers = new[]
{
"C..ctor()",
"System.Type C.EqualityContract.get",
"System.Type C.EqualityContract { get; }",
"System.String C.ToString()",
"System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)",
"System.Boolean C.op_Inequality(C? left, C? right)",
"System.Boolean C.op_Equality(C? left, C? right)",
"System.Int32 C.GetHashCode()",
"System.Boolean C.Equals(System.Object? obj)",
"System.Boolean C.Equals(C? other)",
"C C." + WellKnownMemberNames.CloneMethodName + "()",
"C..ctor(C original)"
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void EmptyRecord_02()
{
var src = @"
record C()
{
C(int x)
{}
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (4,5): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer.
// C(int x)
Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "C", isSuppressed: false).WithLocation(4, 5)
);
}
[Fact]
public void EmptyRecord_03()
{
var src = @"
record B
{
public B(int x)
{
System.Console.WriteLine(x);
}
}
record C() : B(12)
{
C(int x) : this()
{}
}
class Program
{
static void Main()
{
_ = new C();
}
}
";
var verifier = CompileAndVerify(src, expectedOutput: "12");
verifier.VerifyDiagnostics();
verifier.VerifyIL("C..ctor()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 12
IL_0003: call ""B..ctor(int)""
IL_0008: ret
}
");
}
[Fact, WorkItem(50170, "https://github.com/dotnet/roslyn/issues/50170")]
public void StaticCtor()
{
var src = @"
record R(int x)
{
static void Main() { }
static R()
{
System.Console.Write(""static ctor"");
}
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
// [ : R::set_x] Cannot change initonly field outside its .ctor.
CompileAndVerify(comp, expectedOutput: "static ctor", verify: Verification.Skipped);
}
[Fact, WorkItem(50170, "https://github.com/dotnet/roslyn/issues/50170")]
public void StaticCtor_ParameterlessPrimaryCtor()
{
var src = @"
record R()
{
static R() { }
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics();
}
[Fact, WorkItem(50170, "https://github.com/dotnet/roslyn/issues/50170")]
public void StaticCtor_CopyCtor()
{
var src = @"
record R()
{
static R(R r) { }
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (4,12): error CS0132: 'R.R(R)': a static constructor must be parameterless
// static R(R r) { }
Diagnostic(ErrorCode.ERR_StaticConstParam, "R").WithArguments("R.R(R)").WithLocation(4, 12)
);
}
[Fact]
public void WithExpr1()
{
var src = @"
record C(int X)
{
public static void Main()
{
var c = new C(0);
_ = Main() with { };
_ = default with { };
_ = null with { };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (7,13): error CS8802: The receiver of a `with` expression must have a valid non-void type.
// _ = Main() with { };
Diagnostic(ErrorCode.ERR_InvalidWithReceiverType, "Main()").WithLocation(7, 13),
// (8,13): error CS8716: There is no target type for the default literal.
// _ = default with { };
Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(8, 13),
// (9,13): error CS8802: The receiver of a `with` expression must have a valid non-void type.
// _ = null with { };
Diagnostic(ErrorCode.ERR_InvalidWithReceiverType, "null").WithLocation(9, 13)
);
}
[Fact]
public void WithExpr2()
{
var src = @"
using System;
record C(int X)
{
public static void Main()
{
var c1 = new C(1);
c1 = c1 with { };
var c2 = c1 with { X = 11 };
Console.WriteLine(c1.X);
Console.WriteLine(c2.X);
}
}";
CompileAndVerify(src, expectedOutput: @"1
11").VerifyDiagnostics();
}
[Fact]
public void WithExpr3()
{
var src = @"
record C(int X)
{
public static void Main()
{
var c = new C(0);
c = c with { };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
var root = comp.SyntaxTrees[0].GetRoot();
var main = root.DescendantNodes().OfType<MethodDeclarationSyntax>().First();
Assert.Equal("Main", main.Identifier.ToString());
VerifyFlowGraph(comp, main, expectedFlowGraph: @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [C c]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'c = new C(0)')
Left:
ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C(0)')
Right:
IObjectCreationOperation (Constructor: C..ctor(System.Int32 X)) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C(0)')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: '0')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Initializer:
null
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = c with { };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: 'c = c with { }')
Left:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
Right:
IInvocationOperation (virtual C C." + WellKnownMemberNames.CloneMethodName + @"()) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'c with { }')
Instance Receiver:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
Arguments(0)
Next (Regular) Block[B2]
Leaving: {R1}
}
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
");
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")]
[WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")]
public void WithExpr4()
{
var src = @"
class B
{
public B Clone() => null;
}
record C(int X) : B
{
public static void Main()
{
var c = new C(0);
c = c with { };
}
public new C Clone() => null;
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact]
public void WithExpr6()
{
var src = @"
record B
{
public int X { get; init; }
}
record C : B
{
public static void Main()
{
var c = new C();
c = c with { };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact]
public void WithExpr7()
{
var src = @"
record B
{
public int X { get; }
}
record C : B
{
public new int X { get; init; }
public static void Main()
{
var c = new C();
B b = c;
b = b with { X = 0 };
var b2 = c with { X = 0 };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (14,22): error CS0200: Property or indexer 'B.X' cannot be assigned to -- it is read only
// b = b with { X = 0 };
Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "X").WithArguments("B.X").WithLocation(14, 22)
);
}
[Fact]
public void WithExpr8()
{
var src = @"
record B
{
public int X { get; }
}
record C : B
{
public string Y { get; }
public static void Main()
{
var c = new C();
B b = c;
b = b with { };
b = c with { };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact]
public void WithExpr9()
{
var src = @"
record C(int X)
{
public string Clone() => null;
public static void Main()
{
var c = new C(0);
c = c with { };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (4,19): error CS8859: Members named 'Clone' are disallowed in records.
// public string Clone() => null;
Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(4, 19)
);
}
[Fact]
public void WithExpr11()
{
var src = @"
record C(int X)
{
public static void Main()
{
var c = new C(0);
c = c with { X = """"};
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (8,26): error CS0029: Cannot implicitly convert type 'string' to 'int'
// c = c with { X = ""};
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""""").WithArguments("string", "int").WithLocation(8, 26)
);
}
[Fact]
public void WithExpr12()
{
var src = @"
using System;
record C(int X)
{
public static void Main()
{
var c = new C(0);
Console.WriteLine(c.X);
c = c with { X = 5 };
Console.WriteLine(c.X);
}
}";
var verifier = CompileAndVerify(src, expectedOutput: @"0
5").VerifyDiagnostics();
verifier.VerifyIL("C.Main", @"
{
// Code size 40 (0x28)
.maxstack 3
IL_0000: ldc.i4.0
IL_0001: newobj ""C..ctor(int)""
IL_0006: dup
IL_0007: callvirt ""int C.X.get""
IL_000c: call ""void System.Console.WriteLine(int)""
IL_0011: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()""
IL_0016: dup
IL_0017: ldc.i4.5
IL_0018: callvirt ""void C.X.init""
IL_001d: callvirt ""int C.X.get""
IL_0022: call ""void System.Console.WriteLine(int)""
IL_0027: ret
}");
}
[Fact]
public void WithExpr13()
{
var src = @"
using System;
record C(int X, int Y)
{
public override string ToString() => X + "" "" + Y;
public static void Main()
{
var c = new C(0, 1);
Console.WriteLine(c);
c = c with { X = 5 };
Console.WriteLine(c);
}
}";
var verifier = CompileAndVerify(src, expectedOutput: @"0 1
5 1").VerifyDiagnostics();
verifier.VerifyIL("C.Main", @"
{
// Code size 31 (0x1f)
.maxstack 3
IL_0000: ldc.i4.0
IL_0001: ldc.i4.1
IL_0002: newobj ""C..ctor(int, int)""
IL_0007: dup
IL_0008: call ""void System.Console.WriteLine(object)""
IL_000d: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()""
IL_0012: dup
IL_0013: ldc.i4.5
IL_0014: callvirt ""void C.X.init""
IL_0019: call ""void System.Console.WriteLine(object)""
IL_001e: ret
}");
}
[Fact]
public void WithExpr14()
{
var src = @"
using System;
record C(int X, int Y)
{
public override string ToString() => X + "" "" + Y;
public static void Main()
{
var c = new C(0, 1);
Console.WriteLine(c);
c = c with { X = 5 };
Console.WriteLine(c);
c = c with { Y = 2 };
Console.WriteLine(c);
}
}";
var verifier = CompileAndVerify(src, expectedOutput: @"0 1
5 1
5 2").VerifyDiagnostics();
verifier.VerifyIL("C.Main", @"
{
// Code size 49 (0x31)
.maxstack 3
IL_0000: ldc.i4.0
IL_0001: ldc.i4.1
IL_0002: newobj ""C..ctor(int, int)""
IL_0007: dup
IL_0008: call ""void System.Console.WriteLine(object)""
IL_000d: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()""
IL_0012: dup
IL_0013: ldc.i4.5
IL_0014: callvirt ""void C.X.init""
IL_0019: dup
IL_001a: call ""void System.Console.WriteLine(object)""
IL_001f: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()""
IL_0024: dup
IL_0025: ldc.i4.2
IL_0026: callvirt ""void C.Y.init""
IL_002b: call ""void System.Console.WriteLine(object)""
IL_0030: ret
}");
}
[Fact]
public void WithExpr15()
{
var src = @"
record C(int X, int Y)
{
public static void Main()
{
var c = new C(0, 0);
c = c with { = 5 };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (8,22): error CS1525: Invalid expression term '='
// c = c with { = 5 };
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "=").WithArguments("=").WithLocation(8, 22)
);
}
[Fact]
public void WithExpr16()
{
var src = @"
record C(int X, int Y)
{
public static void Main()
{
var c = new C(0, 0);
c = c with { X = };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (8,26): error CS1525: Invalid expression term '}'
// c = c with { X = };
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "}").WithArguments("}").WithLocation(8, 26)
);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")]
[WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")]
public void WithExpr17()
{
var src = @"
record B
{
public int X { get; }
private B Clone() => null;
}
record C(int X) : B
{
public static void Main()
{
var b = new B();
b = b with { };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (12,13): error CS8803: The 'with' expression requires the receiver type 'B' to have a single accessible non-inherited instance method named "Clone".
// b = b with { };
Diagnostic(ErrorCode.ERR_CannotClone, "b").WithArguments("B").WithLocation(12, 13)
);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")]
[WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")]
public void WithExpr18()
{
var src = @"
class B
{
public int X { get; }
protected B Clone() => null;
}
record C(int X) : B
{
public static void Main()
{
var b = new B();
b = b with { };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (12,13): error CS8803: The receiver type 'B' does not have an accessible parameterless instance method named "Clone".
// b = b with { };
Diagnostic(ErrorCode.ERR_CannotClone, "b").WithArguments("B").WithLocation(12, 13)
);
}
[Fact]
public void WithExpr19()
{
var src = @"
class B
{
public int X { get; }
protected B Clone() => null;
}
record C(int X)
{
public static void Main()
{
var b = new B();
b = b with { };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (12,13): error CS8803: The 'with' expression requires the receiver type 'B' to have a single accessible non-inherited instance method named "Clone".
// b = b with { };
Diagnostic(ErrorCode.ERR_CannotClone, "b").WithArguments("B").WithLocation(12, 13)
);
}
[Fact]
public void WithExpr20()
{
var src = @"
using System;
record C
{
public event Action X;
public static void Main()
{
var c = new C();
c = c with { X = null };
}
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (5,25): warning CS0067: The event 'C.X' is never used
// public event Action X;
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "X").WithArguments("C.X").WithLocation(5, 25)
);
}
[Fact]
public void WithExpr21()
{
var src = @"
record B
{
public class X { }
}
class C
{
public static void Main()
{
var b = new B();
b = b with { X = 0 };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (11,22): error CS0572: 'X': cannot reference a type through an expression; try 'B.X' instead
// b = b with { X = 0 };
Diagnostic(ErrorCode.ERR_BadTypeReference, "X").WithArguments("X", "B.X").WithLocation(11, 22),
// (11,22): error CS1913: Member 'X' cannot be initialized. It is not a field or property.
// b = b with { X = 0 };
Diagnostic(ErrorCode.ERR_MemberCannotBeInitialized, "X").WithArguments("X").WithLocation(11, 22)
);
}
[Fact]
public void WithExpr22()
{
var src = @"
record B
{
public int X = 0;
}
class C
{
public static void Main()
{
var b = new B();
b = b with { };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact]
public void WithExpr23()
{
var src = @"
class B
{
public int X = 0;
public B Clone() => null;
}
record C(int X)
{
public static void Main()
{
var b = new B();
b = b with { Y = 2 };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (12,13): error CS8858: The receiver type 'B' is not a valid record type.
// b = b with { Y = 2 };
Diagnostic(ErrorCode.ERR_CannotClone, "b").WithArguments("B").WithLocation(12, 13),
// (12,22): error CS0117: 'B' does not contain a definition for 'Y'
// b = b with { Y = 2 };
Diagnostic(ErrorCode.ERR_NoSuchMember, "Y").WithArguments("B", "Y").WithLocation(12, 22)
);
}
[Fact]
public void WithExpr24_Dynamic()
{
var src = @"
record C(int X)
{
public static void Main()
{
dynamic c = new C(1);
var x = c with { X = 2 };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (7,17): error CS8858: The receiver type 'dynamic' is not a valid record type.
// var x = c with { X = 2 };
Diagnostic(ErrorCode.ERR_CannotClone, "c").WithArguments("dynamic").WithLocation(7, 17)
);
}
[Fact, WorkItem(46427, "https://github.com/dotnet/roslyn/issues/46427"), WorkItem(46249, "https://github.com/dotnet/roslyn/issues/46249")]
public void WithExpr25_TypeParameterWithRecordConstraint()
{
var src = @"
record R(int X);
class C
{
public static T M<T>(T t) where T : R
{
return t with { X = 2 };
}
static void Main()
{
System.Console.Write(M(new R(-1)).X);
}
}";
var verifier = CompileAndVerify(src, expectedOutput: "2").VerifyDiagnostics();
verifier.VerifyIL("C.M<T>(T)", @"
{
// Code size 29 (0x1d)
.maxstack 3
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: callvirt ""R R.<Clone>$()""
IL_000b: unbox.any ""T""
IL_0010: dup
IL_0011: box ""T""
IL_0016: ldc.i4.2
IL_0017: callvirt ""void R.X.init""
IL_001c: ret
}
");
}
[Fact, WorkItem(46427, "https://github.com/dotnet/roslyn/issues/46427"), WorkItem(46249, "https://github.com/dotnet/roslyn/issues/46249")]
public void WithExpr26_TypeParameterWithRecordAndInterfaceConstraint()
{
var src = @"
record R
{
public int X { get; set; }
}
interface I { int Property { get; set; } }
record T : R, I
{
public int Property { get; set; }
}
class C
{
public static T M<T>(T t) where T : R, I
{
return t with { X = 2, Property = 3 };
}
static void Main()
{
System.Console.WriteLine(M(new T()).X);
System.Console.WriteLine(M(new T()).Property);
}
}";
var verifier = CompileAndVerify(
new[] { src, IsExternalInitTypeDefinition },
parseOptions: TestOptions.Regular9,
verify: Verification.Passes,
expectedOutput:
@"2
3").VerifyDiagnostics();
verifier.VerifyIL("C.M<T>(T)", @"
{
// Code size 41 (0x29)
.maxstack 3
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: callvirt ""R R.<Clone>$()""
IL_000b: unbox.any ""T""
IL_0010: dup
IL_0011: box ""T""
IL_0016: ldc.i4.2
IL_0017: callvirt ""void R.X.set""
IL_001c: dup
IL_001d: box ""T""
IL_0022: ldc.i4.3
IL_0023: callvirt ""void I.Property.set""
IL_0028: ret
}
");
}
[Fact]
public void WithExpr27_InExceptionFilter()
{
var src = @"
var r = new R(1);
try
{
throw new System.Exception();
}
catch (System.Exception) when ((r = r with { X = 2 }).X == 2)
{
System.Console.Write(""RAN "");
System.Console.Write(r.X);
}
record R(int X);
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "RAN 2", verify: Verification.Skipped /* init-only */);
}
[Fact]
public void WithExpr28_WithAwait()
{
var src = @"
var r = new R(1);
r = r with { X = await System.Threading.Tasks.Task.FromResult(42) };
System.Console.Write(r.X);
record R(int X);
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree, ignoreAccessibility: false);
var x = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Last().Left;
Assert.Equal("X", x.ToString());
var symbol = model.GetSymbolInfo(x).Symbol;
Assert.Equal("System.Int32 R.X { get; init; }", symbol.ToTestDisplayString());
}
[Fact, WorkItem(46465, "https://github.com/dotnet/roslyn/issues/46465")]
public void WithExpr29_DisallowedAsExpressionStatement()
{
var src = @"
record R(int X)
{
void M()
{
var r = new R(1);
r with { X = 2 };
}
}
";
// Note: we didn't parse the `with` as a `with` expression, but as a broken local declaration
// Tracked by https://github.com/dotnet/roslyn/issues/46465
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (7,9): error CS0118: 'r' is a variable but is used like a type
// r with { X = 2 };
Diagnostic(ErrorCode.ERR_BadSKknown, "r").WithArguments("r", "variable", "type").WithLocation(7, 9),
// (7,11): warning CS0168: The variable 'with' is declared but never used
// r with { X = 2 };
Diagnostic(ErrorCode.WRN_UnreferencedVar, "with").WithArguments("with").WithLocation(7, 11),
// (7,16): error CS1002: ; expected
// r with { X = 2 };
Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(7, 16),
// (7,18): error CS8852: Init-only property or indexer 'R.X' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor.
// r with { X = 2 };
Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "X").WithArguments("R.X").WithLocation(7, 18),
// (7,24): error CS1002: ; expected
// r with { X = 2 };
Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(7, 24)
);
}
[Fact]
public void WithExpr30_TypeParameterNoConstraint()
{
var src = @"
class C
{
public static void M<T>(T t)
{
_ = t with { X = 2 };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (6,13): error CS8858: The receiver type 'T' is not a valid record type.
// _ = t with { X = 2 };
Diagnostic(ErrorCode.ERR_CannotClone, "t").WithArguments("T").WithLocation(6, 13),
// (6,22): error CS0117: 'T' does not contain a definition for 'X'
// _ = t with { X = 2 };
Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("T", "X").WithLocation(6, 22)
);
}
[Fact]
public void WithExpr31_TypeParameterWithInterfaceConstraint()
{
var src = @"
interface I { int Property { get; set; } }
class C
{
public static void M<T>(T t) where T : I
{
_ = t with { X = 2, Property = 3 };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (8,13): error CS8858: The receiver type 'T' is not a valid record type.
// _ = t with { X = 2, Property = 3 };
Diagnostic(ErrorCode.ERR_CannotClone, "t").WithArguments("T").WithLocation(8, 13),
// (8,22): error CS0117: 'T' does not contain a definition for 'X'
// _ = t with { X = 2, Property = 3 };
Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("T", "X").WithLocation(8, 22)
);
}
[Fact]
public void WithExpr32_TypeParameterWithInterfaceConstraint()
{
var ilSource = @"
.class interface public auto ansi abstract I
{
// Methods
.method public hidebysig specialname newslot abstract virtual
instance class I '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
} // end of method I::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig specialname newslot abstract virtual
instance int32 get_Property () cil managed
{
} // end of method I::get_Property
.method public hidebysig specialname newslot abstract virtual
instance void set_Property (
int32 'value'
) cil managed
{
} // end of method I::set_Property
// Properties
.property instance int32 Property()
{
.get instance int32 I::get_Property()
.set instance void I::set_Property(int32)
}
} // end of class I
";
var src = @"
class C
{
public static void M<T>(T t) where T : I
{
_ = t with { X = 2, Property = 3 };
}
}";
var comp = CreateCompilationWithIL(new[] { src, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (6,13): error CS8858: The receiver type 'T' is not a valid record type.
// _ = t with { X = 2, Property = 3 };
Diagnostic(ErrorCode.ERR_CannotClone, "t").WithArguments("T").WithLocation(6, 13),
// (6,22): error CS0117: 'T' does not contain a definition for 'X'
// _ = t with { X = 2, Property = 3 };
Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("T", "X").WithLocation(6, 22)
);
}
[Fact]
public void WithExpr33_TypeParameterWithStructureConstraint()
{
var ilSource = @"
.class public sequential ansi sealed beforefieldinit S
extends System.ValueType
{
.pack 0
.size 1
// Methods
.method public hidebysig
instance valuetype S '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
// Method begins at RVA 0x2150
// Code size 2 (0x2)
.maxstack 1
.locals init (
[0] valuetype S
)
IL_0000: ldnull
IL_0001: throw
} // end of method S::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig specialname
instance int32 get_Property () cil managed
{
// Method begins at RVA 0x215e
// Code size 2 (0x2)
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method S::get_Property
.method public hidebysig specialname
instance void set_Property (
int32 'value'
) cil managed
{
// Method begins at RVA 0x215e
// Code size 2 (0x2)
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method S::set_Property
// Properties
.property instance int32 Property()
{
.get instance int32 S::get_Property()
.set instance void S::set_Property(int32)
}
} // end of class S
";
var src = @"
abstract class Base<T>
{
public abstract void M<U>(U t) where U : T;
}
class C : Base<S>
{
public override void M<U>(U t)
{
_ = t with { X = 2, Property = 3 };
}
}";
var comp = CreateCompilationWithIL(new[] { src, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (11,13): error CS8773: Feature 'with on structs' is not available in C# 9.0. Please use language version 10.0 or greater.
// _ = t with { X = 2, Property = 3 };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "t with { X = 2, Property = 3 }").WithArguments("with on structs", "10.0").WithLocation(11, 13),
// (11,22): error CS0117: 'U' does not contain a definition for 'X'
// _ = t with { X = 2, Property = 3 };
Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("U", "X").WithLocation(11, 22),
// (11,29): error CS0117: 'U' does not contain a definition for 'Property'
// _ = t with { X = 2, Property = 3 };
Diagnostic(ErrorCode.ERR_NoSuchMember, "Property").WithArguments("U", "Property").WithLocation(11, 29)
);
comp = CreateCompilationWithIL(new[] { src, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular10);
comp.VerifyDiagnostics(
// (11,22): error CS0117: 'U' does not contain a definition for 'X'
// _ = t with { X = 2, Property = 3 };
Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("U", "X").WithLocation(11, 22),
// (11,29): error CS0117: 'U' does not contain a definition for 'Property'
// _ = t with { X = 2, Property = 3 };
Diagnostic(ErrorCode.ERR_NoSuchMember, "Property").WithArguments("U", "Property").WithLocation(11, 29)
);
}
[Fact, WorkItem(47513, "https://github.com/dotnet/roslyn/issues/47513")]
public void BothGetHashCodeAndEqualsAreDefined()
{
var src = @"
public sealed record C
{
public object Data;
public bool Equals(C c) { return false; }
public override int GetHashCode() { return 0; }
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact, WorkItem(47513, "https://github.com/dotnet/roslyn/issues/47513")]
public void BothGetHashCodeAndEqualsAreNotDefined()
{
var src = @"
public sealed record C
{
public object Data;
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact, WorkItem(47513, "https://github.com/dotnet/roslyn/issues/47513")]
public void GetHashCodeIsDefinedButEqualsIsNot()
{
var src = @"
public sealed record C
{
public object Data;
public override int GetHashCode() { return 0; }
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact, WorkItem(47513, "https://github.com/dotnet/roslyn/issues/47513")]
public void EqualsIsDefinedButGetHashCodeIsNot()
{
var src = @"
public sealed record C
{
public object Data;
public bool Equals(C c) { return false; }
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (5,17): warning CS8851: 'C' defines 'Equals' but not 'GetHashCode'
// public bool Equals(C c) { return false; }
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("C").WithLocation(5, 17));
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord()
{
var src = @"
class record { }
class C
{
record M(record r) => r;
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (2,7): error CS8860: Types and aliases should not be named 'record'.
// class record { }
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 7),
// (6,24): error CS1514: { expected
// record M(record r) => r;
Diagnostic(ErrorCode.ERR_LbraceExpected, "=>").WithLocation(6, 24),
// (6,24): error CS1513: } expected
// record M(record r) => r;
Diagnostic(ErrorCode.ERR_RbraceExpected, "=>").WithLocation(6, 24),
// (6,24): error CS1519: Invalid token '=>' in class, record, struct, or interface member declaration
// record M(record r) => r;
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=>").WithArguments("=>").WithLocation(6, 24),
// (6,28): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration
// record M(record r) => r;
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(6, 28),
// (6,28): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration
// record M(record r) => r;
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(6, 28)
);
comp = CreateCompilation(src, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics();
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord_Struct()
{
var src = @"
struct record { }
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (2,8): warning CS8860: Types and aliases should not be named 'record'.
// struct record { }
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 8)
);
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord_Interface()
{
var src = @"
interface record { }
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (2,11): warning CS8860: Types and aliases should not be named 'record'.
// interface record { }
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 11)
);
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord_Enum()
{
var src = @"
enum record { }
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (2,6): warning CS8860: Types and aliases should not be named 'record'.
// enum record { }
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 6)
);
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord_Delegate()
{
var src = @"
delegate void record();
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (2,15): warning CS8860: Types and aliases should not be named 'record'.
// delegate void record();
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 15)
);
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord_Delegate_Escaped()
{
var src = @"
delegate void @record();
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord_Alias()
{
var src = @"
using record = System.Console;
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (2,1): hidden CS8019: Unnecessary using directive.
// using record = System.Console;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using record = System.Console;").WithLocation(2, 1),
// (2,7): warning CS8860: Types and aliases should not be named 'record'.
// using record = System.Console;
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 7)
);
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord_Alias_Escaped()
{
var src = @"
using @record = System.Console;
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (2,1): hidden CS8019: Unnecessary using directive.
// using @record = System.Console;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using @record = System.Console;").WithLocation(2, 1)
);
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord_TypeParameter()
{
var src = @"
class C<record> { } // 1
class C2
{
class Nested<record> { } // 2
}
class C3
{
void Method<record>() { } // 3
void Method2()
{
void local<record>() // 4
{
local<record>();
}
}
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (2,9): warning CS8860: Types and aliases should not be named 'record'.
// class C<record> { } // 1
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 9),
// (5,18): warning CS8860: Types and aliases should not be named 'record'.
// class Nested<record> { } // 2
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(5, 18),
// (9,17): warning CS8860: Types and aliases should not be named 'record'.
// void Method<record>() { } // 3
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(9, 17),
// (13,20): warning CS8860: Types and aliases should not be named 'record'.
// void local<record>() // 4
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(13, 20)
);
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord_TypeParameter_Escaped()
{
var src = @"
class C<@record> { }
class C2
{
class Nested<@record> { }
}
class C3
{
void Method<@record>() { }
void Method2()
{
void local<@record>()
{
local<record>();
}
}
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord_TypeParameter_Escaped_Partial()
{
var src = @"
partial class C<@record> { }
partial class C<record> { } // 1
partial class D<record> { } // 2
partial class D<@record> { }
partial class D<record> { } // 3
partial class D<record> { } // 4
partial class E<@record> { }
partial class E<@record> { }
partial class C2
{
partial class Nested<record> { } // 5
partial class Nested<@record> { }
}
partial class C3
{
partial void Method<@record>();
partial void Method<record>() { } // 6
partial void Method2<@record>() { }
partial void Method2<record>(); // 7
partial void Method3<record>(); // 8
partial void Method3<@record>() { }
partial void Method4<record>() { } // 9
partial void Method4<@record>();
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (3,17): warning CS8860: Types and aliases should not be named 'record'.
// partial class C<record> { } // 1
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(3, 17),
// (5,17): warning CS8860: Types and aliases should not be named 'record'.
// partial class D<record> { } // 2
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(5, 17),
// (8,17): warning CS8860: Types and aliases should not be named 'record'.
// partial class D<record> { } // 3
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(8, 17),
// (9,17): warning CS8860: Types and aliases should not be named 'record'.
// partial class D<record> { } // 4
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(9, 17),
// (16,26): warning CS8860: Types and aliases should not be named 'record'.
// partial class Nested<record> { } // 5
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(16, 26),
// (22,25): warning CS8860: Types and aliases should not be named 'record'.
// partial void Method<record>() { } // 6
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(22, 25),
// (25,26): warning CS8860: Types and aliases should not be named 'record'.
// partial void Method2<record>(); // 7
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(25, 26),
// (27,26): warning CS8860: Types and aliases should not be named 'record'.
// partial void Method3<record>(); // 8
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(27, 26),
// (30,26): warning CS8860: Types and aliases should not be named 'record'.
// partial void Method4<record>() { } // 9
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(30, 26)
);
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord_Record()
{
var src = @"
record record { }
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (2,8): warning CS8860: Types and aliases should not be named 'record'.
// record record { }
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 8)
);
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord_TwoParts()
{
var src = @"
partial class record { }
partial class record { }
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (2,15): warning CS8860: Types and aliases should not be named 'record'.
// partial class record { }
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 15),
// (3,15): warning CS8860: Types and aliases should not be named 'record'.
// partial class record { }
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(3, 15)
);
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord_Escaped()
{
var src = @"
class @record { }
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord_MixedEscapedPartial()
{
var src = @"
partial class @record { }
partial class record { }
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (3,15): warning CS8860: Types and aliases should not be named 'record'.
// partial class record { }
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(3, 15)
);
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord_MixedEscapedPartial_ReversedOrder()
{
var src = @"
partial class record { }
partial class @record { }
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (2,15): warning CS8860: Types and aliases should not be named 'record'.
// partial class record { }
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 15)
);
}
[Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")]
public void TypeNamedRecord_BothEscapedPartial()
{
var src = @"
partial class @record { }
partial class @record { }
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact]
public void TypeNamedRecord_EscapedReturnType()
{
var src = @"
class record { }
class C
{
@record M(record r)
{
System.Console.Write(""RAN"");
return r;
}
public static void Main()
{
var c = new C();
_ = c.M(new record());
}
}";
var comp = CreateCompilation(src, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics(
// (2,7): warning CS8860: Types and aliases should not be named 'record'.
// class record { }
Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 7)
);
CompileAndVerify(comp, expectedOutput: "RAN");
}
[Fact, WorkItem(45591, "https://github.com/dotnet/roslyn/issues/45591")]
public void Clone_DisallowedInSource()
{
var src = @"
record C1(string Clone); // 1
record C2
{
string Clone; // 2
}
record C3
{
string Clone { get; set; } // 3
}
record C4
{
data string Clone; // 4 not yet supported
}
record C5
{
void Clone() { } // 5
void Clone(int i) { } // 6
}
record C6
{
class Clone { } // 7
}
record C7
{
delegate void Clone(); // 8
}
record C8
{
event System.Action Clone; // 9
}
record Clone
{
Clone(int i) => throw null;
}
record C9 : System.ICloneable
{
object System.ICloneable.Clone() => throw null;
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (2,18): error CS8859: Members named 'Clone' are disallowed in records.
// record C1(string Clone); // 1
Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(2, 18),
// (5,12): error CS8859: Members named 'Clone' are disallowed in records.
// string Clone; // 2
Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(5, 12),
// (5,12): warning CS0169: The field 'C2.Clone' is never used
// string Clone; // 2
Diagnostic(ErrorCode.WRN_UnreferencedField, "Clone").WithArguments("C2.Clone").WithLocation(5, 12),
// (9,12): error CS8859: Members named 'Clone' are disallowed in records.
// string Clone { get; set; } // 3
Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(9, 12),
// (13,10): error CS1519: Invalid token 'string' in class, record, struct, or interface member declaration
// data string Clone; // 4 not yet supported
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "string").WithArguments("string").WithLocation(13, 10),
// (13,17): error CS8859: Members named 'Clone' are disallowed in records.
// data string Clone; // 4 not yet supported
Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(13, 17),
// (13,17): warning CS0169: The field 'C4.Clone' is never used
// data string Clone; // 4 not yet supported
Diagnostic(ErrorCode.WRN_UnreferencedField, "Clone").WithArguments("C4.Clone").WithLocation(13, 17),
// (17,10): error CS8859: Members named 'Clone' are disallowed in records.
// void Clone() { } // 5
Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(17, 10),
// (18,10): error CS8859: Members named 'Clone' are disallowed in records.
// void Clone(int i) { } // 6
Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(18, 10),
// (22,11): error CS8859: Members named 'Clone' are disallowed in records.
// class Clone { } // 7
Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(22, 11),
// (26,19): error CS8859: Members named 'Clone' are disallowed in records.
// delegate void Clone(); // 8
Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(26, 19),
// (30,25): error CS8859: Members named 'Clone' are disallowed in records.
// event System.Action Clone; // 9
Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(30, 25),
// (30,25): warning CS0067: The event 'C8.Clone' is never used
// event System.Action Clone; // 9
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Clone").WithArguments("C8.Clone").WithLocation(30, 25)
);
}
[Fact]
public void Clone_LoadedFromMetadata()
{
// IL for ' public record Base(int i);' with a 'void Clone()' method added
var il = @"
.class public auto ansi beforefieldinit Base
extends [mscorlib]System.Object
implements class [mscorlib]System.IEquatable`1<class Base>
{
.field private initonly int32 '<i>k__BackingField'
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
.method public hidebysig specialname newslot virtual instance class Base '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldarg.0
IL_0001: newobj instance void Base::.ctor(class Base)
IL_0006: ret
}
.method family hidebysig specialname newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
IL_0000: ldtoken Base
IL_0005: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
IL_000a: ret
}
.method public hidebysig specialname rtspecialname instance void .ctor ( int32 i ) cil managed
{
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld int32 Base::'<i>k__BackingField'
IL_0007: ldarg.0
IL_0008: call instance void [mscorlib]System.Object::.ctor()
IL_000d: ret
}
.method public hidebysig specialname instance int32 get_i () cil managed
{
IL_0000: ldarg.0
IL_0001: ldfld int32 Base::'<i>k__BackingField'
IL_0006: ret
}
.method public hidebysig specialname instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_i ( int32 'value' ) cil managed
{
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld int32 Base::'<i>k__BackingField'
IL_0007: ret
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: call class [mscorlib]System.Collections.Generic.EqualityComparer`1<!0> class [mscorlib]System.Collections.Generic.EqualityComparer`1<class [mscorlib]System.Type>::get_Default()
IL_0005: ldarg.0
IL_0006: callvirt instance class [mscorlib]System.Type Base::get_EqualityContract()
IL_000b: callvirt instance int32 class [mscorlib]System.Collections.Generic.EqualityComparer`1<class [mscorlib]System.Type>::GetHashCode(!0)
IL_0010: ldc.i4 -1521134295
IL_0015: mul
IL_0016: call class [mscorlib]System.Collections.Generic.EqualityComparer`1<!0> class [mscorlib]System.Collections.Generic.EqualityComparer`1<int32>::get_Default()
IL_001b: ldarg.0
IL_001c: ldfld int32 Base::'<i>k__BackingField'
IL_0021: callvirt instance int32 class [mscorlib]System.Collections.Generic.EqualityComparer`1<int32>::GetHashCode(!0)
IL_0026: add
IL_0027: ret
}
.method public hidebysig virtual instance bool Equals ( object obj ) cil managed
{
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: isinst Base
IL_0007: callvirt instance bool Base::Equals(class Base)
IL_000c: ret
}
.method public newslot virtual instance bool Equals ( class Base '' ) cil managed
{
IL_0000: ldarg.1
IL_0001: brfalse.s IL_002d
IL_0003: ldarg.0
IL_0004: callvirt instance class [mscorlib]System.Type Base::get_EqualityContract()
IL_0009: ldarg.1
IL_000a: callvirt instance class [mscorlib]System.Type Base::get_EqualityContract()
IL_000f: call bool [mscorlib]System.Type::op_Equality(class [mscorlib]System.Type, class [mscorlib]System.Type)
IL_0014: brfalse.s IL_002d
IL_0016: call class [mscorlib]System.Collections.Generic.EqualityComparer`1<!0> class [mscorlib]System.Collections.Generic.EqualityComparer`1<int32>::get_Default()
IL_001b: ldarg.0
IL_001c: ldfld int32 Base::'<i>k__BackingField'
IL_0021: ldarg.1
IL_0022: ldfld int32 Base::'<i>k__BackingField'
IL_0027: callvirt instance bool class [mscorlib]System.Collections.Generic.EqualityComparer`1<int32>::Equals(!0, !0)
IL_002c: ret
IL_002d: ldc.i4.0
IL_002e: ret
}
.method family hidebysig specialname rtspecialname instance void .ctor ( class Base '' ) cil managed
{
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ldarg.0
IL_0007: ldarg.1
IL_0008: ldfld int32 Base::'<i>k__BackingField'
IL_000d: stfld int32 Base::'<i>k__BackingField'
IL_0012: ret
}
.method public hidebysig instance void Deconstruct ( [out] int32& i ) cil managed
{
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: call instance int32 Base::get_i()
IL_0007: stind.i4
IL_0008: ret
}
.method public hidebysig instance void Clone () cil managed
{
IL_0000: ldstr ""RAN""
IL_0005: call void [mscorlib]System.Console::Write(string)
IL_000a: ret
}
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type Base::get_EqualityContract()
}
.property instance int32 i()
{
.get instance int32 Base::get_i()
.set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) Base::set_i(int32)
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}
.class public auto ansi abstract sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends [mscorlib]System.Object
{
}
";
var src = @"
record R(int i) : Base(i);
public class C
{
public static void Main()
{
var r = new R(1);
r.Clone();
}
}
";
var comp = CreateCompilationWithIL(src, il, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "RAN").VerifyDiagnostics();
// Note: we do load the Clone method from metadata
}
[Fact]
public void Clone_01()
{
var src = @"
abstract sealed record C1;
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (2,24): error CS0418: 'C1': an abstract type cannot be sealed or static
// abstract sealed record C1;
Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C1").WithArguments("C1").WithLocation(2, 24)
);
var clone = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.CloneMethodName);
Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility);
Assert.False(clone.IsOverride);
Assert.False(clone.IsVirtual);
Assert.True(clone.IsAbstract);
Assert.False(clone.IsSealed);
Assert.True(clone.IsImplicitlyDeclared);
Assert.True(clone.ContainingType.IsSealed);
Assert.True(clone.ContainingType.IsAbstract);
var namedTypeSymbol = comp.GlobalNamespace.GetTypeMember("C1");
Assert.True(namedTypeSymbol.IsRecord);
Assert.Equal("record C1", namedTypeSymbol
.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword)));
}
[Fact]
public void Clone_02()
{
var src = @"
sealed abstract record C1;
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (2,24): error CS0418: 'C1': an abstract type cannot be sealed or static
// sealed abstract record C1;
Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C1").WithArguments("C1").WithLocation(2, 24)
);
var clone = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.CloneMethodName);
Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility);
Assert.False(clone.IsOverride);
Assert.False(clone.IsVirtual);
Assert.True(clone.IsAbstract);
Assert.False(clone.IsSealed);
Assert.True(clone.IsImplicitlyDeclared);
Assert.True(clone.ContainingType.IsSealed);
Assert.True(clone.ContainingType.IsAbstract);
var namedTypeSymbol = comp.GlobalNamespace.GetTypeMember("C1");
Assert.True(namedTypeSymbol.IsRecord);
Assert.Equal("record C1", namedTypeSymbol
.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword)));
}
[Fact]
public void Clone_03()
{
var src = @"
record C1;
abstract sealed record C2 : C1;
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (3,24): error CS0418: 'C2': an abstract type cannot be sealed or static
// abstract sealed record C2 : C1;
Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C2").WithArguments("C2").WithLocation(3, 24)
);
var clone = comp.GetMember<MethodSymbol>("C2." + WellKnownMemberNames.CloneMethodName);
Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility);
Assert.True(clone.IsOverride);
Assert.False(clone.IsVirtual);
Assert.True(clone.IsAbstract);
Assert.False(clone.IsSealed);
Assert.True(clone.IsImplicitlyDeclared);
Assert.True(clone.ContainingType.IsSealed);
Assert.True(clone.ContainingType.IsAbstract);
}
[Fact]
public void Clone_04()
{
var src = @"
record C1;
sealed abstract record C2 : C1;
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (3,24): error CS0418: 'C2': an abstract type cannot be sealed or static
// sealed abstract record C2 : C1;
Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C2").WithArguments("C2").WithLocation(3, 24)
);
var clone = comp.GetMember<MethodSymbol>("C2." + WellKnownMemberNames.CloneMethodName);
Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility);
Assert.True(clone.IsOverride);
Assert.False(clone.IsVirtual);
Assert.True(clone.IsAbstract);
Assert.False(clone.IsSealed);
Assert.True(clone.IsImplicitlyDeclared);
Assert.True(clone.ContainingType.IsSealed);
Assert.True(clone.ContainingType.IsAbstract);
var namedTypeSymbol = comp.GlobalNamespace.GetTypeMember("C1");
Assert.True(namedTypeSymbol.IsRecord);
Assert.Equal("record C1", namedTypeSymbol
.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword)));
}
[Fact]
public void Clone_05_IntReturnType_UsedAsBaseType()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool PrintMembers ( class [mscorlib]System.Text.StringBuilder builder ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,19): error CS8864: Records may only inherit from object or another record
// public record B : A {
Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(2, 19)
);
Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A")
.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword)));
}
[Fact]
public void Clone_06_IntReturnType_UsedInWith()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
} // end of class A
";
var source = @"
public class Program
{
static void Main()
{
A x = new A() with { };
}
}
";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (6,15): error CS8858: The receiver type 'A' is not a valid record type.
// A x = new A() with { };
Diagnostic(ErrorCode.ERR_CannotClone, "new A()").WithArguments("A").WithLocation(6, 15)
);
Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A")
.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword)));
}
[Fact]
public void Clone_07_Ambiguous_UsedAsBaseType()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool PrintMembers ( class [mscorlib]System.Text.StringBuilder builder ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,19): error CS8864: Records may only inherit from object or another record
// public record B : A {
Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(2, 19)
);
Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A")
.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword)));
}
[Fact]
public void Clone_08_Ambiguous_UsedInWith()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
} // end of class A
";
var source = @"
public class Program
{
static void Main()
{
A x = new A() with { };
}
}
";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (6,15): error CS8858: The receiver type 'A' is not a valid record type.
// A x = new A() with { };
Diagnostic(ErrorCode.ERR_CannotClone, "new A()").WithArguments("A").WithLocation(6, 15)
);
Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A")
.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword)));
}
[Fact]
public void Clone_09_AmbiguousReverseOrder_UsedAsBaseType()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig specialname newslot virtual
instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool PrintMembers ( class [mscorlib]System.Text.StringBuilder builder ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,19): error CS8864: Records may only inherit from object or another record
// public record B : A {
Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(2, 19)
);
Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A")
.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword)));
}
[Fact]
public void Clone_10_AmbiguousReverseOrder_UsedInWith()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig specialname newslot virtual
instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
} // end of class A
";
var source = @"
public class Program
{
static void Main()
{
A x = new A() with { };
}
}
";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (6,15): error CS8858: The receiver type 'A' is not a valid record type.
// A x = new A() with { };
Diagnostic(ErrorCode.ERR_CannotClone, "new A()").WithArguments("A").WithLocation(6, 15)
);
Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A")
.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword)));
}
[Fact]
public void Clone_11()
{
string source1 = @"
public record A;
";
var comp1Ref = CreateCompilation(source1).EmitToImageReference();
string source2 = @"
public record B(int X) : A;
";
var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference();
string source3 = @"
class Program
{
public static void Main()
{
var c1 = new B(1);
var c2 = c1 with { X = 11 };
System.Console.WriteLine(c1.X);
System.Console.WriteLine(c2.X);
}
}
";
CompileAndVerify(source3, references: new[] { comp1Ref, comp2Ref }, expectedOutput: @"1
11").VerifyDiagnostics();
}
[Fact]
public void Clone_12()
{
string source1 = @"
public record A;
";
var comp1Ref = CreateCompilation(new[] { source1, IsExternalInitTypeDefinition }, assemblyName: "Clone_12", parseOptions: TestOptions.Regular9).EmitToImageReference();
string source2 = @"
public record B(int X) : A;
";
var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference();
string source3 = @"
class Program
{
public static void Main()
{
var c1 = new B(1);
var c2 = c1 with { X = 11 };
System.Console.WriteLine(c1.X);
System.Console.WriteLine(c2.X);
}
}
";
var comp3 = CreateCompilation(new[] { source3, IsExternalInitTypeDefinition }, references: new[] { comp2Ref }, parseOptions: TestOptions.Regular9);
comp3.VerifyEmitDiagnostics(
// (7,18): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_12, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// var c2 = c1 with { X = 11 };
Diagnostic(ErrorCode.ERR_NoTypeDef, "c1").WithArguments("A", "Clone_12, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18)
);
}
[Fact]
public void Clone_13()
{
string source1 = @"
public record A;
";
var comp1Ref = CreateCompilation(new[] { source1, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9).EmitToImageReference();
string source2 = @"
public record B(int X) : A;
";
var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, assemblyName: "Clone_13", references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference();
string source3 = @"
public record C(int X) : B(X);
";
var comp3Ref = CreateCompilation(new[] { source3, IsExternalInitTypeDefinition }, references: new[] { comp1Ref, comp2Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference();
string source4 = @"
class Program
{
public static void Main()
{
var c1 = new C(1);
var c2 = c1 with { X = 11 };
}
}
";
var comp4 = CreateCompilation(new[] { source4, IsExternalInitTypeDefinition }, references: new[] { comp1Ref, comp3Ref }, parseOptions: TestOptions.Regular9);
comp4.VerifyEmitDiagnostics(
// (7,18): error CS8858: The receiver type 'C' is not a valid record type.
// var c2 = c1 with { X = 11 };
Diagnostic(ErrorCode.ERR_CannotClone, "c1").WithArguments("C").WithLocation(7, 18),
// (7,18): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// var c2 = c1 with { X = 11 };
Diagnostic(ErrorCode.ERR_NoTypeDef, "c1").WithArguments("B", "Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18),
// (7,28): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// var c2 = c1 with { X = 11 };
Diagnostic(ErrorCode.ERR_NoTypeDef, "X").WithArguments("B", "Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 28),
// (7,28): error CS0117: 'C' does not contain a definition for 'X'
// var c2 = c1 with { X = 11 };
Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("C", "X").WithLocation(7, 28)
);
var comp5 = CreateCompilation(new[] { source4, IsExternalInitTypeDefinition }, references: new[] { comp3Ref }, parseOptions: TestOptions.Regular9);
comp5.VerifyEmitDiagnostics(
// (7,18): error CS8858: The receiver type 'C' is not a valid record type.
// var c2 = c1 with { X = 11 };
Diagnostic(ErrorCode.ERR_CannotClone, "c1").WithArguments("C").WithLocation(7, 18),
// (7,18): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// var c2 = c1 with { X = 11 };
Diagnostic(ErrorCode.ERR_NoTypeDef, "c1").WithArguments("B", "Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18),
// (7,28): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// var c2 = c1 with { X = 11 };
Diagnostic(ErrorCode.ERR_NoTypeDef, "X").WithArguments("B", "Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 28),
// (7,28): error CS0117: 'C' does not contain a definition for 'X'
// var c2 = c1 with { X = 11 };
Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("C", "X").WithLocation(7, 28)
);
}
[Fact]
public void Clone_14()
{
string source1 = @"
public record A;
";
var comp1Ref = CreateCompilation(source1).EmitToImageReference();
string source2 = @"
public record B(int X) : A;
";
var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference();
string source3 = @"
record C(int X) : B(X)
{
public static void Main()
{
var c1 = new C(1);
var c2 = c1 with { X = 11 };
System.Console.WriteLine(c1.X);
System.Console.WriteLine(c2.X);
}
}
";
CompileAndVerify(source3, references: new[] { comp1Ref, comp2Ref }, expectedOutput: @"1
11").VerifyDiagnostics();
}
[Fact]
public void Clone_15()
{
string source1 = @"
public record A;
";
var comp1Ref = CreateCompilation(new[] { source1, IsExternalInitTypeDefinition }, assemblyName: "Clone_15", parseOptions: TestOptions.Regular9).EmitToImageReference();
string source2 = @"
public record B(int X) : A;
";
var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference();
string source3 = @"
record C(int X) : B(X)
{
public static void Main()
{
var c1 = new C(1);
var c2 = c1 with { X = 11 };
System.Console.WriteLine(c1.X);
System.Console.WriteLine(c2.X);
}
}
";
var comp3 = CreateCompilation(new[] { source3, IsExternalInitTypeDefinition }, references: new[] { comp2Ref }, parseOptions: TestOptions.Regular9);
comp3.VerifyEmitDiagnostics(
// (2,8): error CS8869: 'C.Equals(object?)' does not override expected method from 'object'.
// record C(int X) : B(X)
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "C").WithArguments("C.Equals(object?)").WithLocation(2, 8),
// (2,8): error CS8869: 'C.GetHashCode()' does not override expected method from 'object'.
// record C(int X) : B(X)
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "C").WithArguments("C.GetHashCode()").WithLocation(2, 8),
// (2,8): error CS8869: 'C.ToString()' does not override expected method from 'object'.
// record C(int X) : B(X)
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "C").WithArguments("C.ToString()").WithLocation(2, 8),
// (2,8): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// record C(int X) : B(X)
Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 8),
// (2,19): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// record C(int X) : B(X)
Diagnostic(ErrorCode.ERR_NoTypeDef, "B").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19),
// (2,19): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// record C(int X) : B(X)
Diagnostic(ErrorCode.ERR_NoTypeDef, "B").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19),
// (6,22): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// var c1 = new C(1);
Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 22),
// (7,18): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// var c2 = c1 with { X = 11 };
Diagnostic(ErrorCode.ERR_NoTypeDef, "c1").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18),
// (8,9): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// System.Console.WriteLine(c1.X);
Diagnostic(ErrorCode.ERR_NoTypeDef, "System").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(8, 9),
// (9,9): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// System.Console.WriteLine(c2.X);
Diagnostic(ErrorCode.ERR_NoTypeDef, "System").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(9, 9)
);
}
[Fact]
public void Clone_16()
{
string source1 = @"
public record A;
";
var comp1Ref = CreateCompilation(new[] { source1, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9).EmitToImageReference();
string source2 = @"
public record B(int X) : A;
";
var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, assemblyName: "Clone_16", references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference();
string source3 = @"
public record C(int X) : B(X);
";
var comp3Ref = CreateCompilation(new[] { source3, IsExternalInitTypeDefinition }, references: new[] { comp1Ref, comp2Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference();
string source4 = @"
record D(int X) : C(X)
{
public static void Main()
{
var c1 = new D(1);
var c2 = c1 with { X = 11 };
}
}
";
var comp4 = CreateCompilation(new[] { source4, IsExternalInitTypeDefinition }, references: new[] { comp1Ref, comp3Ref }, parseOptions: TestOptions.Regular9);
comp4.VerifyEmitDiagnostics(
// (2,8): error CS8869: 'D.Equals(object?)' does not override expected method from 'object'.
// record D(int X) : C(X)
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.Equals(object?)").WithLocation(2, 8),
// (2,8): error CS8869: 'D.GetHashCode()' does not override expected method from 'object'.
// record D(int X) : C(X)
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.GetHashCode()").WithLocation(2, 8),
// (2,8): error CS8869: 'D.ToString()' does not override expected method from 'object'.
// record D(int X) : C(X)
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.ToString()").WithLocation(2, 8),
// (2,19): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// record D(int X) : C(X)
Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19),
// (2,19): error CS8864: Records may only inherit from object or another record
// record D(int X) : C(X)
Diagnostic(ErrorCode.ERR_BadRecordBase, "C").WithLocation(2, 19),
// (2,19): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// record D(int X) : C(X)
Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19),
// (6,22): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// var c1 = new D(1);
Diagnostic(ErrorCode.ERR_NoTypeDef, "D").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 22)
);
var comp5 = CreateCompilation(new[] { source4, IsExternalInitTypeDefinition }, references: new[] { comp3Ref }, parseOptions: TestOptions.Regular9);
comp5.VerifyEmitDiagnostics(
// (2,8): error CS8869: 'D.Equals(object?)' does not override expected method from 'object'.
// record D(int X) : C(X)
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.Equals(object?)").WithLocation(2, 8),
// (2,8): error CS8869: 'D.GetHashCode()' does not override expected method from 'object'.
// record D(int X) : C(X)
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.GetHashCode()").WithLocation(2, 8),
// (2,8): error CS8869: 'D.ToString()' does not override expected method from 'object'.
// record D(int X) : C(X)
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.ToString()").WithLocation(2, 8),
// (2,19): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// record D(int X) : C(X)
Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19),
// (2,19): error CS8864: Records may only inherit from object or another record
// record D(int X) : C(X)
Diagnostic(ErrorCode.ERR_BadRecordBase, "C").WithLocation(2, 19),
// (2,19): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// record D(int X) : C(X)
Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19),
// (6,22): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// var c1 = new D(1);
Diagnostic(ErrorCode.ERR_NoTypeDef, "D").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 22)
);
}
[Fact]
public void Clone_17_NonOverridable()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool PrintMembers ( class [mscorlib]System.Text.StringBuilder builder ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,19): error CS8864: Records may only inherit from object or another record
// public record B : A {
Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(2, 19)
);
Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A")
.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword)));
}
[Fact]
public void Clone_18_NonOverridable()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual final
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool PrintMembers ( class [mscorlib]System.Text.StringBuilder builder ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,19): error CS8864: Records may only inherit from object or another record
// public record B : A {
Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(2, 19)
);
Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A")
.ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword)));
}
[Fact]
public void Clone_19()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
.class public auto ansi beforefieldinit B
extends A
{
// Methods
.method public hidebysig specialname virtual final
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method B::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public final virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public newslot virtual
instance bool Equals (
class B ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class B ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method B::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type B::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class B
";
var source = @"
public record C : B {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0239: 'C.<Clone>$()': cannot override inherited member 'B.<Clone>$()' because it is sealed
// public record C : B {
Diagnostic(ErrorCode.ERR_CantOverrideSealed, "C").WithArguments("C.<Clone>$()", "B.<Clone>$()").WithLocation(2, 15)
);
}
[Fact, WorkItem(47093, "https://github.com/dotnet/roslyn/issues/47093")]
public void ToString_TopLevelRecord_Empty()
{
var src = @"
var c1 = new C1();
System.Console.Write(c1.ToString());
record C1;
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
var v = CompileAndVerify(comp, expectedOutput: "C1 { }");
var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName);
Assert.Equal(Accessibility.Protected, print.DeclaredAccessibility);
Assert.False(print.IsOverride);
Assert.True(print.IsVirtual);
Assert.False(print.IsAbstract);
Assert.False(print.IsSealed);
Assert.True(print.IsImplicitlyDeclared);
var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString);
Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility);
Assert.True(toString.IsOverride);
Assert.False(toString.IsVirtual);
Assert.False(toString.IsAbstract);
Assert.False(toString.IsSealed);
Assert.True(toString.IsImplicitlyDeclared);
v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @"
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: ret
}
");
v.VerifyIL("C1." + WellKnownMemberNames.ObjectToString, @"
{
// Code size 64 (0x40)
.maxstack 2
.locals init (System.Text.StringBuilder V_0)
IL_0000: newobj ""System.Text.StringBuilder..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldstr ""C1""
IL_000c: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_0011: pop
IL_0012: ldloc.0
IL_0013: ldstr "" { ""
IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_001d: pop
IL_001e: ldarg.0
IL_001f: ldloc.0
IL_0020: callvirt ""bool C1.PrintMembers(System.Text.StringBuilder)""
IL_0025: brfalse.s IL_0030
IL_0027: ldloc.0
IL_0028: ldc.i4.s 32
IL_002a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)""
IL_002f: pop
IL_0030: ldloc.0
IL_0031: ldc.i4.s 125
IL_0033: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)""
IL_0038: pop
IL_0039: ldloc.0
IL_003a: callvirt ""string object.ToString()""
IL_003f: ret
}
");
}
[Fact]
public void ToString_TopLevelRecord_AbstractRecord()
{
var src = @"
var c2 = new C2();
System.Console.Write(c2);
abstract record C1;
record C2 : C1
{
public override string ToString() => base.ToString();
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
var v = CompileAndVerify(comp, expectedOutput: "C1 { }");
var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName);
Assert.Equal(Accessibility.Protected, print.DeclaredAccessibility);
Assert.False(print.IsOverride);
Assert.True(print.IsVirtual);
Assert.False(print.IsAbstract);
Assert.False(print.IsSealed);
Assert.True(print.IsImplicitlyDeclared);
var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString);
Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility);
Assert.True(toString.IsOverride);
Assert.False(toString.IsVirtual);
Assert.False(toString.IsAbstract);
Assert.False(toString.IsSealed);
Assert.True(toString.IsImplicitlyDeclared);
v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @"
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: ret
}
");
v.VerifyIL("C1." + WellKnownMemberNames.ObjectToString, @"
{
// Code size 64 (0x40)
.maxstack 2
.locals init (System.Text.StringBuilder V_0)
IL_0000: newobj ""System.Text.StringBuilder..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldstr ""C1""
IL_000c: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_0011: pop
IL_0012: ldloc.0
IL_0013: ldstr "" { ""
IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_001d: pop
IL_001e: ldarg.0
IL_001f: ldloc.0
IL_0020: callvirt ""bool C1.PrintMembers(System.Text.StringBuilder)""
IL_0025: brfalse.s IL_0030
IL_0027: ldloc.0
IL_0028: ldc.i4.s 32
IL_002a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)""
IL_002f: pop
IL_0030: ldloc.0
IL_0031: ldc.i4.s 125
IL_0033: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)""
IL_0038: pop
IL_0039: ldloc.0
IL_003a: callvirt ""string object.ToString()""
IL_003f: ret
}
");
}
[Fact]
public void ToString_DerivedRecord_AbstractRecord()
{
var src = @"
var c2 = new C2();
System.Console.Write(c2);
record Base;
abstract record C1 : Base;
record C2 : C1
{
public override string ToString() => base.ToString();
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
var v = CompileAndVerify(comp, expectedOutput: "C1 { }");
var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName);
Assert.Equal(Accessibility.Protected, print.DeclaredAccessibility);
Assert.True(print.IsOverride);
Assert.False(print.IsVirtual);
Assert.False(print.IsAbstract);
Assert.False(print.IsSealed);
Assert.True(print.IsImplicitlyDeclared);
var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString);
Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility);
Assert.True(toString.IsOverride);
Assert.False(toString.IsVirtual);
Assert.False(toString.IsAbstract);
Assert.False(toString.IsSealed);
Assert.True(toString.IsImplicitlyDeclared);
v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""bool Base.PrintMembers(System.Text.StringBuilder)""
IL_0007: ret
}
");
v.VerifyIL("C1." + WellKnownMemberNames.ObjectToString, @"
{
// Code size 64 (0x40)
.maxstack 2
.locals init (System.Text.StringBuilder V_0)
IL_0000: newobj ""System.Text.StringBuilder..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldstr ""C1""
IL_000c: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_0011: pop
IL_0012: ldloc.0
IL_0013: ldstr "" { ""
IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_001d: pop
IL_001e: ldarg.0
IL_001f: ldloc.0
IL_0020: callvirt ""bool Base.PrintMembers(System.Text.StringBuilder)""
IL_0025: brfalse.s IL_0030
IL_0027: ldloc.0
IL_0028: ldc.i4.s 32
IL_002a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)""
IL_002f: pop
IL_0030: ldloc.0
IL_0031: ldc.i4.s 125
IL_0033: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)""
IL_0038: pop
IL_0039: ldloc.0
IL_003a: callvirt ""string object.ToString()""
IL_003f: ret
}
");
}
[Fact]
public void ToString_TopLevelRecord_MissingStringBuilder()
{
var src = @"
record C1;
";
var comp = CreateCompilation(src);
comp.MakeTypeMissing(WellKnownType.System_Text_StringBuilder);
comp.VerifyEmitDiagnostics(
// (2,1): error CS0518: Predefined type 'System.Text.StringBuilder' is not defined or imported
// record C1;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "record C1;").WithArguments("System.Text.StringBuilder").WithLocation(2, 1),
// (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder..ctor'
// record C1;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1;").WithArguments("System.Text.StringBuilder", ".ctor").WithLocation(2, 1),
// (2,8): error CS0518: Predefined type 'System.Text.StringBuilder' is not defined or imported
// record C1;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "C1").WithArguments("System.Text.StringBuilder").WithLocation(2, 8)
);
}
[Fact]
public void ToString_TopLevelRecord_MissingStringBuilderCtor()
{
var src = @"
record C1;
";
var comp = CreateCompilation(src);
comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__ctor);
comp.VerifyEmitDiagnostics(
// (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder..ctor'
// record C1;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1;").WithArguments("System.Text.StringBuilder", ".ctor").WithLocation(2, 1)
);
}
[Fact]
public void ToString_TopLevelRecord_MissingStringBuilderAppendString()
{
var src = @"
record C1;
";
var comp = CreateCompilation(src);
comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__AppendString);
comp.VerifyEmitDiagnostics(
// (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append'
// record C1;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1;").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1)
);
}
[Fact]
public void ToString_TopLevelRecord_OneProperty_MissingStringBuilderAppendString()
{
var src = @"
record C1(int P);
";
var comp = CreateCompilation(src);
comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__AppendString);
comp.VerifyEmitDiagnostics(
// (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append'
// record C1(int P);
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1),
// (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append'
// record C1(int P);
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1)
);
}
[Fact]
public void ToString_TopLevelRecord_OneProperty_MissingStringBuilderAppendStringAndChar()
{
var src = @"
record C1(int P);
";
var comp = CreateCompilation(src);
comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__AppendString);
comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__AppendChar);
comp.VerifyEmitDiagnostics(
// (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append'
// record C1(int P);
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1),
// (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append'
// record C1(int P);
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1)
);
}
[Fact]
public void ToString_TopLevelRecord_Empty_Sealed()
{
var src = @"
var c1 = new C1();
System.Console.Write(c1.ToString());
sealed record C1;
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "C1 { }");
var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName);
Assert.Equal(Accessibility.Private, print.DeclaredAccessibility);
Assert.False(print.IsOverride);
Assert.False(print.IsVirtual);
Assert.False(print.IsAbstract);
Assert.False(print.IsSealed);
Assert.True(print.IsImplicitlyDeclared);
var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString);
Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility);
Assert.True(toString.IsOverride);
Assert.False(toString.IsVirtual);
Assert.False(toString.IsAbstract);
Assert.False(toString.IsSealed);
Assert.True(toString.IsImplicitlyDeclared);
}
[Fact]
public void ToString_AbstractRecord()
{
var src = @"
var c2 = new C2(42, 43);
System.Console.Write(c2.ToString());
abstract record C1(int I1);
sealed record C2(int I1, int I2) : C1(I1);
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "C2 { I1 = 42, I2 = 43 }", verify: Verification.Skipped /* init-only */);
}
[Fact, WorkItem(47672, "https://github.com/dotnet/roslyn/issues/47672")]
public void ToString_RecordWithIndexer()
{
var src = @"
var c1 = new C1(42);
System.Console.Write(c1.ToString());
record C1(int I1)
{
private int field = 44;
public int this[int i] => 0;
public int PropertyWithoutGetter { set { } }
public int P2 { get => 43; }
public ref int P3 { get => ref field; }
public event System.Action a;
private int field1 = 100;
internal int field2 = 100;
protected int field3 = 100;
private protected int field4 = 100;
internal protected int field5 = 100;
private int Property1 { get; set; } = 100;
internal int Property2 { get; set; } = 100;
protected int Property3 { get; set; } = 100;
private protected int Property4 { get; set; } = 100;
internal protected int Property5 { get; set; } = 100;
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "C1 { I1 = 42, P2 = 43, P3 = 44 }", verify: Verification.Skipped /* init-only */);
comp.VerifyEmitDiagnostics(
// (12,32): warning CS0067: The event 'C1.a' is never used
// public event System.Action a;
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "a", isSuppressed: false).WithArguments("C1.a").WithLocation(12, 32),
// (14,17): warning CS0414: The field 'C1.field1' is assigned but its value is never used
// private int field1 = 100;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field1", isSuppressed: false).WithArguments("C1.field1").WithLocation(14, 17)
);
}
[Fact, WorkItem(47672, "https://github.com/dotnet/roslyn/issues/47672")]
public void ToString_PrivateGetter()
{
var src = @"
var c1 = new C1();
System.Console.Write(c1.ToString());
record C1
{
public int P1 { private get => 43; set => throw null; }
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "C1 { P1 = 43 }");
comp.VerifyEmitDiagnostics();
}
[Fact, WorkItem(47797, "https://github.com/dotnet/roslyn/issues/47797")]
public void ToString_OverriddenVirtualProperty_NoRepetition()
{
var src = @"
System.Console.WriteLine(new B() { P = 2 }.ToString());
abstract record A
{
public virtual int P { get; set; }
}
record B : A
{
public override int P { get; set; }
}
";
var comp = CreateCompilation(src, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "B { P = 2 }");
}
[Fact, WorkItem(47797, "https://github.com/dotnet/roslyn/issues/47797")]
public void ToString_OverriddenAbstractProperty_NoRepetition()
{
var src = @"
System.Console.Write(new B1() { P = 1 });
System.Console.Write("" "");
System.Console.Write(new B2(2));
abstract record A1
{
public abstract int P { get; set; }
}
record B1 : A1
{
public override int P { get; set; }
}
abstract record A2(int P);
record B2(int P) : A2(P);
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "B1 { P = 1 } B2 { P = 2 }", verify: Verification.Skipped /* init-only */);
}
[Fact]
public void ToString_ErrorBase()
{
var src = @"
record C2: Error;
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (2,8): error CS0115: 'C2.ToString()': no suitable method found to override
// record C2: Error;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.ToString()").WithLocation(2, 8),
// (2,8): error CS0115: 'C2.EqualityContract': no suitable method found to override
// record C2: Error;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.EqualityContract").WithLocation(2, 8),
// (2,8): error CS0115: 'C2.Equals(object?)': no suitable method found to override
// record C2: Error;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.Equals(object?)").WithLocation(2, 8),
// (2,8): error CS0115: 'C2.GetHashCode()': no suitable method found to override
// record C2: Error;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.GetHashCode()").WithLocation(2, 8),
// (2,8): error CS0115: 'C2.PrintMembers(StringBuilder)': no suitable method found to override
// record C2: Error;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8),
// (2,12): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?)
// record C2: Error;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(2, 12)
);
}
[Fact, WorkItem(49263, "https://github.com/dotnet/roslyn/issues/49263")]
public void ToString_SelfReferentialBase()
{
var src = @"
record R : R;
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (2,8): error CS0146: Circular base type dependency involving 'R' and 'R'
// record R : R;
Diagnostic(ErrorCode.ERR_CircularBase, "R").WithArguments("R", "R").WithLocation(2, 8),
// (2,8): error CS0115: 'R.ToString()': no suitable method found to override
// record R : R;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R").WithArguments("R.ToString()").WithLocation(2, 8),
// (2,8): error CS0115: 'R.EqualityContract': no suitable method found to override
// record R : R;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R").WithArguments("R.EqualityContract").WithLocation(2, 8),
// (2,8): error CS0115: 'R.Equals(object?)': no suitable method found to override
// record R : R;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R").WithArguments("R.Equals(object?)").WithLocation(2, 8),
// (2,8): error CS0115: 'R.GetHashCode()': no suitable method found to override
// record R : R;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R").WithArguments("R.GetHashCode()").WithLocation(2, 8),
// (2,8): error CS0115: 'R.PrintMembers(StringBuilder)': no suitable method found to override
// record R : R;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R").WithArguments("R.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8)
);
}
[Fact]
public void ToString_TopLevelRecord_Empty_AbstractSealed()
{
var src = @"
abstract sealed record C1;
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (2,24): error CS0418: 'C1': an abstract type cannot be sealed or static
// abstract sealed record C1;
Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C1").WithArguments("C1").WithLocation(2, 24)
);
var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName);
Assert.Equal(Accessibility.Private, print.DeclaredAccessibility);
Assert.False(print.IsOverride);
Assert.False(print.IsVirtual);
Assert.False(print.IsAbstract);
Assert.False(print.IsSealed);
Assert.True(print.IsImplicitlyDeclared);
var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString);
Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility);
Assert.True(toString.IsOverride);
Assert.False(toString.IsVirtual);
Assert.False(toString.IsAbstract);
Assert.False(toString.IsSealed);
Assert.True(toString.IsImplicitlyDeclared);
}
[Fact, WorkItem(47092, "https://github.com/dotnet/roslyn/issues/47092")]
public void ToString_TopLevelRecord_OneField_ValueType()
{
var src = @"
var c1 = new C1() { field = 42 };
System.Console.Write(c1.ToString());
record C1
{
public int field;
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
var v = CompileAndVerify(comp, expectedOutput: "C1 { field = 42 }");
var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName);
Assert.Equal(Accessibility.Protected, print.DeclaredAccessibility);
Assert.False(print.IsOverride);
Assert.True(print.IsVirtual);
Assert.False(print.IsAbstract);
Assert.False(print.IsSealed);
Assert.True(print.IsImplicitlyDeclared);
var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString);
Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility);
Assert.True(toString.IsOverride);
Assert.False(toString.IsVirtual);
Assert.False(toString.IsAbstract);
Assert.False(toString.IsSealed);
Assert.True(toString.IsImplicitlyDeclared);
v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @"
{
// Code size 38 (0x26)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldstr ""field = ""
IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_000b: pop
IL_000c: ldarg.1
IL_000d: ldarg.0
IL_000e: ldflda ""int C1.field""
IL_0013: constrained. ""int""
IL_0019: callvirt ""string object.ToString()""
IL_001e: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_0023: pop
IL_0024: ldc.i4.1
IL_0025: ret
}
");
}
[Fact, WorkItem(47092, "https://github.com/dotnet/roslyn/issues/47092")]
public void ToString_TopLevelRecord_OneField_ConstrainedValueType()
{
var src = @"
var c1 = new C1<int>() { field = 42 };
System.Console.Write(c1.ToString());
record C1<T> where T : struct
{
public T field;
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
var v = CompileAndVerify(comp, expectedOutput: "C1 { field = 42 }");
v.VerifyIL("C1<T>." + WellKnownMemberNames.PrintMembersMethodName, @"
{
// Code size 38 (0x26)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldstr ""field = ""
IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_000b: pop
IL_000c: ldarg.1
IL_000d: ldarg.0
IL_000e: ldflda ""T C1<T>.field""
IL_0013: constrained. ""T""
IL_0019: callvirt ""string object.ToString()""
IL_001e: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_0023: pop
IL_0024: ldc.i4.1
IL_0025: ret
}
");
}
[Fact, WorkItem(47092, "https://github.com/dotnet/roslyn/issues/47092")]
public void ToString_TopLevelRecord_OneField_ReferenceType()
{
var src = @"
var c1 = new C1() { field = ""hello"" };
System.Console.Write(c1.ToString());
record C1
{
public string field;
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
var v = CompileAndVerify(comp, expectedOutput: "C1 { field = hello }");
v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @"
{
// Code size 27 (0x1b)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldstr ""field = ""
IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_000b: pop
IL_000c: ldarg.1
IL_000d: ldarg.0
IL_000e: ldfld ""string C1.field""
IL_0013: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)""
IL_0018: pop
IL_0019: ldc.i4.1
IL_001a: ret
}
");
}
[Fact, WorkItem(47092, "https://github.com/dotnet/roslyn/issues/47092")]
public void ToString_TopLevelRecord_OneField_Unconstrained()
{
var src = @"
var c1 = new C1<string>() { field = ""hello"" };
System.Console.Write(c1.ToString());
System.Console.Write("" "");
var c2 = new C1<int>() { field = 42 };
System.Console.Write(c2.ToString());
record C1<T>
{
public T field;
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
var v = CompileAndVerify(comp, expectedOutput: "C1 { field = hello } C1 { field = 42 }", verify: Verification.Skipped /* init-only */);
v.VerifyIL("C1<T>." + WellKnownMemberNames.PrintMembersMethodName, @"
{
// Code size 32 (0x20)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldstr ""field = ""
IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_000b: pop
IL_000c: ldarg.1
IL_000d: ldarg.0
IL_000e: ldfld ""T C1<T>.field""
IL_0013: box ""T""
IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)""
IL_001d: pop
IL_001e: ldc.i4.1
IL_001f: ret
}
");
}
[Fact]
public void ToString_TopLevelRecord_OneField_ErrorType()
{
var src = @"
record C1
{
public Error field;
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (4,12): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?)
// public Error field;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(4, 12),
// (4,18): warning CS0649: Field 'C1.field' is never assigned to, and will always have its default value null
// public Error field;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("C1.field", "null").WithLocation(4, 18)
);
}
[Fact]
public void ToString_TopLevelRecord_TwoFields_ReferenceType()
{
var src = @"
var c1 = new C1() { field1 = ""hi"", field2 = null };
System.Console.Write(c1.ToString());
record C1
{
public string field1;
public string field2;
private string field3;
internal string field4;
protected string field5;
protected internal string field6;
private protected string field7;
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics(
// (10,20): warning CS0169: The field 'C1.field3' is never used
// private string field3;
Diagnostic(ErrorCode.WRN_UnreferencedField, "field3").WithArguments("C1.field3").WithLocation(10, 20),
// (11,21): warning CS0649: Field 'C1.field4' is never assigned to, and will always have its default value null
// internal string field4;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field4").WithArguments("C1.field4", "null").WithLocation(11, 21),
// (12,22): warning CS0649: Field 'C1.field5' is never assigned to, and will always have its default value null
// protected string field5;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field5").WithArguments("C1.field5", "null").WithLocation(12, 22),
// (13,31): warning CS0649: Field 'C1.field6' is never assigned to, and will always have its default value null
// protected internal string field6;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field6").WithArguments("C1.field6", "null").WithLocation(13, 31),
// (14,30): warning CS0649: Field 'C1.field7' is never assigned to, and will always have its default value null
// private protected string field7;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field7").WithArguments("C1.field7", "null").WithLocation(14, 30)
);
var v = CompileAndVerify(comp, expectedOutput: "C1 { field1 = hi, field2 = }");
v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @"
{
// Code size 52 (0x34)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldstr ""field1 = ""
IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_000b: pop
IL_000c: ldarg.1
IL_000d: ldarg.0
IL_000e: ldfld ""string C1.field1""
IL_0013: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)""
IL_0018: pop
IL_0019: ldarg.1
IL_001a: ldstr "", field2 = ""
IL_001f: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_0024: pop
IL_0025: ldarg.1
IL_0026: ldarg.0
IL_0027: ldfld ""string C1.field2""
IL_002c: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)""
IL_0031: pop
IL_0032: ldc.i4.1
IL_0033: ret
}
");
}
[Fact]
public void ToString_TopLevelRecord_OneProperty()
{
var src = @"
var c1 = new C1(Property: 42);
System.Console.Write(c1.ToString());
record C1(int Property)
{
private int Property2;
internal int Property3;
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics(
// (7,17): warning CS0169: The field 'C1.Property2' is never used
// private int Property2;
Diagnostic(ErrorCode.WRN_UnreferencedField, "Property2").WithArguments("C1.Property2").WithLocation(7, 17),
// (8,18): warning CS0649: Field 'C1.Property3' is never assigned to, and will always have its default value 0
// internal int Property3;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Property3").WithArguments("C1.Property3", "0").WithLocation(8, 18)
);
var v = CompileAndVerify(comp, expectedOutput: "C1 { Property = 42 }", verify: Verification.Skipped /* init-only */);
v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @"
{
// Code size 41 (0x29)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarg.1
IL_0001: ldstr ""Property = ""
IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_000b: pop
IL_000c: ldarg.1
IL_000d: ldarg.0
IL_000e: call ""int C1.Property.get""
IL_0013: stloc.0
IL_0014: ldloca.s V_0
IL_0016: constrained. ""int""
IL_001c: callvirt ""string object.ToString()""
IL_0021: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_0026: pop
IL_0027: ldc.i4.1
IL_0028: ret
}
");
}
[Fact]
public void ToString_TopLevelRecord_TwoFieldsAndTwoProperties()
{
var src = @"
var c1 = new C1<int, string>(42, null) { field1 = 43, field2 = ""hi"" };
System.Console.Write(c1.ToString());
record C1<T1, T2>(T1 Property1, T2 Property2)
{
public T1 field1;
public T2 field2;
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "C1 { Property1 = 42, Property2 = , field1 = 43, field2 = hi }", verify: Verification.Skipped /* init-only */);
}
[Fact]
public void ToString_DerivedRecord_TwoFieldsAndTwoProperties()
{
var src = @"
var c1 = new C1(42, 43) { A2 = 100, B2 = 101 };
System.Console.Write(c1.ToString());
record Base(int A1)
{
public int A2;
}
record C1(int A1, int B1) : Base(A1)
{
public int B2;
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
var v = CompileAndVerify(comp, expectedOutput: "C1 { A1 = 42, A2 = 100, B1 = 43, B2 = 101 }", verify: Verification.Skipped /* init-only */);
v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @"
{
// Code size 98 (0x62)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""bool Base.PrintMembers(System.Text.StringBuilder)""
IL_0007: brfalse.s IL_0015
IL_0009: ldarg.1
IL_000a: ldstr "", ""
IL_000f: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_0014: pop
IL_0015: ldarg.1
IL_0016: ldstr ""B1 = ""
IL_001b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_0020: pop
IL_0021: ldarg.1
IL_0022: ldarg.0
IL_0023: call ""int C1.B1.get""
IL_0028: stloc.0
IL_0029: ldloca.s V_0
IL_002b: constrained. ""int""
IL_0031: callvirt ""string object.ToString()""
IL_0036: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_003b: pop
IL_003c: ldarg.1
IL_003d: ldstr "", B2 = ""
IL_0042: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_0047: pop
IL_0048: ldarg.1
IL_0049: ldarg.0
IL_004a: ldflda ""int C1.B2""
IL_004f: constrained. ""int""
IL_0055: callvirt ""string object.ToString()""
IL_005a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)""
IL_005f: pop
IL_0060: ldc.i4.1
IL_0061: ret
}
");
}
[Fact]
public void ToString_DerivedRecord_AbstractSealed()
{
var src = @"
record C1;
abstract sealed record C2 : C1;
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (3,24): error CS0418: 'C2': an abstract type cannot be sealed or static
// abstract sealed record C2 : C1;
Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C2").WithArguments("C2").WithLocation(3, 24)
);
var print = comp.GetMember<MethodSymbol>("C2." + WellKnownMemberNames.PrintMembersMethodName);
Assert.Equal(Accessibility.Protected, print.DeclaredAccessibility);
Assert.True(print.IsOverride);
Assert.False(print.IsVirtual);
Assert.False(print.IsAbstract);
Assert.False(print.IsSealed);
Assert.True(print.IsImplicitlyDeclared);
var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString);
Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility);
Assert.True(toString.IsOverride);
Assert.False(toString.IsVirtual);
Assert.False(toString.IsAbstract);
Assert.False(toString.IsSealed);
Assert.True(toString.IsImplicitlyDeclared);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void ToString_DerivedRecord_BaseHasSealedToString(bool usePreview)
{
var src = @"
var c = new C2();
System.Console.Write(c.ToString());
record C1
{
public sealed override string ToString() => ""C1"";
}
record C2 : C1;
";
var comp = CreateCompilation(src, parseOptions: usePreview ? TestOptions.Regular10 : TestOptions.Regular9, options: TestOptions.DebugExe);
if (usePreview)
{
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "C1");
}
else
{
comp.VerifyEmitDiagnostics(
// (7,35): error CS8773: Feature 'sealed ToString in record' is not available in C# 9.0. Please use language version 10.0 or greater.
// public sealed override string ToString() => "C1";
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "ToString").WithArguments("sealed ToString in record", "10.0").WithLocation(7, 35)
);
}
}
[Fact]
public void ToString_DerivedRecord_BaseBaseHasSealedToString()
{
var src = @"
var c = new C3();
System.Console.Write(c.ToString());
record C1
{
public sealed override string ToString() => ""C1"";
}
record C2 : C1;
record C3 : C2;
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "C1");
}
[Fact]
public void ToString_DerivedRecord_BaseBaseHasSealedToString_And_BaseTriesToOverride()
{
var src = @"
var c = new C3();
System.Console.Write(c.ToString());
record C1
{
public sealed override string ToString() => ""C1"";
}
record C2 : C1
{
public override string ToString() => ""C2"";
}
record C3 : C2;
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics(
// (11,28): error CS0239: 'C2.ToString()': cannot override inherited member 'C1.ToString()' because it is sealed
// public override string ToString() => "C2";
Diagnostic(ErrorCode.ERR_CantOverrideSealed, "ToString").WithArguments("C2.ToString()", "C1.ToString()").WithLocation(11, 28)
);
}
[Fact]
public void ToString_DerivedRecord_BaseBaseHasSealedToString_And_BaseShadowsToStringPrivate()
{
var src = @"
var c = new C3();
System.Console.Write(c.ToString());
record C1
{
public sealed override string ToString() => ""C1"";
}
record C2 : C1
{
private new string ToString() => ""C2"";
}
record C3 : C2;
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "C1");
var actualMembers = comp.GetMember<NamedTypeSymbol>("C3").GetMembers().ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type C3.EqualityContract.get",
"System.Type C3.EqualityContract { get; }",
"System.Boolean C3." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)",
"System.Boolean C3.op_Inequality(C3? left, C3? right)",
"System.Boolean C3.op_Equality(C3? left, C3? right)",
"System.Int32 C3.GetHashCode()",
"System.Boolean C3.Equals(System.Object? obj)",
"System.Boolean C3.Equals(C2? other)",
"System.Boolean C3.Equals(C3? other)",
"C1 C3." + WellKnownMemberNames.CloneMethodName + "()",
"C3..ctor(C3 original)",
"C3..ctor()"
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void ToString_DerivedRecord_BaseBaseHasSealedToString_And_BaseShadowsToStringNonSealed()
{
var src = @"
C3 c3 = new C3();
System.Console.Write(c3.ToString());
C1 c1 = c3;
System.Console.Write(c1.ToString());
record C1
{
public sealed override string ToString() => ""C1"";
}
record C2 : C1
{
public new virtual string ToString() => ""C2"";
}
record C3 : C2;
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "C2C1");
var actualMembers = comp.GetMember<NamedTypeSymbol>("C3").GetMembers().ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type C3.EqualityContract.get",
"System.Type C3.EqualityContract { get; }",
"System.Boolean C3." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)",
"System.Boolean C3.op_Inequality(C3? left, C3? right)",
"System.Boolean C3.op_Equality(C3? left, C3? right)",
"System.Int32 C3.GetHashCode()",
"System.Boolean C3.Equals(System.Object? obj)",
"System.Boolean C3.Equals(C2? other)",
"System.Boolean C3.Equals(C3? other)",
"C1 C3." + WellKnownMemberNames.CloneMethodName + "()",
"C3..ctor(C3 original)",
"C3..ctor()"
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void ToString_DerivedRecord_BaseBaseHasSealedToString_And_BaseHasToStringWithDifferentSignature()
{
var src = @"
var c = new C3();
System.Console.Write(c.ToString());
record C1
{
public sealed override string ToString() => ""C1"";
}
record C2 : C1
{
public string ToString(int n) => throw null;
}
record C3 : C2;
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "C1");
var actualMembers = comp.GetMember<NamedTypeSymbol>("C3").GetMembers().ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type C3.EqualityContract.get",
"System.Type C3.EqualityContract { get; }",
"System.Boolean C3." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)",
"System.Boolean C3.op_Inequality(C3? left, C3? right)",
"System.Boolean C3.op_Equality(C3? left, C3? right)",
"System.Int32 C3.GetHashCode()",
"System.Boolean C3.Equals(System.Object? obj)",
"System.Boolean C3.Equals(C2? other)",
"System.Boolean C3.Equals(C3? other)",
"C1 C3." + WellKnownMemberNames.CloneMethodName + "()",
"C3..ctor(C3 original)",
"C3..ctor()"
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void ToString_DerivedRecord_BaseBaseHasSealedToString_And_BaseHasToStringWithDifferentReturnType()
{
var src = @"
C1 c = new C3();
System.Console.Write(c.ToString());
record C1
{
public sealed override string ToString() => ""C1"";
}
record C2 : C1
{
public new int ToString() => throw null;
}
record C3 : C2;
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "C1");
var actualMembers = comp.GetMember<NamedTypeSymbol>("C3").GetMembers().ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type C3.EqualityContract.get",
"System.Type C3.EqualityContract { get; }",
"System.Boolean C3." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)",
"System.Boolean C3.op_Inequality(C3? left, C3? right)",
"System.Boolean C3.op_Equality(C3? left, C3? right)",
"System.Int32 C3.GetHashCode()",
"System.Boolean C3.Equals(System.Object? obj)",
"System.Boolean C3.Equals(C2? other)",
"System.Boolean C3.Equals(C3? other)",
"C1 C3." + WellKnownMemberNames.CloneMethodName + "()",
"C3..ctor(C3 original)",
"C3..ctor()"
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void ToString_DerivedRecord_TwoFieldsAndTwoProperties_ReverseOrder()
{
var src = @"
var c1 = new C1(42, 43) { A1 = 100, B1 = 101 };
System.Console.Write(c1.ToString());
record Base(int A2)
{
public int A1;
}
record C1(int A2, int B2) : Base(A2)
{
public int B1;
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "C1 { A2 = 42, A1 = 100, B2 = 43, B1 = 101 }", verify: Verification.Skipped /* init-only */);
}
[Fact]
public void ToString_DerivedRecord_TwoFieldsAndTwoProperties_Partial()
{
var src1 = @"
var c1 = new C1() { A1 = 100, B1 = 101 };
System.Console.Write(c1.ToString());
partial record C1
{
public int A1;
}
";
var src2 = @"
partial record C1
{
public int B1;
}
";
var comp = CreateCompilation(new[] { src1, src2, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "C1 { A1 = 100, B1 = 101 }", verify: Verification.Skipped /* init-only */);
}
[Fact]
public void ToString_DerivedRecord_TwoFieldsAndTwoProperties_Partial_ReverseOrder()
{
var src1 = @"
var c1 = new C1() { A1 = 100, B1 = 101 };
System.Console.Write(c1.ToString());
partial record C1
{
public int B1;
}
";
var src2 = @"
partial record C1
{
public int A1;
}
";
var comp = CreateCompilation(new[] { src1, src2, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "C1 { B1 = 101, A1 = 100 }", verify: Verification.Skipped /* init-only */);
}
[Fact]
public void ToString_BadBase_MissingToString()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
.method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals ( object other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public newslot virtual instance bool Equals ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
}
.method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance string ToString () cil managed
{
IL_0000: ldstr ""RAN""
IL_0005: ret
}
}
.class public auto ansi beforefieldinit B
extends A
{
.method family hidebysig specialname virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname static bool op_Inequality ( class B r1, class B r2 ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname static bool op_Equality ( class B r1, class B r2 ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals ( object obj ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public final hidebysig virtual instance bool Equals ( class A other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig newslot virtual instance bool Equals ( class B other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig specialname rtspecialname instance void .ctor ( class B original ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldarg.0
IL_0001: call instance void A::.ctor()
IL_0006: ret
}
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type B::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
// no override for ToString
}
";
var source = @"
var c = new C();
System.Console.Write(c);
public record C : B
{
public override string ToString() => base.ToString();
}
";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "RAN");
}
[Fact]
public void ToString_BadBase_PrintMembersSealed()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
.method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals ( object other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public newslot virtual instance bool Equals ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method final family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0506: 'B.PrintMembers(StringBuilder)': cannot override inherited member 'A.PrintMembers(StringBuilder)' because it is not marked virtual, abstract, or override
// public record B : A {
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)", "A.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 15)
);
}
[Fact]
public void ToString_BadBase_PrintMembersInaccessible()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
.method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals ( object other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public newslot virtual instance bool Equals ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method private hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0115: 'B.PrintMembers(StringBuilder)': no suitable method found to override
// public record B : A {
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 15)
);
}
[Fact]
public void ToString_BadBase_PrintMembersReturnsInt()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
.method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals ( object other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public newslot virtual instance bool Equals ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance int32 '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0508: 'B.PrintMembers(StringBuilder)': return type must be 'int' to match overridden member 'A.PrintMembers(StringBuilder)'
// public record B : A {
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)", "A.PrintMembers(System.Text.StringBuilder)", "int").WithLocation(2, 15)
);
}
[Fact]
public void EqualityContract_BadBase_ReturnsInt()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
.method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals ( object other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public newslot virtual instance bool Equals ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig newslot virtual instance int32 get_EqualityContract () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.property instance int32 EqualityContract()
{
.get instance int32 A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS1715: 'B.EqualityContract': type must be 'int' to match overridden member 'A.EqualityContract'
// public record B : A {
Diagnostic(ErrorCode.ERR_CantChangeTypeOnOverride, "B").WithArguments("B.EqualityContract", "A.EqualityContract", "int").WithLocation(2, 15)
);
}
[Fact]
public void ToString_BadBase_PrintMembersIsAmbiguous()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
.method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals ( object other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public newslot virtual instance bool Equals ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance int32 '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics();
}
[Fact]
public void ToString_BadBase_MissingPrintMembers()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
.method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals ( object other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public newslot virtual instance bool Equals ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
}
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0115: 'B.PrintMembers(StringBuilder)': no suitable method found to override
// public record B : A {
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 15)
);
}
[Fact]
public void ToString_BadBase_DuplicatePrintMembers()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
.method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals ( object other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public newslot virtual instance bool Equals ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder modopt(int64) builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance string ToString () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics();
}
[Fact]
public void ToString_BadBase_PrintMembersNotOverriddenInBase()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
.method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals ( object other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public newslot virtual instance bool Equals ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance string ToString () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}
.class public auto ansi beforefieldinit B
extends A
{
.method family hidebysig specialname virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname static bool op_Inequality ( class B r1, class B r2 ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname static bool op_Equality ( class B r1, class B r2 ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals ( object obj ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public final hidebysig virtual instance bool Equals ( class A other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig newslot virtual instance bool Equals ( class B other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig specialname rtspecialname instance void .ctor ( class B original ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type B::get_EqualityContract()
}
// no override for PrintMembers
}
";
var source = @"
public record C : B
{
protected override bool PrintMembers(System.Text.StringBuilder builder) => throw null;
}
";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (4,29): error CS8871: 'C.PrintMembers(StringBuilder)' does not override expected method from 'B'.
// protected override bool PrintMembers(System.Text.StringBuilder builder) => throw null;
Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseMethod, "PrintMembers").WithArguments("C.PrintMembers(System.Text.StringBuilder)", "B").WithLocation(4, 29)
);
var source2 = @"
public record C : B;
";
comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS8871: 'C.PrintMembers(StringBuilder)' does not override expected method from 'B'.
// public record C : B;
Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseMethod, "C").WithArguments("C.PrintMembers(System.Text.StringBuilder)", "B").WithLocation(2, 15)
);
}
[Fact]
public void ToString_BadBase_PrintMembersWithModOpt()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
.method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals ( object other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public newslot virtual instance bool Equals ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder modopt(int64) builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance string ToString () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics();
var print = comp.GetMember<MethodSymbol>("B." + WellKnownMemberNames.PrintMembersMethodName);
Assert.Equal("System.Boolean B.PrintMembers(System.Text.StringBuilder modopt(System.Int64) builder)", print.ToTestDisplayString());
Assert.Equal("System.Boolean A.PrintMembers(System.Text.StringBuilder modopt(System.Int64) builder)", print.OverriddenMethod.ToTestDisplayString());
}
[Fact]
public void ToString_BadBase_NewToString()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
.method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals ( object other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public newslot virtual instance bool Equals ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig newslot virtual instance string ToString () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS8869: 'B.ToString()' does not override expected method from 'object'.
// public record B : A {
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "B").WithArguments("B.ToString()").WithLocation(2, 15)
);
}
[Fact]
public void ToString_NewToString_SealedBaseToString()
{
var source = @"
B b = new B();
System.Console.Write(b.ToString());
A a = b;
System.Console.Write(a.ToString());
public record A
{
public sealed override string ToString() => ""A"";
}
public record B : A
{
public new string ToString() => ""B"";
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "BA");
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void ToString_BadBase_SealedToString(bool usePreview)
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
.method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals ( object other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public newslot virtual instance bool Equals ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
}
.method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public final hidebysig virtual instance string ToString () cil managed
{
IL_0000: ldstr ""A""
IL_0001: ret
}
}
";
var source = @"
var b = new B();
System.Console.Write(b.ToString());
public record B : A {
}";
var comp = CreateCompilationWithIL(
new[] { source, IsExternalInitTypeDefinition },
ilSource: ilSource,
parseOptions: usePreview ? TestOptions.Regular10 : TestOptions.Regular9);
if (usePreview)
{
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "A");
}
else
{
comp.VerifyEmitDiagnostics(
// (5,15): error CS8912: Inheriting from a record with a sealed 'Object.ToString' is not supported in C# 9.0. Please use language version '10.0' or greater.
// public record B : A {
Diagnostic(ErrorCode.ERR_InheritingFromRecordWithSealedToString, "B").WithArguments("9.0", "10.0").WithLocation(5, 15)
);
}
}
[Fact]
public void ToString_TopLevelRecord_UserDefinedToString()
{
var src = @"
var c1 = new C1();
System.Console.Write(c1.ToString());
record C1
{
public override string ToString() => ""RAN"";
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "RAN");
var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName);
Assert.Equal("System.Boolean C1." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", print.ToTestDisplayString());
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void ToString_TopLevelRecord_UserDefinedToString_Sealed(bool usePreview)
{
var src = @"
record C1
{
public sealed override string ToString() => throw null;
}
";
var comp = CreateCompilation(src, parseOptions: usePreview ? TestOptions.Regular10 : TestOptions.Regular9);
if (usePreview)
{
comp.VerifyEmitDiagnostics();
}
else
{
comp.VerifyEmitDiagnostics(
// (4,35): error CS8773: Feature 'sealed ToString in record' is not available in C# 9.0. Please use language version 10.0 or greater.
// public sealed override string ToString() => throw null;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "ToString").WithArguments("sealed ToString in record", "10.0").WithLocation(4, 35)
);
}
}
[Fact]
public void ToString_TopLevelRecord_UserDefinedToString_Sealed_InSealedRecord()
{
var src = @"
sealed record C1
{
public sealed override string ToString() => throw null;
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics();
}
[Fact]
public void ToString_UserDefinedPrintMembers_WithNullableStringBuilder()
{
var src = @"
#nullable enable
record C1
{
protected virtual bool PrintMembers(System.Text.StringBuilder? builder) => throw null!;
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics();
}
[Fact]
public void ToString_UserDefinedPrintMembers_ErrorReturnType()
{
var src = @"
record C1
{
protected virtual Error PrintMembers(System.Text.StringBuilder builder) => throw null;
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (4,23): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?)
// protected virtual Error PrintMembers(System.Text.StringBuilder builder) => throw null;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(4, 23)
);
}
[Fact]
public void ToString_UserDefinedPrintMembers_WrongReturnType()
{
var src = @"
record C1
{
protected virtual int PrintMembers(System.Text.StringBuilder builder) => throw null;
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (4,27): error CS8874: Record member 'C1.PrintMembers(StringBuilder)' must return 'bool'.
// protected virtual int PrintMembers(System.Text.StringBuilder builder) => throw null;
Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)", "bool").WithLocation(4, 27)
);
}
[Fact]
public void ToString_UserDefinedPrintMembers_Sealed()
{
var src = @"
record C1(int I1);
record C2(int I1, int I2) : C1(I1)
{
protected sealed override bool PrintMembers(System.Text.StringBuilder builder) => throw null;
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (5,36): error CS8872: 'C2.PrintMembers(StringBuilder)' must allow overriding because the containing record is not sealed.
// protected sealed override bool PrintMembers(System.Text.StringBuilder builder) => throw null;
Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "PrintMembers").WithArguments("C2.PrintMembers(System.Text.StringBuilder)").WithLocation(5, 36)
);
}
[Fact]
public void ToString_UserDefinedPrintMembers_NonVirtual()
{
var src = @"
record C1
{
protected bool PrintMembers(System.Text.StringBuilder builder) => throw null;
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (4,20): error CS8872: 'C1.PrintMembers(StringBuilder)' must allow overriding because the containing record is not sealed.
// protected bool PrintMembers(System.Text.StringBuilder builder) => throw null;
Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 20)
);
}
[Fact]
public void ToString_UserDefinedPrintMembers_SealedInSealedRecord()
{
var src = @"
record C1(int I1);
sealed record C2(int I1, int I2) : C1(I1)
{
protected sealed override bool PrintMembers(System.Text.StringBuilder builder) => throw null;
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics();
}
[Fact]
public void ToString_UserDefinedPrintMembers_Static()
{
var src = @"
sealed record C
{
private static bool PrintMembers(System.Text.StringBuilder builder) => throw null;
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (4,25): error CS8877: Record member 'C.PrintMembers(StringBuilder)' may not be static.
// private static bool PrintMembers(System.Text.StringBuilder builder) => throw null;
Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "PrintMembers").WithArguments("C.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 25)
);
}
[Fact]
public void ToString_UserDefinedPrintMembers()
{
var src = @"
var c1 = new C1();
System.Console.Write(c1.ToString());
record C1
{
protected virtual bool PrintMembers(System.Text.StringBuilder builder)
{
builder.Append(""RAN"");
return true;
}
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "C1 { RAN }");
}
[Fact]
public void ToString_UserDefinedPrintMembers_WrongAccessibility()
{
var src = @"
record C1
{
public virtual bool PrintMembers(System.Text.StringBuilder builder) => throw null;
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (4,25): error CS8875: Record member 'C1.PrintMembers(StringBuilder)' must be protected.
// public virtual bool PrintMembers(System.Text.StringBuilder builder) => throw null;
Diagnostic(ErrorCode.ERR_NonProtectedAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 25)
);
}
[Fact]
public void ToString_UserDefinedPrintMembers_WrongAccessibility_SealedRecord()
{
var src = @"
sealed record C1
{
protected bool PrintMembers(System.Text.StringBuilder builder) => throw null;
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (4,20): warning CS0628: 'C1.PrintMembers(StringBuilder)': new protected member declared in sealed type
// protected bool PrintMembers(System.Text.StringBuilder builder) => throw null;
Diagnostic(ErrorCode.WRN_ProtectedInSealed, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 20),
// (4,20): error CS8879: Record member 'C1.PrintMembers(StringBuilder)' must be private.
// protected bool PrintMembers(System.Text.StringBuilder builder) => throw null;
Diagnostic(ErrorCode.ERR_NonPrivateAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 20)
);
}
[Fact]
public void ToString_UserDefinedPrintMembers_DerivedRecord_WrongAccessibility()
{
var src = @"
record B;
record C1 : B
{
public bool PrintMembers(System.Text.StringBuilder builder) => throw null;
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (5,17): error CS8875: Record member 'C1.PrintMembers(StringBuilder)' must be protected.
// public bool PrintMembers(System.Text.StringBuilder builder) => throw null;
Diagnostic(ErrorCode.ERR_NonProtectedAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(5, 17),
// (5,17): error CS8860: 'C1.PrintMembers(StringBuilder)' does not override expected method from 'B'.
// public bool PrintMembers(System.Text.StringBuilder builder) => throw null;
Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseMethod, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)", "B").WithLocation(5, 17),
// (5,17): error CS8872: 'C1.PrintMembers(StringBuilder)' must allow overriding because the containing record is not sealed.
// public bool PrintMembers(System.Text.StringBuilder builder) => throw null;
Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(5, 17),
// (5,17): warning CS0114: 'C1.PrintMembers(StringBuilder)' hides inherited member 'B.PrintMembers(StringBuilder)'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.
// public bool PrintMembers(System.Text.StringBuilder builder) => throw null;
Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)", "B.PrintMembers(System.Text.StringBuilder)").WithLocation(5, 17)
);
}
[Fact]
public void ToString_UserDefinedPrintMembers_New()
{
var src = @"
record B;
record C1 : B
{
protected new virtual bool PrintMembers(System.Text.StringBuilder builder) => throw null;
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (5,32): error CS8860: 'C1.PrintMembers(StringBuilder)' does not override expected method from 'B'.
// protected new virtual bool PrintMembers(System.Text.StringBuilder builder) => throw null;
Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseMethod, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)", "B").WithLocation(5, 32)
);
}
[Fact]
public void ToString_TopLevelRecord_EscapedNamed()
{
var src = @"
var c1 = new @base();
System.Console.Write(c1.ToString());
record @base;
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "base { }");
}
[Fact]
public void ToString_DerivedDerivedRecord()
{
var src = @"
var r1 = new R1(1);
System.Console.Write(r1.ToString());
System.Console.Write("" "");
var r2 = new R2(10, 11);
System.Console.Write(r2.ToString());
System.Console.Write("" "");
var r3 = new R3(20, 21, 22);
System.Console.Write(r3.ToString());
record R1(int I1);
record R2(int I1, int I2) : R1(I1);
record R3(int I1, int I2, int I3) : R2(I1, I2);
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "R1 { I1 = 1 } R2 { I1 = 10, I2 = 11 } R3 { I1 = 20, I2 = 21, I3 = 22 }", verify: Verification.Skipped /* init-only */);
}
[Fact]
public void WithExpr24()
{
string source = @"
record C(int X)
{
public static void Main()
{
var c1 = new C(1);
c1 = c1 with { };
var c2 = c1 with { X = 11 };
System.Console.WriteLine(c1.X);
System.Console.WriteLine(c2.X);
}
protected C(ref C other) : this(-1)
{
}
protected C(C other)
{
X = other.X;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"1
11").VerifyDiagnostics();
verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: newobj ""C..ctor(C)""
IL_0006: ret
}
");
var clone = verifier.Compilation.GetMember("C." + WellKnownMemberNames.CloneMethodName);
Assert.Equal("<Clone>$", clone.Name);
}
[Fact]
public void WithExpr25()
{
string source = @"
record C(int X)
{
public static void Main()
{
var c1 = new C(1);
c1 = c1 with { };
var c2 = c1 with { X = 11 };
System.Console.WriteLine(c1.X);
System.Console.WriteLine(c2.X);
}
protected C(in C other) : this(-1)
{
}
protected C(C other)
{
X = other.X;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"1
11").VerifyDiagnostics();
verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: newobj ""C..ctor(C)""
IL_0006: ret
}
");
}
[Fact]
public void WithExpr26()
{
string source = @"
record C(int X)
{
public static void Main()
{
var c1 = new C(1);
c1 = c1 with { };
var c2 = c1 with { X = 11 };
System.Console.WriteLine(c1.X);
System.Console.WriteLine(c2.X);
}
protected C(out C other) : this(-1)
{
other = null;
}
protected C(C other)
{
X = other.X;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"1
11").VerifyDiagnostics();
verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: newobj ""C..ctor(C)""
IL_0006: ret
}
");
}
[Fact]
public void WithExpr27()
{
string source = @"
record C(int X)
{
public static void Main()
{
var c1 = new C(1);
c1 = c1 with { };
var c2 = c1 with { X = 11 };
System.Console.WriteLine(c1.X);
System.Console.WriteLine(c2.X);
}
protected C(ref C other) : this(-1)
{
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"1
11").VerifyDiagnostics();
verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: newobj ""C..ctor(C)""
IL_0006: ret
}
");
}
[Fact]
public void WithExpr28()
{
string source = @"
record C(int X)
{
public static void Main()
{
var c1 = new C(1);
c1 = c1 with { };
var c2 = c1 with { X = 11 };
System.Console.WriteLine(c1.X);
System.Console.WriteLine(c2.X);
}
protected C(in C other) : this(-1)
{
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"1
11").VerifyDiagnostics();
verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: newobj ""C..ctor(C)""
IL_0006: ret
}
");
}
[Fact]
public void WithExpr29()
{
string source = @"
record C(int X)
{
public static void Main()
{
var c1 = new C(1);
c1 = c1 with { };
var c2 = c1 with { X = 11 };
System.Console.WriteLine(c1.X);
System.Console.WriteLine(c2.X);
}
protected C(out C other) : this(-1)
{
other = null;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"1
11").VerifyDiagnostics();
verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: newobj ""C..ctor(C)""
IL_0006: ret
}
");
}
[Fact]
public void AccessibilityOfBaseCtor_01()
{
var src = @"
using System;
record Base
{
protected Base(int X, int Y)
{
Console.WriteLine(X);
Console.WriteLine(Y);
}
public Base() {}
public static void Main()
{
var c = new C(1, 2);
}
}
record C(int X, int Y) : Base(X, Y);
";
CompileAndVerify(src, expectedOutput: @"
1
2
").VerifyDiagnostics();
}
[Fact]
public void AccessibilityOfBaseCtor_02()
{
var src = @"
using System;
record Base
{
protected Base(int X, int Y)
{
Console.WriteLine(X);
Console.WriteLine(Y);
}
public Base() {}
public static void Main()
{
var c = new C(1, 2);
}
}
record C(int X, int Y) : Base(X, Y) {}
";
CompileAndVerify(src, expectedOutput: @"
1
2
").VerifyDiagnostics();
}
[Fact]
[WorkItem(44898, "https://github.com/dotnet/roslyn/issues/44898")]
public void AccessibilityOfBaseCtor_03()
{
var src = @"
abstract record A
{
protected A() {}
protected A(A x) {}
};
record B(object P) : A;
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics();
}
[Fact]
[WorkItem(44898, "https://github.com/dotnet/roslyn/issues/44898")]
public void AccessibilityOfBaseCtor_04()
{
var src = @"
abstract record A
{
protected A() {}
protected A(A x) {}
};
record B(object P) : A {}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact]
[WorkItem(44898, "https://github.com/dotnet/roslyn/issues/44898")]
public void AccessibilityOfBaseCtor_05()
{
var src = @"
abstract record A
{
protected A() {}
protected A(A x) {}
};
record B : A;
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics();
}
[Fact]
[WorkItem(44898, "https://github.com/dotnet/roslyn/issues/44898")]
public void AccessibilityOfBaseCtor_06()
{
var src = @"
abstract record A
{
protected A() {}
protected A(A x) {}
};
record B : A {}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact]
public void WithExprNestedErrors()
{
var src = @"
class C
{
public int X { get; init; }
public static void Main()
{
var c = new C();
c = c with { X = """"-3 };
}
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (8,13): error CS8808: The receiver type 'C' does not have an accessible parameterless instance method named "Clone".
// c = c with { X = ""-3 };
Diagnostic(ErrorCode.ERR_CannotClone, "c").WithArguments("C").WithLocation(8, 13),
// (8,26): error CS0019: Operator '-' cannot be applied to operands of type 'string' and 'int'
// c = c with { X = ""-3 };
Diagnostic(ErrorCode.ERR_BadBinaryOps, @"""""-3").WithArguments("-", "string", "int").WithLocation(8, 26)
);
}
[Fact]
public void WithExprNoExpressionToPropertyTypeConversion()
{
var src = @"
record C(int X)
{
public static void Main()
{
var c = new C(0);
c = c with { X = """" };
}
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (8,26): error CS0029: Cannot implicitly convert type 'string' to 'int'
// c = c with { X = "" };
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""""").WithArguments("string", "int").WithLocation(8, 26)
);
}
[Fact]
public void WithExprPropertyInaccessibleSet()
{
var src = @"
record C
{
public int X { get; private set; }
}
class D
{
public static void Main()
{
var c = new C();
c = c with { X = 0 };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (11,22): error CS0272: The property or indexer 'C.X' cannot be used in this context because the set accessor is inaccessible
// c = c with { X = 0 };
Diagnostic(ErrorCode.ERR_InaccessibleSetter, "X").WithArguments("C.X").WithLocation(11, 22)
);
}
[Fact]
public void WithExprSideEffects1()
{
var src = @"
using System;
record C(int X, int Y, int Z)
{
public static void Main()
{
var c = new C(0, 1, 2);
c = c with { Y = W(""Y""), X = W(""X"") };
}
public static int W(string s)
{
Console.WriteLine(s);
return 0;
}
}
";
var verifier = CompileAndVerify(src, expectedOutput: @"
Y
X").VerifyDiagnostics();
verifier.VerifyIL("C.Main", @"
{
// Code size 47 (0x2f)
.maxstack 3
IL_0000: ldc.i4.0
IL_0001: ldc.i4.1
IL_0002: ldc.i4.2
IL_0003: newobj ""C..ctor(int, int, int)""
IL_0008: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()""
IL_000d: dup
IL_000e: ldstr ""Y""
IL_0013: call ""int C.W(string)""
IL_0018: callvirt ""void C.Y.init""
IL_001d: dup
IL_001e: ldstr ""X""
IL_0023: call ""int C.W(string)""
IL_0028: callvirt ""void C.X.init""
IL_002d: pop
IL_002e: ret
}");
var comp = (CSharpCompilation)verifier.Compilation;
var tree = comp.SyntaxTrees.First();
var root = tree.GetRoot();
var model = comp.GetSemanticModel(tree);
var withExpr1 = root.DescendantNodes().OfType<WithExpressionSyntax>().First();
comp.VerifyOperationTree(withExpr1, @"
IWithOperation (OperationKind.With, Type: C) (Syntax: 'c with { Y ... = W(""X"") }')
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
CloneMethod: C C." + WellKnownMemberNames.CloneMethodName + @"()
Initializer:
IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C) (Syntax: '{ Y = W(""Y"" ... = W(""X"") }')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'Y = W(""Y"")')
Left:
IPropertyReferenceOperation: System.Int32 C.Y { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Y')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'Y')
Right:
IInvocationOperation (System.Int32 C.W(System.String s)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'W(""Y"")')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: s) (OperationKind.Argument, Type: null) (Syntax: '""Y""')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""Y"") (Syntax: '""Y""')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = W(""X"")')
Left:
IPropertyReferenceOperation: System.Int32 C.X { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X')
Right:
IInvocationOperation (System.Int32 C.W(System.String s)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'W(""X"")')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: s) (OperationKind.Argument, Type: null) (Syntax: '""X""')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""X"") (Syntax: '""X""')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
var main = root.DescendantNodes().OfType<MethodDeclarationSyntax>().First();
Assert.Equal("Main", main.Identifier.ToString());
VerifyFlowGraph(comp, main, expectedFlowGraph: @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [C c]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'c = new C(0, 1, 2)')
Left:
ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C(0, 1, 2)')
Right:
IObjectCreationOperation (Constructor: C..ctor(System.Int32 X, System.Int32 Y, System.Int32 Z)) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C(0, 1, 2)')
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: '0')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Z) (OperationKind.Argument, Type: null) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [0] [1]
Block[B2] - Block
Predecessors: [B1]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c')
Value:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c with { Y ... = W(""X"") }')
Value:
IInvocationOperation (virtual C C." + WellKnownMemberNames.CloneMethodName + @"()) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'c with { Y ... = W(""X"") }')
Instance Receiver:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
Arguments(0)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'Y = W(""Y"")')
Left:
IPropertyReferenceOperation: System.Int32 C.Y { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Y')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c with { Y ... = W(""X"") }')
Right:
IInvocationOperation (System.Int32 C.W(System.String s)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'W(""Y"")')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: s) (OperationKind.Argument, Type: null) (Syntax: '""Y""')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""Y"") (Syntax: '""Y""')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = W(""X"")')
Left:
IPropertyReferenceOperation: System.Int32 C.X { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c with { Y ... = W(""X"") }')
Right:
IInvocationOperation (System.Int32 C.W(System.String s)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'W(""X"")')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: s) (OperationKind.Argument, Type: null) (Syntax: '""X""')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""X"") (Syntax: '""X""')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = c with ... = W(""X"") };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: 'c = c with ... = W(""X"") }')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c with { Y ... = W(""X"") }')
Next (Regular) Block[B3]
Leaving: {R2} {R1}
}
}
Block[B3] - Exit
Predecessors: [B2]
Statements (0)
");
}
[Fact]
public void WithExprConversions1()
{
var src = @"
using System;
record C(long X)
{
public static void Main()
{
var c = new C(0);
Console.WriteLine((c with { X = 11 }).X);
}
}";
var verifier = CompileAndVerify(src, expectedOutput: "11").VerifyDiagnostics();
verifier.VerifyIL("C.Main", @"
{
// Code size 32 (0x20)
.maxstack 3
IL_0000: ldc.i4.0
IL_0001: conv.i8
IL_0002: newobj ""C..ctor(long)""
IL_0007: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()""
IL_000c: dup
IL_000d: ldc.i4.s 11
IL_000f: conv.i8
IL_0010: callvirt ""void C.X.init""
IL_0015: callvirt ""long C.X.get""
IL_001a: call ""void System.Console.WriteLine(long)""
IL_001f: ret
}");
}
[Fact]
public void WithExprConversions2()
{
var src = @"
using System;
struct S
{
private int _i;
public S(int i)
{
_i = i;
}
public static implicit operator long(S s)
{
Console.WriteLine(""conversion"");
return s._i;
}
}
record C(long X)
{
public static void Main()
{
var c = new C(0);
var s = new S(11);
Console.WriteLine((c with { X = s }).X);
}
}";
var verifier = CompileAndVerify(src, expectedOutput: @"
conversion
11").VerifyDiagnostics();
verifier.VerifyIL("C.Main", @"
{
// Code size 44 (0x2c)
.maxstack 3
.locals init (S V_0) //s
IL_0000: ldc.i4.0
IL_0001: conv.i8
IL_0002: newobj ""C..ctor(long)""
IL_0007: ldloca.s V_0
IL_0009: ldc.i4.s 11
IL_000b: call ""S..ctor(int)""
IL_0010: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()""
IL_0015: dup
IL_0016: ldloc.0
IL_0017: call ""long S.op_Implicit(S)""
IL_001c: callvirt ""void C.X.init""
IL_0021: callvirt ""long C.X.get""
IL_0026: call ""void System.Console.WriteLine(long)""
IL_002b: ret
}");
}
[Fact]
public void WithExprConversions3()
{
var src = @"
using System;
struct S
{
private int _i;
public S(int i)
{
_i = i;
}
public static explicit operator int(S s)
{
Console.WriteLine(""conversion"");
return s._i;
}
}
record C(long X)
{
public static void Main()
{
var c = new C(0);
var s = new S(11);
Console.WriteLine((c with { X = (int)s }).X);
}
}";
var verifier = CompileAndVerify(src, expectedOutput: @"
conversion
11").VerifyDiagnostics();
}
[Fact]
public void WithExprConversions4()
{
var src = @"
using System;
struct S
{
private int _i;
public S(int i)
{
_i = i;
}
public static explicit operator long(S s) => s._i;
}
record C(long X)
{
public static void Main()
{
var c = new C(0);
var s = new S(11);
Console.WriteLine((c with { X = s }).X);
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (19,41): error CS0266: Cannot implicitly convert type 'S' to 'long'. An explicit conversion exists (are you missing a cast?)
// Console.WriteLine((c with { X = s }).X);
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "s").WithArguments("S", "long").WithLocation(19, 41)
);
}
[Fact]
public void WithExprConversions5()
{
var src = @"
using System;
record C(object X)
{
public static void Main()
{
var c = new C(0);
Console.WriteLine((c with { X = ""abc"" }).X);
}
}";
CompileAndVerify(src, expectedOutput: "abc").VerifyDiagnostics();
}
[Fact]
public void WithExprConversions6()
{
var src = @"
using System;
struct S
{
private int _i;
public S(int i)
{
_i = i;
}
public static implicit operator int(S s)
{
Console.WriteLine(""conversion"");
return s._i;
}
}
record C
{
private readonly long _x;
public long X { get => _x; init { Console.WriteLine(""set""); _x = value; } }
public static void Main()
{
var c = new C();
var s = new S(11);
Console.WriteLine((c with { X = s }).X);
}
}";
var verifier = CompileAndVerify(src, expectedOutput: @"
conversion
set
11").VerifyDiagnostics();
verifier.VerifyIL("C.Main", @"
{
// Code size 43 (0x2b)
.maxstack 3
.locals init (S V_0) //s
IL_0000: newobj ""C..ctor()""
IL_0005: ldloca.s V_0
IL_0007: ldc.i4.s 11
IL_0009: call ""S..ctor(int)""
IL_000e: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()""
IL_0013: dup
IL_0014: ldloc.0
IL_0015: call ""int S.op_Implicit(S)""
IL_001a: conv.i8
IL_001b: callvirt ""void C.X.init""
IL_0020: callvirt ""long C.X.get""
IL_0025: call ""void System.Console.WriteLine(long)""
IL_002a: ret
}");
}
[Fact]
public void WithExprStaticProperty()
{
var src = @"
record C
{
public static int X { get; set; }
public static void Main()
{
var c = new C();
c = c with { };
c = c with { X = 11 };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (9,22): error CS0176: Member 'C.X' cannot be accessed with an instance reference; qualify it with a type name instead
// c = c with { X = 11 };
Diagnostic(ErrorCode.ERR_ObjectProhibited, "X").WithArguments("C.X").WithLocation(9, 22)
);
}
[Fact]
public void WithExprMethodAsArgument()
{
var src = @"
record C
{
public int X() => 0;
public static void Main()
{
var c = new C();
c = c with { };
c = c with { X = 11 };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (9,22): error CS1913: Member 'X' cannot be initialized. It is not a field or property.
// c = c with { X = 11 };
Diagnostic(ErrorCode.ERR_MemberCannotBeInitialized, "X").WithArguments("X").WithLocation(9, 22)
);
}
[Fact]
public void WithExprStaticWithMethod()
{
var src = @"
class C
{
public int X = 0;
public static C Clone() => null;
public static void Main()
{
var c = new C();
c = c with { };
c = c with { X = 11 };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (9,13): error CS8808: The receiver type 'C' does not have an accessible parameterless instance method named "Clone".
// c = c with { };
Diagnostic(ErrorCode.ERR_CannotClone, "c").WithArguments("C").WithLocation(9, 13),
// (10,13): error CS8808: The receiver type 'C' does not have an accessible parameterless instance method named "Clone".
// c = c with { X = 11 };
Diagnostic(ErrorCode.ERR_CannotClone, "c").WithArguments("C").WithLocation(10, 13)
);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")]
[WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")]
public void WithExprStaticWithMethod2()
{
var src = @"
class B
{
public B Clone() => null;
}
class C : B
{
public int X = 0;
public static new C Clone() => null; // static
public static void Main()
{
var c = new C();
c = c with { };
c = c with { X = 11 };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (13,13): error CS0266: Cannot implicitly convert type 'B' to 'C'. An explicit conversion exists (are you missing a cast?)
// c = c with { };
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "c with { }").WithArguments("B", "C").WithLocation(13, 13),
// (14,22): error CS0117: 'B' does not contain a definition for 'X'
// c = c with { X = 11 };
Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("B", "X").WithLocation(14, 22)
);
}
[Fact]
public void WithExprBadMemberBadType()
{
var src = @"
record C
{
public int X { get; init; }
public static void Main()
{
var c = new C();
c = c with { X = ""a"" };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (8,26): error CS0029: Cannot implicitly convert type 'string' to 'int'
// c = c with { X = "a" };
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""a""").WithArguments("string", "int").WithLocation(8, 26)
);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")]
[WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")]
public void WithExprCloneReturnDifferent()
{
var src = @"
class B
{
public int X { get; init; }
}
class C : B
{
public B Clone() => new B();
public static void Main()
{
var c = new C();
var b = c with { X = 0 };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact]
public void WithSemanticModel1()
{
var src = @"
record C(int X, string Y)
{
public static void Main()
{
var c = new C(0, ""a"");
c = c with { X = 2 };
}
}";
var comp = CreateCompilation(src);
var tree = comp.SyntaxTrees[0];
var root = tree.GetRoot();
var model = comp.GetSemanticModel(tree);
var withExpr = root.DescendantNodes().OfType<WithExpressionSyntax>().Single();
var typeInfo = model.GetTypeInfo(withExpr);
var c = comp.GlobalNamespace.GetTypeMember("C");
Assert.True(c.IsRecord);
Assert.True(c.ISymbol.Equals(typeInfo.Type));
var x = c.GetMembers("X").Single();
var xId = withExpr.DescendantNodes().Single(id => id.ToString() == "X");
var symbolInfo = model.GetSymbolInfo(xId);
Assert.True(x.ISymbol.Equals(symbolInfo.Symbol));
comp.VerifyOperationTree(withExpr, @"
IWithOperation (OperationKind.With, Type: C) (Syntax: 'c with { X = 2 }')
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
CloneMethod: C C." + WellKnownMemberNames.CloneMethodName + @"()
Initializer:
IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C) (Syntax: '{ X = 2 }')
Initializers(1):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 2')
Left:
IPropertyReferenceOperation: System.Int32 C.X { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')");
var main = root.DescendantNodes().OfType<MethodDeclarationSyntax>().Single();
Assert.Equal("Main", main.Identifier.ToString());
VerifyFlowGraph(comp, main, expectedFlowGraph: @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [C c]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'c = new C(0, ""a"")')
Left:
ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C(0, ""a"")')
Right:
IObjectCreationOperation (Constructor: C..ctor(System.Int32 X, System.String Y)) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C(0, ""a"")')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: '0')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: '""a""')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""a"") (Syntax: '""a""')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [0] [1]
Block[B2] - Block
Predecessors: [B1]
Statements (4)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c')
Value:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c with { X = 2 }')
Value:
IInvocationOperation (virtual C C." + WellKnownMemberNames.CloneMethodName + @"()) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'c with { X = 2 }')
Instance Receiver:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
Arguments(0)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 2')
Left:
IPropertyReferenceOperation: System.Int32 C.X { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c with { X = 2 }')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = c with { X = 2 };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: 'c = c with { X = 2 }')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c with { X = 2 }')
Next (Regular) Block[B3]
Leaving: {R2} {R1}
}
}
Block[B3] - Exit
Predecessors: [B2]
Statements (0)
");
}
[Fact]
public void NoCloneMethod_01()
{
var src = @"
class C
{
int X { get; set; }
public static void Main()
{
var c = new C();
c = c with { X = 2 };
}
}";
var comp = CreateCompilation(src);
var tree = comp.SyntaxTrees[0];
var root = tree.GetRoot();
var withExpr = root.DescendantNodes().OfType<WithExpressionSyntax>().Single();
comp.VerifyOperationTree(withExpr, @"
IWithOperation (OperationKind.With, Type: C, IsInvalid) (Syntax: 'c with { X = 2 }')
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c')
CloneMethod: null
Initializer:
IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C) (Syntax: '{ X = 2 }')
Initializers(1):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 2')
Left:
IPropertyReferenceOperation: System.Int32 C.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')");
var main = root.DescendantNodes().OfType<MethodDeclarationSyntax>().Single();
Assert.Equal("Main", main.Identifier.ToString());
VerifyFlowGraph(comp, main, expectedFlowGraph: @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [C c]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'c = new C()')
Left:
ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C()')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [0] [1]
Block[B2] - Block
Predecessors: [B1]
Statements (4)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c')
Value:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c')
Value:
IInvalidOperation (OperationKind.Invalid, Type: C, IsInvalid, IsImplicit) (Syntax: 'c')
Children(1):
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 2')
Left:
IPropertyReferenceOperation: System.Int32 C.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'c')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'c = c with { X = 2 };')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsInvalid) (Syntax: 'c = c with { X = 2 }')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'c')
Next (Regular) Block[B3]
Leaving: {R2} {R1}
}
}
Block[B3] - Exit
Predecessors: [B2]
Statements (0)
");
}
[Fact]
public void NoCloneMethod_02()
{
var source =
@"#nullable enable
class R
{
public object? P { get; set; }
}
class Program
{
static void Main()
{
R r = new R();
_ = r with { P = 2 };
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (11,13): error CS8858: The receiver type 'R' is not a valid record type.
// _ = r with { P = 2 };
Diagnostic(ErrorCode.ERR_CannotClone, "r").WithArguments("R").WithLocation(11, 13));
}
[Fact]
public void WithBadExprArg()
{
var src = @"
record C(int X, int Y)
{
public static void Main()
{
var c = new C(0, 0);
c = c with { 5 };
c = c with { { X = 2 } };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (8,22): error CS0747: Invalid initializer member declarator
// c = c with { 5 };
Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "5").WithLocation(8, 22),
// (9,22): error CS1513: } expected
// c = c with { { X = 2 } };
Diagnostic(ErrorCode.ERR_RbraceExpected, "{").WithLocation(9, 22),
// (9,22): error CS1002: ; expected
// c = c with { { X = 2 } };
Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(9, 22),
// (9,24): error CS0120: An object reference is required for the non-static field, method, or property 'C.X'
// c = c with { { X = 2 } };
Diagnostic(ErrorCode.ERR_ObjectRequired, "X").WithArguments("C.X").WithLocation(9, 24),
// (9,30): error CS1002: ; expected
// c = c with { { X = 2 } };
Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(9, 30),
// (9,33): error CS1597: Semicolon after method or accessor block is not valid
// c = c with { { X = 2 } };
Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(9, 33),
// (11,1): error CS1022: Type or namespace definition, or end-of-file expected
// }
Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(11, 1)
);
var tree = comp.SyntaxTrees[0];
var root = tree.GetRoot();
var model = comp.GetSemanticModel(tree);
VerifyClone(model);
var withExpr1 = root.DescendantNodes().OfType<WithExpressionSyntax>().First();
comp.VerifyOperationTree(withExpr1, @"
IWithOperation (OperationKind.With, Type: C, IsInvalid) (Syntax: 'c with { 5 }')
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
CloneMethod: C C." + WellKnownMemberNames.CloneMethodName + @"()
Initializer:
IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C, IsInvalid) (Syntax: '{ 5 }')
Initializers(1):
IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '5')
Children(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5, IsInvalid) (Syntax: '5')");
var withExpr2 = root.DescendantNodes().OfType<WithExpressionSyntax>().Skip(1).Single();
comp.VerifyOperationTree(withExpr2, @"
IWithOperation (OperationKind.With, Type: C, IsInvalid) (Syntax: 'c with { ')
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
CloneMethod: C C." + WellKnownMemberNames.CloneMethodName + @"()
Initializer:
IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C, IsInvalid) (Syntax: '{ ')
Initializers(0)");
}
[Fact]
public void WithExpr_DefiniteAssignment_01()
{
var src = @"
record B(int X)
{
static void M(B b)
{
int y;
_ = b with { X = y = 42 };
y.ToString();
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact]
public void WithExpr_DefiniteAssignment_02()
{
var src = @"
record B(int X, string Y)
{
static void M(B b)
{
int z;
_ = b with { X = z = 42, Y = z.ToString() };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact]
public void WithExpr_DefiniteAssignment_03()
{
var src = @"
record B(int X, string Y)
{
static void M(B b)
{
int z;
_ = b with { Y = z.ToString(), X = z = 42 };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (7,26): error CS0165: Use of unassigned local variable 'z'
// _ = b with { Y = z.ToString(), X = z = 42 };
Diagnostic(ErrorCode.ERR_UseDefViolation, "z").WithArguments("z").WithLocation(7, 26));
}
[Fact]
public void WithExpr_DefiniteAssignment_04()
{
var src = @"
record B(int X)
{
static void M()
{
B b;
_ = (b = new B(42)) with { X = b.X };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact]
public void WithExpr_DefiniteAssignment_05()
{
var src = @"
record B(int X)
{
static void M()
{
B b;
_ = new B(b.X) with { X = (b = new B(42)).X };
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (7,19): error CS0165: Use of unassigned local variable 'b'
// _ = new B(b.X) with { X = new B(42).X };
Diagnostic(ErrorCode.ERR_UseDefViolation, "b").WithArguments("b").WithLocation(7, 19));
}
[Fact]
public void WithExpr_DefiniteAssignment_06()
{
var src = @"
record B(int X)
{
static void M(B b)
{
int y;
_ = b with { X = M(out y) };
y.ToString();
}
static int M(out int y) { y = 42; return 43; }
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact]
public void WithExpr_DefiniteAssignment_07()
{
var src = @"
record B(int X)
{
static void M(B b)
{
_ = b with { X = M(out int y) };
y.ToString();
}
static int M(out int y) { y = 42; return 43; }
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact]
public void WithExpr_NullableAnalysis_01()
{
var src = @"
#nullable enable
record B(int X)
{
static void M(B b)
{
string? s = null;
_ = b with { X = M(out s) };
s.ToString();
}
static int M(out string s) { s = ""a""; return 42; }
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
}
[Fact]
public void WithExpr_NullableAnalysis_02()
{
var src = @"
#nullable enable
record B(string X)
{
static void M(B b, string? s)
{
b.X.ToString();
_ = b with { X = s }; // 1
b.X.ToString(); // 2
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (8,26): warning CS8601: Possible null reference assignment.
// _ = b with { X = s }; // 1
Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "s").WithLocation(8, 26));
}
[Fact]
public void WithExpr_NullableAnalysis_03()
{
var src = @"
#nullable enable
record B(string? X)
{
static void M1(B b, string s, bool flag)
{
if (flag) { b.X.ToString(); } // 1
_ = b with { X = s };
if (flag) { b.X.ToString(); } // 2
}
static void M2(B b, string s, bool flag)
{
if (flag) { b.X.ToString(); } // 3
b = b with { X = s };
if (flag) { b.X.ToString(); }
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (7,21): warning CS8602: Dereference of a possibly null reference.
// if (flag) { b.X.ToString(); } // 1
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(7, 21),
// (9,21): warning CS8602: Dereference of a possibly null reference.
// if (flag) { b.X.ToString(); } // 2
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(9, 21),
// (14,21): warning CS8602: Dereference of a possibly null reference.
// if (flag) { b.X.ToString(); } // 3
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(14, 21));
}
[Fact]
public void WithExpr_NullableAnalysis_04()
{
var src = @"
#nullable enable
record B(int X)
{
static void M1(B? b)
{
var b1 = b with { X = 42 }; // 1
_ = b.ToString();
_ = b1.ToString();
}
static void M2(B? b)
{
(b with { X = 42 }).ToString(); // 2
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (7,18): warning CS8602: Dereference of a possibly null reference.
// var b1 = b with { X = 42 }; // 1
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b").WithLocation(7, 18),
// (14,10): warning CS8602: Dereference of a possibly null reference.
// (b with { X = 42 }).ToString(); // 2
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b").WithLocation(14, 10));
}
[Fact, WorkItem(44763, "https://github.com/dotnet/roslyn/issues/44763")]
public void WithExpr_NullableAnalysis_05()
{
var src = @"
#nullable enable
record B(string? X, string? Y)
{
static void M1(bool flag)
{
B b = new B(""hello"", null);
if (flag)
{
b.X.ToString(); // shouldn't warn
b.Y.ToString(); // 1
}
b = b with { Y = ""world"" };
b.X.ToString(); // shouldn't warn
b.Y.ToString();
}
}";
// records should propagate the nullability of the
// constructor arguments to the corresponding properties.
// https://github.com/dotnet/roslyn/issues/44763
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (10,13): warning CS8602: Dereference of a possibly null reference.
// b.X.ToString(); // shouldn't warn
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(10, 13),
// (11,13): warning CS8602: Dereference of a possibly null reference.
// b.Y.ToString(); // 1
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Y").WithLocation(11, 13),
// (15,9): warning CS8602: Dereference of a possibly null reference.
// b.X.ToString(); // shouldn't warn
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(15, 9));
}
[Fact]
public void WithExpr_NullableAnalysis_06()
{
var src = @"
#nullable enable
record B
{
public string? X { get; init; }
public string? Y { get; init; }
static void M1(bool flag)
{
B b = new B { X = ""hello"", Y = null };
if (flag)
{
b.X.ToString();
b.Y.ToString(); // 1
}
b = b with { Y = ""world"" };
b.X.ToString();
b.Y.ToString();
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (14,13): warning CS8602: Dereference of a possibly null reference.
// b.Y.ToString(); // 1
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Y").WithLocation(14, 13)
);
}
[Fact, WorkItem(44691, "https://github.com/dotnet/roslyn/issues/44691")]
public void WithExpr_NullableAnalysis_07()
{
var src = @"
#nullable enable
using System.Diagnostics.CodeAnalysis;
record B([AllowNull] string X) // 1
{
static void M1(B b)
{
b.X.ToString();
b = b with { X = null }; // 2
b.X.ToString(); // 3
b = new B((string?)null);
b.X.ToString();
}
}";
var comp = CreateCompilation(new[] { src, AllowNullAttributeDefinition });
comp.VerifyDiagnostics(
// (5,10): warning CS8601: Possible null reference assignment.
// record B([AllowNull] string X) // 1
Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "[AllowNull] string X").WithLocation(5, 10),
// (10,26): warning CS8625: Cannot convert null literal to non-nullable reference type.
// b = b with { X = null }; // 2
Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 26),
// (11,9): warning CS8602: Dereference of a possibly null reference.
// b.X.ToString(); // 3
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(11, 9));
}
[Fact, WorkItem(44691, "https://github.com/dotnet/roslyn/issues/44691")]
public void WithExpr_NullableAnalysis_08()
{
var src = @"
#nullable enable
using System.Diagnostics.CodeAnalysis;
record B([property: AllowNull][AllowNull] string X)
{
static void M1(B b)
{
b.X.ToString();
b = b with { X = null };
b.X.ToString(); // 1
b = new B((string?)null);
b.X.ToString();
}
}";
var comp = CreateCompilation(new[] { src, AllowNullAttributeDefinition });
comp.VerifyDiagnostics(
// (11,9): warning CS8602: Dereference of a possibly null reference.
// b.X.ToString(); // 1
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(11, 9));
}
[Fact]
public void WithExpr_NullableAnalysis_09()
{
var src = @"
#nullable enable
record B(string? X, string? Y)
{
static void M1(B b1)
{
B b2 = b1 with { X = ""hello"" };
B b3 = b1 with { Y = ""world"" };
B b4 = b2 with { Y = ""world"" };
b1.X.ToString(); // 1
b1.Y.ToString(); // 2
b2.X.ToString();
b2.Y.ToString(); // 3
b3.X.ToString(); // 4
b3.Y.ToString();
b4.X.ToString();
b4.Y.ToString();
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (11,9): warning CS8602: Dereference of a possibly null reference.
// b1.X.ToString(); // 1
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b1.X").WithLocation(11, 9),
// (12,9): warning CS8602: Dereference of a possibly null reference.
// b1.Y.ToString(); // 2
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b1.Y").WithLocation(12, 9),
// (14,9): warning CS8602: Dereference of a possibly null reference.
// b2.Y.ToString(); // 3
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b2.Y").WithLocation(14, 9),
// (15,9): warning CS8602: Dereference of a possibly null reference.
// b3.X.ToString(); // 4
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b3.X").WithLocation(15, 9));
}
[Fact]
public void WithExpr_NullableAnalysis_10()
{
var src = @"
#nullable enable
record B(string? X, string? Y)
{
static void M1(B b1)
{
string? local = ""hello"";
_ = b1 with
{
X = local = null,
Y = local.ToString() // 1
};
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (11,17): warning CS8602: Dereference of a possibly null reference.
// Y = local.ToString() // 1
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "local").WithLocation(11, 17));
}
[Fact]
public void WithExpr_NullableAnalysis_11()
{
var src = @"
#nullable enable
record B(string X, string Y)
{
static string M0(out string? s) { s = null; return ""hello""; }
static void M1(B b1)
{
string? local = ""world"";
_ = b1 with
{
X = M0(out local),
Y = local // 1
};
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (13,17): warning CS8601: Possible null reference assignment.
// Y = local // 1
Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "local").WithLocation(13, 17));
}
[Fact]
public void WithExpr_NullableAnalysis_VariantClone()
{
var src = @"
#nullable enable
record A
{
public string? Y { get; init; }
public string? Z { get; init; }
}
record B(string? X) : A
{
public new string Z { get; init; } = ""zed"";
static void M1(B b1)
{
b1.Z.ToString();
(b1 with { Y = ""hello"" }).Y.ToString();
(b1 with { Y = ""hello"" }).Z.ToString();
}
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")]
[WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")]
public void WithExpr_NullableAnalysis_NullableClone()
{
var src = @"
#nullable enable
record B(string? X)
{
public B? Clone() => new B(X);
static void M1(B b1)
{
_ = b1 with { X = null }; // 1
(b1 with { X = null }).ToString(); // 2
}
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (10,21): warning CS8602: Dereference of a possibly null reference.
// _ = b1 with { X = null }; // 1
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "{ X = null }").WithLocation(10, 21),
// (11,18): warning CS8602: Dereference of a possibly null reference.
// (b1 with { X = null }).ToString(); // 2
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "{ X = null }").WithLocation(11, 18));
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")]
[WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")]
public void WithExpr_NullableAnalysis_MaybeNullClone()
{
var src = @"
#nullable enable
using System.Diagnostics.CodeAnalysis;
record B(string? X)
{
[return: MaybeNull]
public B Clone() => new B(X);
static void M1(B b1)
{
_ = b1 with { };
_ = b1 with { X = null }; // 1
(b1 with { X = null }).ToString(); // 2
}
}
";
var comp = CreateCompilation(new[] { src, MaybeNullAttributeDefinition });
comp.VerifyDiagnostics(
// (13,21): warning CS8602: Dereference of a possibly null reference.
// _ = b1 with { X = null }; // 1
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "{ X = null }").WithLocation(13, 21),
// (14,18): warning CS8602: Dereference of a possibly null reference.
// (b1 with { X = null }).ToString(); // 2
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "{ X = null }").WithLocation(14, 18));
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")]
[WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")]
public void WithExpr_NullableAnalysis_NotNullClone()
{
var src = @"
#nullable enable
using System.Diagnostics.CodeAnalysis;
record B(string? X)
{
[return: NotNull]
public B? Clone() => new B(X);
static void M1(B b1)
{
_ = b1 with { };
_ = b1 with { X = null };
(b1 with { X = null }).ToString();
}
}
";
var comp = CreateCompilation(new[] { src, NotNullAttributeDefinition });
comp.VerifyDiagnostics();
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")]
[WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")]
public void WithExpr_NullableAnalysis_NullableClone_NoInitializers()
{
var src = @"
#nullable enable
record B(string? X)
{
public B? Clone() => new B(X);
static void M1(B b1)
{
_ = b1 with { };
(b1 with { }).ToString(); // 1
}
}
";
var comp = CreateCompilation(src);
// Note: we expect to give a warning on `// 1`, but do not currently
// due to limitations of object initializer analysis.
// Tracking in https://github.com/dotnet/roslyn/issues/44759
comp.VerifyDiagnostics();
}
[Fact]
public void WithExprNominalRecord()
{
var src = @"
using System;
record C
{
public int X { get; set; }
public string Y { get; init; }
public long Z;
public event Action E;
public C() { }
public C(C other)
{
X = other.X;
Y = other.Y;
Z = other.Z;
E = other.E;
}
public static void Main()
{
var c = new C() { X = 1, Y = ""2"", Z = 3, E = () => { } };
var c2 = c with {};
Console.WriteLine(c.Equals(c2));
Console.WriteLine(ReferenceEquals(c, c2));
Console.WriteLine(c2.X);
Console.WriteLine(c2.Y);
Console.WriteLine(c2.Z);
Console.WriteLine(ReferenceEquals(c.E, c2.E));
var c3 = c with { Y = ""3"", X = 2 };
Console.WriteLine(c.Y);
Console.WriteLine(c3.Y);
Console.WriteLine(c.X);
Console.WriteLine(c3.X);
}
}";
var verifier = CompileAndVerify(src, expectedOutput: @"
True
False
1
2
3
True
2
3
1
2").VerifyDiagnostics();
}
[Fact]
public void WithExprNominalRecord2()
{
var comp1 = CreateCompilation(@"
public record C
{
public int X { get; set; }
public string Y { get; init; }
public long Z;
public C() { }
public C(C other)
{
X = other.X;
Y = other.Y;
Z = other.Z;
}
}");
var verifier = CompileAndVerify(@"
class D
{
public C M(C c) => c with
{
X = 5,
Y = ""a"",
Z = 2,
};
}", references: new[] { comp1.EmitToImageReference() }).VerifyDiagnostics();
verifier.VerifyIL("D.M", @"
{
// Code size 33 (0x21)
.maxstack 3
IL_0000: ldarg.1
IL_0001: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()""
IL_0006: dup
IL_0007: ldc.i4.5
IL_0008: callvirt ""void C.X.set""
IL_000d: dup
IL_000e: ldstr ""a""
IL_0013: callvirt ""void C.Y.init""
IL_0018: dup
IL_0019: ldc.i4.2
IL_001a: conv.i8
IL_001b: stfld ""long C.Z""
IL_0020: ret
}");
}
[Fact]
public void WithExprAssignToRef1()
{
var src = @"
using System;
record C(int Y)
{
private readonly int[] _a = new[] { 0 };
public ref int X => ref _a[0];
public static void Main()
{
var c = new C(0) { X = 5 };
Console.WriteLine(c.X);
c = c with { X = 1 };
Console.WriteLine(c.X);
}
}";
var verifier = CompileAndVerify(src, expectedOutput: @"
5
1").VerifyDiagnostics();
verifier.VerifyIL("C.Main", @"
{
// Code size 51 (0x33)
.maxstack 3
IL_0000: ldc.i4.0
IL_0001: newobj ""C..ctor(int)""
IL_0006: dup
IL_0007: callvirt ""ref int C.X.get""
IL_000c: ldc.i4.5
IL_000d: stind.i4
IL_000e: dup
IL_000f: callvirt ""ref int C.X.get""
IL_0014: ldind.i4
IL_0015: call ""void System.Console.WriteLine(int)""
IL_001a: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()""
IL_001f: dup
IL_0020: callvirt ""ref int C.X.get""
IL_0025: ldc.i4.1
IL_0026: stind.i4
IL_0027: callvirt ""ref int C.X.get""
IL_002c: ldind.i4
IL_002d: call ""void System.Console.WriteLine(int)""
IL_0032: ret
}");
}
[Fact]
public void WithExprAssignToRef2()
{
var src = @"
using System;
record C(int Y)
{
private readonly int[] _a = new[] { 0 };
public ref int X
{
get => ref _a[0];
set { }
}
public static void Main()
{
var a = new[] { 0 };
var c = new C(0) { X = ref a[0] };
Console.WriteLine(c.X);
c = c with { X = ref a[0] };
Console.WriteLine(c.X);
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (9,9): error CS8147: Properties which return by reference cannot have set accessors
// set { }
Diagnostic(ErrorCode.ERR_RefPropertyCannotHaveSetAccessor, "set").WithArguments("C.X.set").WithLocation(9, 9),
// (15,32): error CS1525: Invalid expression term 'ref'
// var c = new C(0) { X = ref a[0] };
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "ref a[0]").WithArguments("ref").WithLocation(15, 32),
// (15,32): error CS1073: Unexpected token 'ref'
// var c = new C(0) { X = ref a[0] };
Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(15, 32),
// (17,26): error CS1073: Unexpected token 'ref'
// c = c with { X = ref a[0] };
Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(17, 26)
);
}
[Fact]
public void WithExpressionSameLHS()
{
var comp = CreateCompilation(@"
record C(int X)
{
public static void Main()
{
var c = new C(0);
c = c with { X = 1, X = 2};
}
}");
comp.VerifyDiagnostics(
// (7,29): error CS1912: Duplicate initialization of member 'X'
// c = c with { X = 1, X = 2};
Diagnostic(ErrorCode.ERR_MemberAlreadyInitialized, "X").WithArguments("X").WithLocation(7, 29)
);
}
[Fact]
public void WithExpr_ValEscape()
{
var text = @"
using System;
record R
{
public S1 Property { set { throw null; } }
}
class Program
{
static void Main()
{
var r = new R();
Span<int> local = stackalloc int[1];
_ = r with { Property = MayWrap(ref local) };
_ = new R() { Property = MayWrap(ref local) };
}
static S1 MayWrap(ref Span<int> arg)
{
return default;
}
}
ref struct S1
{
public ref int this[int i] => throw null;
}
";
CreateCompilationWithMscorlibAndSpan(text).VerifyDiagnostics();
}
[WorkItem(44616, "https://github.com/dotnet/roslyn/issues/44616")]
[Fact]
public void Inheritance_01()
{
var source =
@"record A
{
internal A() { }
public object P1 { get; set; }
internal object P2 { get; set; }
protected internal object P3 { get; set; }
protected object P4 { get; set; }
private protected object P5 { get; set; }
private object P6 { get; set; }
}
record B(object P1, object P2, object P3, object P4, object P5, object P6) : A
{
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (11,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(11, 17),
// (11,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(11, 28),
// (11,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(11, 39),
// (11,50): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(11, 50),
// (11,61): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(11, 61)
);
var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type B.EqualityContract { get; }",
"System.Object B.P6 { get; init; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[WorkItem(44616, "https://github.com/dotnet/roslyn/issues/44616")]
[Fact]
public void Inheritance_02()
{
var source =
@"record A
{
internal A() { }
private protected object P1 { get; set; }
private object P2 { get; set; }
private record B(object P1, object P2) : A
{
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,29): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// private record B(object P1, object P2) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(6, 29),
// (6,40): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// private record B(object P1, object P2) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(6, 40)
);
var actualMembers = GetProperties(comp, "A.B").ToTestDisplayStrings();
AssertEx.Equal(new[] { "System.Type A.B.EqualityContract { get; }" }, actualMembers);
}
[WorkItem(44616, "https://github.com/dotnet/roslyn/issues/44616")]
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Inheritance_03(bool useCompilationReference)
{
var sourceA =
@"public record A
{
public A() { }
internal object P { get; set; }
}
public record B(object Q) : A
{
public B() : this(null) { }
}
record C1(object P, object Q) : B
{
}";
var comp = CreateCompilation(sourceA);
AssertEx.Equal(new[] { "System.Type C1.EqualityContract { get; }" }, GetProperties(comp, "C1").ToTestDisplayStrings());
var refA = useCompilationReference ? comp.ToMetadataReference() : comp.EmitToImageReference();
var sourceB =
@"record C2(object P, object Q) : B
{
}";
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (1,28): warning CS8907: Parameter 'Q' is unread. Did you forget to use it to initialize the property with that name?
// record C2(object P, object Q) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Q").WithArguments("Q").WithLocation(1, 28)
);
AssertEx.Equal(new[] { "System.Type C2.EqualityContract { get; }", "System.Object C2.P { get; init; }" }, GetProperties(comp, "C2").ToTestDisplayStrings());
}
[WorkItem(44616, "https://github.com/dotnet/roslyn/issues/44616")]
[Fact]
public void Inheritance_04()
{
var source =
@"record A
{
internal A() { }
public object P1 { get { return null; } set { } }
public object P2 { get; init; }
public object P3 { get; }
public object P4 { set { } }
public virtual object P5 { get; set; }
public static object P6 { get; set; }
public ref object P7 => throw null;
}
record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A
{
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (12,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(12, 17),
// (12,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(12, 28),
// (12,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(12, 39),
// (12,50): error CS8866: Record member 'A.P4' must be a readable instance property or field of type 'object' to match positional parameter 'P4'.
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P4").WithArguments("A.P4", "object", "P4").WithLocation(12, 50),
// (12,50): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(12, 50),
// (12,61): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(12, 61),
// (12,72): error CS8866: Record member 'A.P6' must be a readable instance property or field of type 'object' to match positional parameter 'P6'.
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P6").WithArguments("A.P6", "object", "P6").WithLocation(12, 72),
// (12,72): warning CS8907: Parameter 'P6' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P6").WithArguments("P6").WithLocation(12, 72),
// (12,83): warning CS8907: Parameter 'P7' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P7").WithArguments("P7").WithLocation(12, 83));
var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings();
AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers);
}
[Fact]
public void Inheritance_05()
{
var source =
@"record A
{
internal A() { }
public object P1 { get; set; }
public int P2 { get; set; }
}
record B(int P1, object P2) : A
{
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (7,14): error CS8866: Record member 'A.P1' must be a readable instance property or field of type 'int' to match positional parameter 'P1'.
// record B(int P1, object P2) : A
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("A.P1", "int", "P1").WithLocation(7, 14),
// (7,14): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record B(int P1, object P2) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(7, 14),
// (7,25): error CS8866: Record member 'A.P2' must be a readable instance property or field of type 'object' to match positional parameter 'P2'.
// record B(int P1, object P2) : A
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P2").WithArguments("A.P2", "object", "P2").WithLocation(7, 25),
// (7,25): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record B(int P1, object P2) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(7, 25));
var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings();
AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers);
}
[Fact]
public void Inheritance_06()
{
var source =
@"record A
{
internal int X { get; set; }
internal int Y { set { } }
internal int Z;
}
record B(int X, int Y, int Z) : A
{
}
class Program
{
static void Main()
{
var b = new B(1, 2, 3);
b.X = 4;
b.Y = 5;
b.Z = 6;
((A)b).X = 7;
((A)b).Y = 8;
((A)b).Z = 9;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (7,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record B(int X, int Y, int Z) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(7, 14),
// (7,21): error CS8866: Record member 'A.Y' must be a readable instance property or field of type 'int' to match positional parameter 'Y'.
// record B(int X, int Y, int Z) : A
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Y").WithArguments("A.Y", "int", "Y").WithLocation(7, 21),
// (7,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// record B(int X, int Y, int Z) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(7, 21),
// (7,24): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater.
// record B(int X, int Y, int Z) : A
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int Z").WithArguments("positional fields in records", "10.0").WithLocation(7, 24),
// (7,28): warning CS8907: Parameter 'Z' is unread. Did you forget to use it to initialize the property with that name?
// record B(int X, int Y, int Z) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Z").WithArguments("Z").WithLocation(7, 28));
var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings();
AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers);
}
[WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")]
[Fact]
public void Inheritance_07()
{
var source =
@"abstract record A
{
public abstract int X { get; }
public virtual int Y { get; }
}
abstract record B1(int X, int Y) : A
{
}
record B2(int X, int Y) : A
{
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,24): error CS0546: 'B1.X.init': cannot override because 'A.X' does not have an overridable set accessor
// abstract record B1(int X, int Y) : A
Diagnostic(ErrorCode.ERR_NoSetToOverride, "X").WithArguments("B1.X.init", "A.X").WithLocation(6, 24),
// (6,31): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// abstract record B1(int X, int Y) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(6, 31),
// (9,15): error CS0546: 'B2.X.init': cannot override because 'A.X' does not have an overridable set accessor
// record B2(int X, int Y) : A
Diagnostic(ErrorCode.ERR_NoSetToOverride, "X").WithArguments("B2.X.init", "A.X").WithLocation(9, 15),
// (9,22): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// record B2(int X, int Y) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(9, 22));
AssertEx.Equal(new[] { "System.Type B1.EqualityContract { get; }", "System.Int32 B1.X { get; init; }" }, GetProperties(comp, "B1").ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.Type B2.EqualityContract { get; }", "System.Int32 B2.X { get; init; }" }, GetProperties(comp, "B2").ToTestDisplayStrings());
var b1Ctor = comp.GetTypeByMetadataName("B1")!.GetMembersUnordered().OfType<SynthesizedRecordConstructor>().Single();
Assert.Equal("B1..ctor(System.Int32 X, System.Int32 Y)", b1Ctor.ToTestDisplayString());
Assert.Equal(Accessibility.Protected, b1Ctor.DeclaredAccessibility);
}
[WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")]
[Fact]
public void Inheritance_08()
{
var source =
@"abstract record A
{
public abstract int X { get; }
public virtual int Y { get; }
public virtual int Z { get; }
}
abstract record B : A
{
public override abstract int Y { get; }
}
record C(int X, int Y, int Z) : B
{
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (11,14): error CS0546: 'C.X.init': cannot override because 'A.X' does not have an overridable set accessor
// record C(int X, int Y, int Z) : B
Diagnostic(ErrorCode.ERR_NoSetToOverride, "X").WithArguments("C.X.init", "A.X").WithLocation(11, 14),
// (11,21): error CS0546: 'C.Y.init': cannot override because 'B.Y' does not have an overridable set accessor
// record C(int X, int Y, int Z) : B
Diagnostic(ErrorCode.ERR_NoSetToOverride, "Y").WithArguments("C.Y.init", "B.Y").WithLocation(11, 21),
// (11,28): warning CS8907: Parameter 'Z' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X, int Y, int Z) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Z").WithArguments("Z").WithLocation(11, 28));
var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings();
AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }", "System.Int32 C.X { get; init; }", "System.Int32 C.Y { get; init; }" }, actualMembers);
}
[Fact, WorkItem(48947, "https://github.com/dotnet/roslyn/issues/48947")]
public void Inheritance_09()
{
var source =
@"abstract record C(int X, int Y)
{
public abstract int X { get; }
public virtual int Y { get; }
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (1,23): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// abstract record C(int X, int Y)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(1, 23),
// (1,30): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// abstract record C(int X, int Y)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(1, 30)
);
NamedTypeSymbol c = comp.GetMember<NamedTypeSymbol>("C");
var actualMembers = c.GetMembers().ToTestDisplayStrings();
var expectedMembers = new[]
{
"C..ctor(System.Int32 X, System.Int32 Y)",
"System.Type C.EqualityContract.get",
"System.Type C.EqualityContract { get; }",
"System.Int32 C.X { get; }",
"System.Int32 C.X.get",
"System.Int32 C.<Y>k__BackingField",
"System.Int32 C.Y { get; }",
"System.Int32 C.Y.get",
"System.String C.ToString()",
"System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)",
"System.Boolean C.op_Inequality(C? left, C? right)",
"System.Boolean C.op_Equality(C? left, C? right)",
"System.Int32 C.GetHashCode()",
"System.Boolean C.Equals(System.Object? obj)",
"System.Boolean C.Equals(C? other)",
"C C." + WellKnownMemberNames.CloneMethodName + "()",
"C..ctor(C original)",
"void C.Deconstruct(out System.Int32 X, out System.Int32 Y)"
};
AssertEx.Equal(expectedMembers, actualMembers);
var expectedMemberNames = new[] {
".ctor",
"get_EqualityContract",
"EqualityContract",
"X",
"get_X",
"<Y>k__BackingField",
"Y",
"get_Y",
"ToString",
"PrintMembers",
"op_Inequality",
"op_Equality",
"GetHashCode",
"Equals",
"Equals",
"<Clone>$",
".ctor",
"Deconstruct"
};
AssertEx.Equal(expectedMemberNames, c.GetPublicSymbol().MemberNames);
var expectedCtors = new[]
{
"C..ctor(System.Int32 X, System.Int32 Y)",
"C..ctor(C original)",
};
AssertEx.Equal(expectedCtors, c.GetPublicSymbol().Constructors.ToTestDisplayStrings());
}
[Fact]
public void Inheritance_10()
{
var source =
@"using System;
interface IA
{
int X { get; }
}
interface IB
{
int Y { get; }
}
record C(int X, int Y) : IA, IB
{
}
class Program
{
static void Main()
{
var c = new C(1, 2);
Console.WriteLine(""{0}, {1}"", c.X, c.Y);
Console.WriteLine(""{0}, {1}"", ((IA)c).X, ((IB)c).Y);
}
}";
CompileAndVerify(source, expectedOutput:
@"1, 2
1, 2").VerifyDiagnostics();
}
[Fact]
public void Inheritance_11()
{
var source =
@"interface IA
{
int X { get; }
}
interface IB
{
object Y { get; set; }
}
record C(object X, object Y) : IA, IB
{
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (9,32): error CS0738: 'C' does not implement interface member 'IA.X'. 'C.X' cannot implement 'IA.X' because it does not have the matching return type of 'int'.
// record C(object X, object Y) : IA, IB
Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "IA").WithArguments("C", "IA.X", "C.X", "int").WithLocation(9, 32),
// (9,36): error CS8854: 'C' does not implement interface member 'IB.Y.set'. 'C.Y.init' cannot implement 'IB.Y.set'.
// record C(object X, object Y) : IA, IB
Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "IB").WithArguments("C", "IB.Y.set", "C.Y.init").WithLocation(9, 36)
);
}
[Fact]
public void Inheritance_12()
{
var source =
@"record A
{
public object X { get; }
public object Y { get; }
}
record B(object X, object Y) : A
{
public object X { get; }
public object Y { get; }
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,17): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record B(object X, object Y) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(6, 17),
// (6,27): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// record B(object X, object Y) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(6, 27),
// (8,19): warning CS0108: 'B.X' hides inherited member 'A.X'. Use the new keyword if hiding was intended.
// public object X { get; }
Diagnostic(ErrorCode.WRN_NewRequired, "X").WithArguments("B.X", "A.X").WithLocation(8, 19),
// (9,19): warning CS0108: 'B.Y' hides inherited member 'A.Y'. Use the new keyword if hiding was intended.
// public object Y { get; }
Diagnostic(ErrorCode.WRN_NewRequired, "Y").WithArguments("B.Y", "A.Y").WithLocation(9, 19));
var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type B.EqualityContract { get; }",
"System.Object B.X { get; }",
"System.Object B.Y { get; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void Inheritance_13()
{
var source =
@"record A(object X, object Y)
{
internal A() : this(null, null) { }
}
record B(object X, object Y) : A
{
public object X { get; }
public object Y { get; }
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (5,17): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record B(object X, object Y) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(5, 17),
// (5,27): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// record B(object X, object Y) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(5, 27),
// (7,19): warning CS0108: 'B.X' hides inherited member 'A.X'. Use the new keyword if hiding was intended.
// public object X { get; }
Diagnostic(ErrorCode.WRN_NewRequired, "X").WithArguments("B.X", "A.X").WithLocation(7, 19),
// (8,19): warning CS0108: 'B.Y' hides inherited member 'A.Y'. Use the new keyword if hiding was intended.
// public object Y { get; }
Diagnostic(ErrorCode.WRN_NewRequired, "Y").WithArguments("B.Y", "A.Y").WithLocation(8, 19));
var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type B.EqualityContract { get; }",
"System.Object B.X { get; }",
"System.Object B.Y { get; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void Inheritance_14()
{
var source =
@"record A
{
public object P1 { get; }
public object P2 { get; }
public object P3 { get; }
public object P4 { get; }
}
record B : A
{
public new int P1 { get; }
public new int P2 { get; }
}
record C(object P1, int P2, object P3, int P4) : B
{
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (13,17): error CS8866: Record member 'B.P1' must be a readable instance property or field of type 'object' to match positional parameter 'P1'.
// record C(object P1, int P2, object P3, int P4) : B
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("B.P1", "object", "P1").WithLocation(13, 17),
// (13,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, int P2, object P3, int P4) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(13, 17),
// (13,25): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, int P2, object P3, int P4) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(13, 25),
// (13,36): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, int P2, object P3, int P4) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(13, 36),
// (13,44): error CS8866: Record member 'A.P4' must be a readable instance property or field of type 'int' to match positional parameter 'P4'.
// record C(object P1, int P2, object P3, int P4) : B
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P4").WithArguments("A.P4", "int", "P4").WithLocation(13, 44),
// (13,44): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, int P2, object P3, int P4) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(13, 44));
var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings();
AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }" }, actualMembers);
}
[Fact]
public void Inheritance_15()
{
var source =
@"record C(int P1, object P2)
{
public object P1 { get; set; }
public int P2 { get; set; }
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (1,14): error CS8866: Record member 'C.P1' must be a readable instance property or field of type 'int' to match positional parameter 'P1'.
// record C(int P1, object P2)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("C.P1", "int", "P1").WithLocation(1, 14),
// (1,14): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record C(int P1, object P2)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(1, 14),
// (1,25): error CS8866: Record member 'C.P2' must be a readable instance property or field of type 'object' to match positional parameter 'P2'.
// record C(int P1, object P2)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P2").WithArguments("C.P2", "object", "P2").WithLocation(1, 25),
// (1,25): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record C(int P1, object P2)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 25));
var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type C.EqualityContract { get; }",
"System.Object C.P1 { get; set; }",
"System.Int32 C.P2 { get; set; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void Inheritance_16()
{
var source =
@"record A
{
public int P1 { get; }
public int P2 { get; }
public int P3 { get; }
public int P4 { get; }
}
record B(object P1, int P2, object P3, int P4) : A
{
public new object P1 { get; }
public new object P2 { get; }
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, int P2, object P3, int P4) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(8, 17),
// (8,25): error CS8866: Record member 'B.P2' must be a readable instance property or field of type 'int' to match positional parameter 'P2'.
// record B(object P1, int P2, object P3, int P4) : A
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P2").WithArguments("B.P2", "int", "P2").WithLocation(8, 25),
// (8,25): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, int P2, object P3, int P4) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(8, 25),
// (8,36): error CS8866: Record member 'A.P3' must be a readable instance property or field of type 'object' to match positional parameter 'P3'.
// record B(object P1, int P2, object P3, int P4) : A
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P3").WithArguments("A.P3", "object", "P3").WithLocation(8, 36),
// (8,36): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, int P2, object P3, int P4) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(8, 36),
// (8,44): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, int P2, object P3, int P4) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(8, 44));
var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type B.EqualityContract { get; }",
"System.Object B.P1 { get; }",
"System.Object B.P2 { get; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void Inheritance_17()
{
var source =
@"record A
{
public object P1 { get; }
public object P2 { get; }
public object P3 { get; }
public object P4 { get; }
}
record B(object P1, int P2, object P3, int P4) : A
{
public new int P1 { get; }
public new int P2 { get; }
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,17): error CS8866: Record member 'B.P1' must be a readable instance property or field of type 'object' to match positional parameter 'P1'.
// record B(object P1, int P2, object P3, int P4) : A
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("B.P1", "object", "P1").WithLocation(8, 17),
// (8,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, int P2, object P3, int P4) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(8, 17),
// (8,25): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, int P2, object P3, int P4) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(8, 25),
// (8,36): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, int P2, object P3, int P4) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(8, 36),
// (8,44): error CS8866: Record member 'A.P4' must be a readable instance property or field of type 'int' to match positional parameter 'P4'.
// record B(object P1, int P2, object P3, int P4) : A
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P4").WithArguments("A.P4", "int", "P4").WithLocation(8, 44),
// (8,44): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, int P2, object P3, int P4) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(8, 44));
var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type B.EqualityContract { get; }",
"System.Int32 B.P1 { get; }",
"System.Int32 B.P2 { get; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void Inheritance_18()
{
var source =
@"record C(object P1, object P2, object P3, object P4, object P5)
{
public object P1 { get { return null; } set { } }
public object P2 { get; }
public object P3 { set { } }
public static object P4 { get; set; }
public ref object P5 => throw null;
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (1,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, object P2, object P3, object P4, object P5)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(1, 17),
// (1,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, object P2, object P3, object P4, object P5)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 28),
// (1,39): error CS8866: Record member 'C.P3' must be a readable instance property or field of type 'object' to match positional parameter 'P3'.
// record C(object P1, object P2, object P3, object P4, object P5)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P3").WithArguments("C.P3", "object", "P3").WithLocation(1, 39),
// (1,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, object P2, object P3, object P4, object P5)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(1, 39),
// (1,50): error CS8866: Record member 'C.P4' must be a readable instance property or field of type 'object' to match positional parameter 'P4'.
// record C(object P1, object P2, object P3, object P4, object P5)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P4").WithArguments("C.P4", "object", "P4").WithLocation(1, 50),
// (1,50): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, object P2, object P3, object P4, object P5)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(1, 50),
// (1,61): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, object P2, object P3, object P4, object P5)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(1, 61));
var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type C.EqualityContract { get; }",
"System.Object C.P1 { get; set; }",
"System.Object C.P2 { get; }",
"System.Object C.P3 { set; }",
"System.Object C.P4 { get; set; }",
"ref System.Object C.P5 { get; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void Inheritance_19()
{
var source =
@"#pragma warning disable 8618
#nullable enable
record A
{
internal A() { }
public object P1 { get; }
public dynamic[] P2 { get; }
public object? P3 { get; }
public object[] P4 { get; }
public (int X, int Y) P5 { get; }
public (int, int)[] P6 { get; }
public nint P7 { get; }
public System.UIntPtr[] P8 { get; }
}
record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A
{
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (15,18): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(15, 18),
// (15,31): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(15, 31),
// (15,42): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name?
// record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(15, 42),
// (15,56): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name?
// record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(15, 56),
// (15,71): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name?
// record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(15, 71),
// (15,92): warning CS8907: Parameter 'P6' is unread. Did you forget to use it to initialize the property with that name?
// record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P6").WithArguments("P6").WithLocation(15, 92),
// (15,110): warning CS8907: Parameter 'P7' is unread. Did you forget to use it to initialize the property with that name?
// record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P7").WithArguments("P7").WithLocation(15, 110),
// (15,122): warning CS8907: Parameter 'P8' is unread. Did you forget to use it to initialize the property with that name?
// record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P8").WithArguments("P8").WithLocation(15, 122)
);
var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings();
AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers);
}
[Fact]
public void Inheritance_20()
{
var source =
@"#pragma warning disable 8618
#nullable enable
record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8)
{
public object P1 { get; }
public dynamic[] P2 { get; }
public object? P3 { get; }
public object[] P4 { get; }
public (int X, int Y) P5 { get; }
public (int, int)[] P6 { get; }
public nint P7 { get; }
public System.UIntPtr[] P8 { get; }
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (3,18): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(3, 18),
// (3,31): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(3, 31),
// (3,42): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name?
// record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(3, 42),
// (3,56): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name?
// record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(3, 56),
// (3,71): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name?
// record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(3, 71),
// (3,92): warning CS8907: Parameter 'P6' is unread. Did you forget to use it to initialize the property with that name?
// record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P6").WithArguments("P6").WithLocation(3, 92),
// (3,110): warning CS8907: Parameter 'P7' is unread. Did you forget to use it to initialize the property with that name?
// record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P7").WithArguments("P7").WithLocation(3, 110),
// (3,122): warning CS8907: Parameter 'P8' is unread. Did you forget to use it to initialize the property with that name?
// record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P8").WithArguments("P8").WithLocation(3, 122)
);
var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type C.EqualityContract { get; }",
"System.Object C.P1 { get; }",
"dynamic[] C.P2 { get; }",
"System.Object? C.P3 { get; }",
"System.Object[] C.P4 { get; }",
"(System.Int32 X, System.Int32 Y) C.P5 { get; }",
"(System.Int32, System.Int32)[] C.P6 { get; }",
"nint C.P7 { get; }",
"System.UIntPtr[] C.P8 { get; }"
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Inheritance_21(bool useCompilationReference)
{
var sourceA =
@"public record A
{
public object P1 { get; }
internal object P2 { get; }
}
public record B : A
{
internal new object P1 { get; }
public new object P2 { get; }
}";
var comp = CreateCompilation(sourceA);
var refA = useCompilationReference ? comp.ToMetadataReference() : comp.EmitToImageReference();
var sourceB =
@"record C(object P1, object P2) : B
{
}
class Program
{
static void Main()
{
var c = new C(1, 2);
System.Console.WriteLine(""({0}, {1})"", c.P1, c.P2);
}
}";
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings();
AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }" }, actualMembers);
var verifier = CompileAndVerify(comp, expectedOutput: "(, )").VerifyDiagnostics(
// (1,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, object P2) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(1, 17),
// (1,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, object P2) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 28)
);
verifier.VerifyIL("C..ctor(object, object)",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""B..ctor()""
IL_0006: ret
}");
verifier.VerifyIL("C..ctor(C)", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""B..ctor(B)""
IL_0007: ret
}");
verifier.VerifyIL("Program.Main",
@"{
// Code size 41 (0x29)
.maxstack 3
.locals init (C V_0) //c
IL_0000: ldc.i4.1
IL_0001: box ""int""
IL_0006: ldc.i4.2
IL_0007: box ""int""
IL_000c: newobj ""C..ctor(object, object)""
IL_0011: stloc.0
IL_0012: ldstr ""({0}, {1})""
IL_0017: ldloc.0
IL_0018: callvirt ""object A.P1.get""
IL_001d: ldloc.0
IL_001e: callvirt ""object B.P2.get""
IL_0023: call ""void System.Console.WriteLine(string, object, object)""
IL_0028: ret
}");
}
[Fact]
public void Inheritance_22()
{
var source =
@"record A
{
public ref object P1 => throw null;
public object P2 => throw null;
}
record B : A
{
public new object P1 => throw null;
public new ref object P2 => throw null;
}
record C(object P1, object P2) : B
{
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (11,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, object P2) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(11, 17),
// (11,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, object P2) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(11, 28)
);
var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings();
AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }" }, actualMembers);
}
[Fact]
public void Inheritance_23()
{
var source =
@"record A
{
public static object P1 { get; }
public object P2 { get; }
}
record B : A
{
public new object P1 { get; }
public new static object P2 { get; }
}
record C(object P1, object P2) : B
{
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (11,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, object P2) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(11, 17),
// (11,28): error CS8866: Record member 'B.P2' must be a readable instance property or field of type 'object' to match positional parameter 'P2'.
// record C(object P1, object P2) : B
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P2").WithArguments("B.P2", "object", "P2").WithLocation(11, 28),
// (11,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P1, object P2) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(11, 28));
var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings();
AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }" }, actualMembers);
}
[Fact]
public void Inheritance_24()
{
var source =
@"record A
{
public object get_P() => null;
public object set_Q() => null;
}
record B(object P, object Q) : A
{
}
record C(object P)
{
public object get_P() => null;
public object set_Q() => null;
}";
var comp = CreateCompilation(RuntimeUtilities.IsCoreClrRuntime ? source : new[] { source, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.StandardLatest);
comp.VerifyDiagnostics(
// (9,17): error CS0082: Type 'C' already reserves a member called 'get_P' with the same parameter types
// record C(object P)
Diagnostic(ErrorCode.ERR_MemberReserved, "P").WithArguments("get_P", "C").WithLocation(9, 17));
Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses);
var expectedClone = comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses
? "B B." + WellKnownMemberNames.CloneMethodName + "()"
: "A B." + WellKnownMemberNames.CloneMethodName + "()";
var expectedMembers = new[]
{
"B..ctor(System.Object P, System.Object Q)",
"System.Type B.EqualityContract.get",
"System.Type B.EqualityContract { get; }",
"System.Object B.<P>k__BackingField",
"System.Object B.P.get",
"void modreq(System.Runtime.CompilerServices.IsExternalInit) B.P.init",
"System.Object B.P { get; init; }",
"System.Object B.<Q>k__BackingField",
"System.Object B.Q.get",
"void modreq(System.Runtime.CompilerServices.IsExternalInit) B.Q.init",
"System.Object B.Q { get; init; }",
"System.String B.ToString()",
"System.Boolean B." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)",
"System.Boolean B.op_Inequality(B? left, B? right)",
"System.Boolean B.op_Equality(B? left, B? right)",
"System.Int32 B.GetHashCode()",
"System.Boolean B.Equals(System.Object? obj)",
"System.Boolean B.Equals(A? other)",
"System.Boolean B.Equals(B? other)",
expectedClone,
"B..ctor(B original)",
"void B.Deconstruct(out System.Object P, out System.Object Q)"
};
AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("B").GetMembers().ToTestDisplayStrings());
expectedMembers = new[]
{
"C..ctor(System.Object P)",
"System.Type C.EqualityContract.get",
"System.Type C.EqualityContract { get; }",
"System.Object C.<P>k__BackingField",
"System.Object C.P.get",
"void modreq(System.Runtime.CompilerServices.IsExternalInit) C.P.init",
"System.Object C.P { get; init; }",
"System.Object C.get_P()",
"System.Object C.set_Q()",
"System.String C.ToString()",
"System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)",
"System.Boolean C.op_Inequality(C? left, C? right)",
"System.Boolean C.op_Equality(C? left, C? right)",
"System.Int32 C.GetHashCode()",
"System.Boolean C.Equals(System.Object? obj)",
"System.Boolean C.Equals(C? other)",
"C C." + WellKnownMemberNames.CloneMethodName + "()",
"C..ctor(C original)",
"void C.Deconstruct(out System.Object P)"
};
AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings());
}
[Fact]
public void Inheritance_25()
{
var sourceA =
@"public record A
{
public class P1 { }
internal object P2 = 2;
public int P3(object o) => 3;
internal int P4<T>(T t) => 4;
}";
var sourceB =
@"record B(object P1, object P2, object P3, object P4) : A
{
}";
var comp = CreateCompilation(new[] { sourceA, sourceB, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (1,17): error CS8866: Record member 'A.P1' must be a readable instance property or field of type 'object' to match positional parameter 'P1'.
// record B(object P1, object P2, object P3, object P4) : A
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("A.P1", "object", "P1").WithLocation(1, 17),
// (1,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(1, 17),
// (1,21): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater.
// record B(object P1, object P2, object P3, object P4) : A
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object P2").WithArguments("positional fields in records", "10.0").WithLocation(1, 21),
// (1,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 28),
// (1,39): error CS8866: Record member 'A.P3' must be a readable instance property or field of type 'object' to match positional parameter 'P3'.
// record B(object P1, object P2, object P3, object P4) : A
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P3").WithArguments("A.P3", "object", "P3").WithLocation(1, 39),
// (1,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(1, 39));
var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type B.EqualityContract { get; }",
"System.Object B.P4 { get; init; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
comp = CreateCompilation(sourceA);
var refA = comp.EmitToImageReference();
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (1,17): error CS8866: Record member 'A.P1' must be a readable instance property or field of type 'object' to match positional parameter 'P1'.
// record B(object P1, object P2, object P3, object P4) : A
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("A.P1", "object", "P1").WithLocation(1, 17),
// (1,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(1, 17),
// (1,39): error CS8866: Record member 'A.P3' must be a readable instance property or field of type 'object' to match positional parameter 'P3'.
// record B(object P1, object P2, object P3, object P4) : A
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P3").WithArguments("A.P3", "object", "P3").WithLocation(1, 39),
// (1,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(1, 39));
actualMembers = GetProperties(comp, "B").ToTestDisplayStrings();
expectedMembers = new[]
{
"System.Type B.EqualityContract { get; }",
"System.Object B.P2 { get; init; }",
"System.Object B.P4 { get; init; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void Inheritance_26()
{
var sourceA =
@"public record A
{
internal const int P = 4;
}";
var sourceB =
@"record B(object P) : A
{
}";
var comp = CreateCompilation(new[] { sourceA, sourceB });
comp.VerifyDiagnostics(
// (1,17): error CS8866: Record member 'A.P' must be a readable instance property or field of type 'object' to match positional parameter 'P'.
// record B(object P) : A
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("A.P", "object", "P").WithLocation(1, 17),
// (1,17): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(1, 17));
AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, GetProperties(comp, "B").ToTestDisplayStrings());
comp = CreateCompilation(sourceA);
var refA = comp.EmitToImageReference();
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }", "System.Object B.P { get; init; }" }, GetProperties(comp, "B").ToTestDisplayStrings());
}
[Fact]
public void Inheritance_27()
{
var source =
@"record A
{
public object P { get; }
public object Q { get; set; }
}
record B(object get_P, object set_Q) : A
{
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type B.EqualityContract { get; }",
"System.Object B.get_P { get; init; }",
"System.Object B.set_Q { get; init; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void Inheritance_28()
{
var source =
@"interface I
{
object P { get; }
}
record A : I
{
object I.P => null;
}
record B(object P) : A
{
}
record C(object P) : I
{
object I.P => null;
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }", "System.Object B.P { get; init; }" }, GetProperties(comp, "B").ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }", "System.Object C.P { get; init; }", "System.Object C.I.P { get; }" }, GetProperties(comp, "C").ToTestDisplayStrings());
}
[Fact]
public void Inheritance_29()
{
var sourceA =
@"Public Class A
Public Property P(o As Object) As Object
Get
Return Nothing
End Get
Set
End Set
End Property
Public Property Q(x As Object, y As Object) As Object
Get
Return Nothing
End Get
Set
End Set
End Property
End Class
";
var compA = CreateVisualBasicCompilation(sourceA);
compA.VerifyDiagnostics();
var refA = compA.EmitToImageReference();
var sourceB =
@"record B(object P, object Q) : A
{
object P { get; }
}";
var compB = CreateCompilation(new[] { sourceB, IsExternalInitTypeDefinition }, references: new[] { refA }, parseOptions: TestOptions.Regular9);
compB.VerifyDiagnostics(
// (1,8): error CS0115: 'B.EqualityContract': no suitable method found to override
// record B(object P, object Q) : A
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.EqualityContract").WithLocation(1, 8),
// (1,8): error CS0115: 'B.Equals(A?)': no suitable method found to override
// record B(object P, object Q) : A
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.Equals(A?)").WithLocation(1, 8),
// (1,8): error CS0115: 'B.PrintMembers(StringBuilder)': no suitable method found to override
// record B(object P, object Q) : A
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)").WithLocation(1, 8),
// (1,8): error CS8867: No accessible copy constructor found in base type 'A'.
// record B(object P, object Q) : A
Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "B").WithArguments("A").WithLocation(1, 8),
// (1,17): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P, object Q) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(1, 17),
// (1,32): error CS8864: Records may only inherit from object or another record
// record B(object P, object Q) : A
Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(1, 32)
);
var actualMembers = GetProperties(compB, "B").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type B.EqualityContract { get; }",
"System.Object B.Q { get; init; }",
"System.Object B.P { get; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void Inheritance_30()
{
var sourceA =
@"Public Class A
Public ReadOnly Overloads Property P() As Object
Get
Return Nothing
End Get
End Property
Public ReadOnly Overloads Property P(o As Object) As Object
Get
Return Nothing
End Get
End Property
Public Overloads Property Q(o As Object) As Object
Get
Return Nothing
End Get
Set
End Set
End Property
Public Overloads Property Q() As Object
Get
Return Nothing
End Get
Set
End Set
End Property
End Class
";
var compA = CreateVisualBasicCompilation(sourceA);
compA.VerifyDiagnostics();
var refA = compA.EmitToImageReference();
var sourceB =
@"record B(object P, object Q) : A
{
}";
var compB = CreateCompilation(new[] { sourceB, IsExternalInitTypeDefinition }, references: new[] { refA }, parseOptions: TestOptions.Regular9);
compB.VerifyDiagnostics(
// (1,8): error CS0115: 'B.EqualityContract': no suitable method found to override
// record B(object P, object Q) : A
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.EqualityContract").WithLocation(1, 8),
// (1,8): error CS0115: 'B.Equals(A?)': no suitable method found to override
// record B(object P, object Q) : A
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.Equals(A?)").WithLocation(1, 8),
// (1,8): error CS0115: 'B.PrintMembers(StringBuilder)': no suitable method found to override
// record B(object P, object Q) : A
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)").WithLocation(1, 8),
// (1,8): error CS8867: No accessible copy constructor found in base type 'A'.
// record B(object P, object Q) : A
Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "B").WithArguments("A").WithLocation(1, 8),
// (1,17): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P, object Q) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(1, 17),
// (1,27): warning CS8907: Parameter 'Q' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P, object Q) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Q").WithArguments("Q").WithLocation(1, 27),
// (1,32): error CS8864: Records may only inherit from object or another record
// record B(object P, object Q) : A
Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(1, 32)
);
var actualMembers = GetProperties(compB, "B").ToTestDisplayStrings();
AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers);
}
[Fact]
public void Inheritance_31()
{
var sourceA =
@"Public Class A
Public ReadOnly Property P() As Object
Get
Return Nothing
End Get
End Property
Public Property Q(o As Object) As Object
Get
Return Nothing
End Get
Set
End Set
End Property
Public Property R(o As Object) As Object
Get
Return Nothing
End Get
Set
End Set
End Property
Public Sub New(a as A)
End Sub
End Class
Public Class B
Inherits A
Public ReadOnly Overloads Property P(o As Object) As Object
Get
Return Nothing
End Get
End Property
Public Overloads Property Q() As Object
Get
Return Nothing
End Get
Set
End Set
End Property
Public Overloads Property R(x As Object, y As Object) As Object
Get
Return Nothing
End Get
Set
End Set
End Property
Public Sub New(b as B)
MyBase.New(b)
End Sub
End Class
";
var compA = CreateVisualBasicCompilation(sourceA);
compA.VerifyDiagnostics();
var refA = compA.EmitToImageReference();
var sourceB =
@"record C(object P, object Q, object R) : B
{
}";
var compB = CreateCompilation(new[] { sourceB, IsExternalInitTypeDefinition }, references: new[] { refA }, parseOptions: TestOptions.Regular9);
compB.VerifyDiagnostics(
// (1,8): error CS0115: 'C.EqualityContract': no suitable method found to override
// record C(object P, object Q, object R) : B
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.EqualityContract").WithLocation(1, 8),
// (1,8): error CS0115: 'C.Equals(B?)': no suitable method found to override
// record C(object P, object Q, object R) : B
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.Equals(B?)").WithLocation(1, 8),
// (1,8): error CS0115: 'C.PrintMembers(StringBuilder)': no suitable method found to override
// record C(object P, object Q, object R) : B
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.PrintMembers(System.Text.StringBuilder)").WithLocation(1, 8),
// (1,8): error CS7036: There is no argument given that corresponds to the required formal parameter 'b' of 'B.B(B)'
// record C(object P, object Q, object R) : B
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("b", "B.B(B)").WithLocation(1, 8),
// (1,17): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P, object Q, object R) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(1, 17),
// (1,27): warning CS8907: Parameter 'Q' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P, object Q, object R) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Q").WithArguments("Q").WithLocation(1, 27),
// (1,42): error CS8864: Records may only inherit from object or another record
// record C(object P, object Q, object R) : B
Diagnostic(ErrorCode.ERR_BadRecordBase, "B").WithLocation(1, 42)
);
var actualMembers = GetProperties(compB, "C").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type C.EqualityContract { get; }",
"System.Object C.R { get; init; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void Inheritance_32()
{
var source =
@"record A
{
public virtual object P1 { get; }
public virtual object P2 { get; set; }
public virtual object P3 { get; protected init; }
public virtual object P4 { protected get; init; }
public virtual object P5 { init { } }
public virtual object P6 { set { } }
public static object P7 { get; set; }
}
record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A;
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (11,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A;
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(11, 17),
// (11,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A;
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(11, 28),
// (11,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A;
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(11, 39),
// (11,50): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A;
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(11, 50),
// (11,61): error CS8866: Record member 'A.P5' must be a readable instance property or field of type 'object' to match positional parameter 'P5'.
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A;
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P5").WithArguments("A.P5", "object", "P5").WithLocation(11, 61),
// (11,61): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A;
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(11, 61),
// (11,72): error CS8866: Record member 'A.P6' must be a readable instance property or field of type 'object' to match positional parameter 'P6'.
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A;
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P6").WithArguments("A.P6", "object", "P6").WithLocation(11, 72),
// (11,72): warning CS8907: Parameter 'P6' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A;
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P6").WithArguments("P6").WithLocation(11, 72),
// (11,83): error CS8866: Record member 'A.P7' must be a readable instance property or field of type 'object' to match positional parameter 'P7'.
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A;
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P7").WithArguments("A.P7", "object", "P7").WithLocation(11, 83),
// (11,83): warning CS8907: Parameter 'P7' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A;
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P7").WithArguments("P7").WithLocation(11, 83));
AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, GetProperties(comp, "B").ToTestDisplayStrings());
}
[WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")]
[Fact]
public void Inheritance_33()
{
var source =
@"abstract record A
{
public abstract object P1 { get; }
public abstract object P2 { get; set; }
public abstract object P3 { get; protected init; }
public abstract object P4 { protected get; init; }
public abstract object P5 { init; }
public abstract object P6 { set; }
}
record B(object P1, object P2, object P3, object P4, object P5, object P6) : A;
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (10,8): error CS0534: 'B' does not implement inherited abstract member 'A.P6.set'
// record B(object P1, object P2, object P3, object P4, object P5, object P6) : A;
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.P6.set").WithLocation(10, 8),
// (10,8): error CS0534: 'B' does not implement inherited abstract member 'A.P5.init'
// record B(object P1, object P2, object P3, object P4, object P5, object P6) : A;
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.P5.init").WithLocation(10, 8),
// (10,17): error CS0546: 'B.P1.init': cannot override because 'A.P1' does not have an overridable set accessor
// record B(object P1, object P2, object P3, object P4, object P5, object P6) : A;
Diagnostic(ErrorCode.ERR_NoSetToOverride, "P1").WithArguments("B.P1.init", "A.P1").WithLocation(10, 17),
// (10,28): error CS8853: 'B.P2' must match by init-only of overridden member 'A.P2'
// record B(object P1, object P2, object P3, object P4, object P5, object P6) : A;
Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "P2").WithArguments("B.P2", "A.P2").WithLocation(10, 28),
// (10,39): error CS0507: 'B.P3.init': cannot change access modifiers when overriding 'protected' inherited member 'A.P3.init'
// record B(object P1, object P2, object P3, object P4, object P5, object P6) : A;
Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "P3").WithArguments("B.P3.init", "protected", "A.P3.init").WithLocation(10, 39),
// (10,50): error CS0507: 'B.P4.get': cannot change access modifiers when overriding 'protected' inherited member 'A.P4.get'
// record B(object P1, object P2, object P3, object P4, object P5, object P6) : A;
Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "P4").WithArguments("B.P4.get", "protected", "A.P4.get").WithLocation(10, 50),
// (10,61): error CS8866: Record member 'A.P5' must be a readable instance property or field of type 'object' to match positional parameter 'P5'.
// record B(object P1, object P2, object P3, object P4, object P5, object P6) : A;
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P5").WithArguments("A.P5", "object", "P5").WithLocation(10, 61),
// (10,61): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6) : A;
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(10, 61),
// (10,72): error CS8866: Record member 'A.P6' must be a readable instance property or field of type 'object' to match positional parameter 'P6'.
// record B(object P1, object P2, object P3, object P4, object P5, object P6) : A;
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P6").WithArguments("A.P6", "object", "P6").WithLocation(10, 72),
// (10,72): warning CS8907: Parameter 'P6' is unread. Did you forget to use it to initialize the property with that name?
// record B(object P1, object P2, object P3, object P4, object P5, object P6) : A;
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P6").WithArguments("P6").WithLocation(10, 72));
var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type B.EqualityContract { get; }",
"System.Object B.P1 { get; init; }",
"System.Object B.P2 { get; init; }",
"System.Object B.P3 { get; init; }",
"System.Object B.P4 { get; init; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")]
[Fact]
public void Inheritance_34()
{
var source =
@"abstract record A
{
public abstract object P1 { get; init; }
public virtual object P2 { get; init; }
}
record B(string P1, string P2) : A;
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,8): error CS0534: 'B' does not implement inherited abstract member 'A.P1.init'
// record B(string P1, string P2) : A;
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.P1.init").WithLocation(6, 8),
// (6,8): error CS0534: 'B' does not implement inherited abstract member 'A.P1.get'
// record B(string P1, string P2) : A;
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.P1.get").WithLocation(6, 8),
// (6,17): error CS8866: Record member 'A.P1' must be a readable instance property or field of type 'string' to match positional parameter 'P1'.
// record B(string P1, string P2) : A;
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("A.P1", "string", "P1").WithLocation(6, 17),
// (6,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// record B(string P1, string P2) : A;
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(6, 17),
// (6,28): error CS8866: Record member 'A.P2' must be a readable instance property or field of type 'string' to match positional parameter 'P2'.
// record B(string P1, string P2) : A;
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P2").WithArguments("A.P2", "string", "P2").WithLocation(6, 28),
// (6,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name?
// record B(string P1, string P2) : A;
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(6, 28));
AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, GetProperties(comp, "B").ToTestDisplayStrings());
}
[WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")]
[Fact]
public void Inheritance_35()
{
var source =
@"using static System.Console;
abstract record A(object X, object Y)
{
public abstract object X { get; }
public abstract object Y { get; init; }
}
record B(object X, object Y) : A(X, Y)
{
public override object X { get; } = X;
}
class Program
{
static void Main()
{
B b = new B(1, 2);
A a = b;
WriteLine((b.X, b.Y));
WriteLine((a.X, a.Y));
var (x, y) = b;
WriteLine((x, y));
(x, y) = a;
WriteLine((x, y));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type B.EqualityContract { get; }",
"System.Object B.Y { get; init; }",
"System.Object B.X { get; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
var verifier = CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput:
@"(1, 2)
(1, 2)
(1, 2)
(1, 2)").VerifyDiagnostics(
// (2,26): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// abstract record A(object X, object Y)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 26),
// (2,36): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// abstract record A(object X, object Y)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(2, 36)
);
verifier.VerifyIL("A..ctor(object, object)",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ret
}");
verifier.VerifyIL("A..ctor(A)",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ret
}");
verifier.VerifyIL("A.Deconstruct",
@"{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: callvirt ""object A.X.get""
IL_0007: stind.ref
IL_0008: ldarg.2
IL_0009: ldarg.0
IL_000a: callvirt ""object A.Y.get""
IL_000f: stind.ref
IL_0010: ret
}");
verifier.VerifyIL("A.Equals(A)",
@"{
// Code size 29 (0x1d)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_001b
IL_0004: ldarg.1
IL_0005: brfalse.s IL_0019
IL_0007: ldarg.0
IL_0008: callvirt ""System.Type A.EqualityContract.get""
IL_000d: ldarg.1
IL_000e: callvirt ""System.Type A.EqualityContract.get""
IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)""
IL_0018: ret
IL_0019: ldc.i4.0
IL_001a: ret
IL_001b: ldc.i4.1
IL_001c: ret
}");
verifier.VerifyIL("A.GetHashCode()",
@"{
// Code size 17 (0x11)
.maxstack 2
IL_0000: call ""System.Collections.Generic.EqualityComparer<System.Type> System.Collections.Generic.EqualityComparer<System.Type>.Default.get""
IL_0005: ldarg.0
IL_0006: callvirt ""System.Type A.EqualityContract.get""
IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<System.Type>.GetHashCode(System.Type)""
IL_0010: ret
}");
verifier.VerifyIL("B..ctor(object, object)",
@"{
// Code size 23 (0x17)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.2
IL_0002: stfld ""object B.<Y>k__BackingField""
IL_0007: ldarg.0
IL_0008: ldarg.1
IL_0009: stfld ""object B.<X>k__BackingField""
IL_000e: ldarg.0
IL_000f: ldarg.1
IL_0010: ldarg.2
IL_0011: call ""A..ctor(object, object)""
IL_0016: ret
}");
verifier.VerifyIL("B..ctor(B)",
@"{
// Code size 32 (0x20)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""A..ctor(A)""
IL_0007: ldarg.0
IL_0008: ldarg.1
IL_0009: ldfld ""object B.<Y>k__BackingField""
IL_000e: stfld ""object B.<Y>k__BackingField""
IL_0013: ldarg.0
IL_0014: ldarg.1
IL_0015: ldfld ""object B.<X>k__BackingField""
IL_001a: stfld ""object B.<X>k__BackingField""
IL_001f: ret
}");
verifier.VerifyIL("B.Deconstruct",
@"{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: callvirt ""object A.X.get""
IL_0007: stind.ref
IL_0008: ldarg.2
IL_0009: ldarg.0
IL_000a: callvirt ""object A.Y.get""
IL_000f: stind.ref
IL_0010: ret
}");
verifier.VerifyIL("B.Equals(B)",
@"{
// Code size 64 (0x40)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_003e
IL_0004: ldarg.0
IL_0005: ldarg.1
IL_0006: call ""bool A.Equals(A)""
IL_000b: brfalse.s IL_003c
IL_000d: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get""
IL_0012: ldarg.0
IL_0013: ldfld ""object B.<Y>k__BackingField""
IL_0018: ldarg.1
IL_0019: ldfld ""object B.<Y>k__BackingField""
IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)""
IL_0023: brfalse.s IL_003c
IL_0025: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get""
IL_002a: ldarg.0
IL_002b: ldfld ""object B.<X>k__BackingField""
IL_0030: ldarg.1
IL_0031: ldfld ""object B.<X>k__BackingField""
IL_0036: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)""
IL_003b: ret
IL_003c: ldc.i4.0
IL_003d: ret
IL_003e: ldc.i4.1
IL_003f: ret
}");
verifier.VerifyIL("B.GetHashCode()",
@"{
// Code size 53 (0x35)
.maxstack 3
IL_0000: ldarg.0
IL_0001: call ""int A.GetHashCode()""
IL_0006: ldc.i4 0xa5555529
IL_000b: mul
IL_000c: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get""
IL_0011: ldarg.0
IL_0012: ldfld ""object B.<Y>k__BackingField""
IL_0017: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)""
IL_001c: add
IL_001d: ldc.i4 0xa5555529
IL_0022: mul
IL_0023: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get""
IL_0028: ldarg.0
IL_0029: ldfld ""object B.<X>k__BackingField""
IL_002e: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)""
IL_0033: add
IL_0034: ret
}");
}
[WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")]
[Fact]
public void Inheritance_36()
{
var source =
@"using static System.Console;
abstract record A
{
public abstract object X { get; init; }
}
abstract record B : A
{
public abstract object Y { get; init; }
}
record C(object X, object Y) : B;
class Program
{
static void Main()
{
C c = new C(1, 2);
B b = c;
A a = c;
WriteLine((c.X, c.Y));
WriteLine((b.X, b.Y));
WriteLine(a.X);
var (x, y) = c;
WriteLine((x, y));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type C.EqualityContract { get; }",
"System.Object C.X { get; init; }",
"System.Object C.Y { get; init; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
var verifier = CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput:
@"(1, 2)
(1, 2)
1
(1, 2)").VerifyDiagnostics();
verifier.VerifyIL("A..ctor()",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ret
}");
verifier.VerifyIL("A..ctor(A)",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ret
}");
verifier.VerifyIL("A.Equals(A)",
@"{
// Code size 29 (0x1d)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_001b
IL_0004: ldarg.1
IL_0005: brfalse.s IL_0019
IL_0007: ldarg.0
IL_0008: callvirt ""System.Type A.EqualityContract.get""
IL_000d: ldarg.1
IL_000e: callvirt ""System.Type A.EqualityContract.get""
IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)""
IL_0018: ret
IL_0019: ldc.i4.0
IL_001a: ret
IL_001b: ldc.i4.1
IL_001c: ret
}");
verifier.VerifyIL("A.GetHashCode()",
@"{
// Code size 17 (0x11)
.maxstack 2
IL_0000: call ""System.Collections.Generic.EqualityComparer<System.Type> System.Collections.Generic.EqualityComparer<System.Type>.Default.get""
IL_0005: ldarg.0
IL_0006: callvirt ""System.Type A.EqualityContract.get""
IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<System.Type>.GetHashCode(System.Type)""
IL_0010: ret
}");
verifier.VerifyIL("B..ctor()",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""A..ctor()""
IL_0006: ret
}");
verifier.VerifyIL("B..ctor(B)",
@"{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""A..ctor(A)""
IL_0007: ret
}");
verifier.VerifyIL("B.Equals(B)",
@"{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_000c
IL_0004: ldarg.0
IL_0005: ldarg.1
IL_0006: call ""bool A.Equals(A)""
IL_000b: ret
IL_000c: ldc.i4.1
IL_000d: ret
}");
verifier.VerifyIL("B.GetHashCode()",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""int A.GetHashCode()""
IL_0006: ret
}");
verifier.VerifyIL("C..ctor(object, object)",
@"{
// Code size 21 (0x15)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld ""object C.<X>k__BackingField""
IL_0007: ldarg.0
IL_0008: ldarg.2
IL_0009: stfld ""object C.<Y>k__BackingField""
IL_000e: ldarg.0
IL_000f: call ""B..ctor()""
IL_0014: ret
}");
verifier.VerifyIL("C..ctor(C)",
@"{
// Code size 32 (0x20)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""B..ctor(B)""
IL_0007: ldarg.0
IL_0008: ldarg.1
IL_0009: ldfld ""object C.<X>k__BackingField""
IL_000e: stfld ""object C.<X>k__BackingField""
IL_0013: ldarg.0
IL_0014: ldarg.1
IL_0015: ldfld ""object C.<Y>k__BackingField""
IL_001a: stfld ""object C.<Y>k__BackingField""
IL_001f: ret
}");
verifier.VerifyIL("C.Deconstruct",
@"{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: callvirt ""object A.X.get""
IL_0007: stind.ref
IL_0008: ldarg.2
IL_0009: ldarg.0
IL_000a: callvirt ""object B.Y.get""
IL_000f: stind.ref
IL_0010: ret
}");
verifier.VerifyIL("C.Equals(C)",
@"{
// Code size 64 (0x40)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_003e
IL_0004: ldarg.0
IL_0005: ldarg.1
IL_0006: call ""bool B.Equals(B)""
IL_000b: brfalse.s IL_003c
IL_000d: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get""
IL_0012: ldarg.0
IL_0013: ldfld ""object C.<X>k__BackingField""
IL_0018: ldarg.1
IL_0019: ldfld ""object C.<X>k__BackingField""
IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)""
IL_0023: brfalse.s IL_003c
IL_0025: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get""
IL_002a: ldarg.0
IL_002b: ldfld ""object C.<Y>k__BackingField""
IL_0030: ldarg.1
IL_0031: ldfld ""object C.<Y>k__BackingField""
IL_0036: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)""
IL_003b: ret
IL_003c: ldc.i4.0
IL_003d: ret
IL_003e: ldc.i4.1
IL_003f: ret
}");
verifier.VerifyIL("C.GetHashCode()",
@"{
// Code size 53 (0x35)
.maxstack 3
IL_0000: ldarg.0
IL_0001: call ""int B.GetHashCode()""
IL_0006: ldc.i4 0xa5555529
IL_000b: mul
IL_000c: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get""
IL_0011: ldarg.0
IL_0012: ldfld ""object C.<X>k__BackingField""
IL_0017: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)""
IL_001c: add
IL_001d: ldc.i4 0xa5555529
IL_0022: mul
IL_0023: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get""
IL_0028: ldarg.0
IL_0029: ldfld ""object C.<Y>k__BackingField""
IL_002e: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)""
IL_0033: add
IL_0034: ret
}");
}
[WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")]
[Fact]
public void Inheritance_37()
{
var source =
@"using static System.Console;
abstract record A(object X, object Y)
{
public abstract object X { get; init; }
public virtual object Y { get; init; }
}
abstract record B(object X, object Y) : A(X, Y)
{
public override abstract object X { get; init; }
public override abstract object Y { get; init; }
}
record C(object X, object Y) : B(X, Y);
class Program
{
static void Main()
{
C c = new C(1, 2);
B b = c;
A a = c;
WriteLine((c.X, c.Y));
WriteLine((b.X, b.Y));
WriteLine((a.X, a.Y));
var (x, y) = c;
WriteLine((x, y));
(x, y) = b;
WriteLine((x, y));
(x, y) = a;
WriteLine((x, y));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type C.EqualityContract { get; }",
"System.Object C.X { get; init; }",
"System.Object C.Y { get; init; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
var verifier = CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput:
@"(1, 2)
(1, 2)
(1, 2)
(1, 2)
(1, 2)
(1, 2)").VerifyDiagnostics(
// (2,26): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// abstract record A(object X, object Y)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 26),
// (2,36): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// abstract record A(object X, object Y)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(2, 36)
);
verifier.VerifyIL("A..ctor(object, object)",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ret
}");
verifier.VerifyIL("A..ctor(A)",
@"{
// Code size 19 (0x13)
.maxstack 2
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ldarg.0
IL_0007: ldarg.1
IL_0008: ldfld ""object A.<Y>k__BackingField""
IL_000d: stfld ""object A.<Y>k__BackingField""
IL_0012: ret
}");
verifier.VerifyIL("A.Deconstruct",
@"{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: callvirt ""object A.X.get""
IL_0007: stind.ref
IL_0008: ldarg.2
IL_0009: ldarg.0
IL_000a: callvirt ""object A.Y.get""
IL_000f: stind.ref
IL_0010: ret
}");
verifier.VerifyIL("A.Equals(A)",
@"{
// Code size 53 (0x35)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_0033
IL_0004: ldarg.1
IL_0005: brfalse.s IL_0031
IL_0007: ldarg.0
IL_0008: callvirt ""System.Type A.EqualityContract.get""
IL_000d: ldarg.1
IL_000e: callvirt ""System.Type A.EqualityContract.get""
IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)""
IL_0018: brfalse.s IL_0031
IL_001a: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get""
IL_001f: ldarg.0
IL_0020: ldfld ""object A.<Y>k__BackingField""
IL_0025: ldarg.1
IL_0026: ldfld ""object A.<Y>k__BackingField""
IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)""
IL_0030: ret
IL_0031: ldc.i4.0
IL_0032: ret
IL_0033: ldc.i4.1
IL_0034: ret
}");
verifier.VerifyIL("A.GetHashCode()",
@"{
// Code size 40 (0x28)
.maxstack 3
IL_0000: call ""System.Collections.Generic.EqualityComparer<System.Type> System.Collections.Generic.EqualityComparer<System.Type>.Default.get""
IL_0005: ldarg.0
IL_0006: callvirt ""System.Type A.EqualityContract.get""
IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<System.Type>.GetHashCode(System.Type)""
IL_0010: ldc.i4 0xa5555529
IL_0015: mul
IL_0016: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get""
IL_001b: ldarg.0
IL_001c: ldfld ""object A.<Y>k__BackingField""
IL_0021: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)""
IL_0026: add
IL_0027: ret
}");
verifier.VerifyIL("B..ctor(object, object)",
@"{
// Code size 9 (0x9)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: ldarg.2
IL_0003: call ""A..ctor(object, object)""
IL_0008: ret
}");
verifier.VerifyIL("B..ctor(B)",
@"{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""A..ctor(A)""
IL_0007: ret
}");
verifier.VerifyIL("B.Deconstruct",
@"{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: callvirt ""object A.X.get""
IL_0007: stind.ref
IL_0008: ldarg.2
IL_0009: ldarg.0
IL_000a: callvirt ""object A.Y.get""
IL_000f: stind.ref
IL_0010: ret
}");
verifier.VerifyIL("B.Equals(B)",
@"{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_000c
IL_0004: ldarg.0
IL_0005: ldarg.1
IL_0006: call ""bool A.Equals(A)""
IL_000b: ret
IL_000c: ldc.i4.1
IL_000d: ret
}");
verifier.VerifyIL("B.GetHashCode()",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""int A.GetHashCode()""
IL_0006: ret
}");
verifier.VerifyIL("C..ctor(object, object)",
@"{
// Code size 23 (0x17)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld ""object C.<X>k__BackingField""
IL_0007: ldarg.0
IL_0008: ldarg.2
IL_0009: stfld ""object C.<Y>k__BackingField""
IL_000e: ldarg.0
IL_000f: ldarg.1
IL_0010: ldarg.2
IL_0011: call ""B..ctor(object, object)""
IL_0016: ret
}");
verifier.VerifyIL("C..ctor(C)",
@"{
// Code size 32 (0x20)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""B..ctor(B)""
IL_0007: ldarg.0
IL_0008: ldarg.1
IL_0009: ldfld ""object C.<X>k__BackingField""
IL_000e: stfld ""object C.<X>k__BackingField""
IL_0013: ldarg.0
IL_0014: ldarg.1
IL_0015: ldfld ""object C.<Y>k__BackingField""
IL_001a: stfld ""object C.<Y>k__BackingField""
IL_001f: ret
}");
verifier.VerifyIL("C.Deconstruct",
@"{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: callvirt ""object A.X.get""
IL_0007: stind.ref
IL_0008: ldarg.2
IL_0009: ldarg.0
IL_000a: callvirt ""object A.Y.get""
IL_000f: stind.ref
IL_0010: ret
}");
verifier.VerifyIL("C.Equals(C)",
@"{
// Code size 64 (0x40)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_003e
IL_0004: ldarg.0
IL_0005: ldarg.1
IL_0006: call ""bool B.Equals(B)""
IL_000b: brfalse.s IL_003c
IL_000d: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get""
IL_0012: ldarg.0
IL_0013: ldfld ""object C.<X>k__BackingField""
IL_0018: ldarg.1
IL_0019: ldfld ""object C.<X>k__BackingField""
IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)""
IL_0023: brfalse.s IL_003c
IL_0025: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get""
IL_002a: ldarg.0
IL_002b: ldfld ""object C.<Y>k__BackingField""
IL_0030: ldarg.1
IL_0031: ldfld ""object C.<Y>k__BackingField""
IL_0036: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)""
IL_003b: ret
IL_003c: ldc.i4.0
IL_003d: ret
IL_003e: ldc.i4.1
IL_003f: ret
}");
verifier.VerifyIL("C.GetHashCode()",
@"{
// Code size 53 (0x35)
.maxstack 3
IL_0000: ldarg.0
IL_0001: call ""int B.GetHashCode()""
IL_0006: ldc.i4 0xa5555529
IL_000b: mul
IL_000c: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get""
IL_0011: ldarg.0
IL_0012: ldfld ""object C.<X>k__BackingField""
IL_0017: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)""
IL_001c: add
IL_001d: ldc.i4 0xa5555529
IL_0022: mul
IL_0023: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get""
IL_0028: ldarg.0
IL_0029: ldfld ""object C.<Y>k__BackingField""
IL_002e: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)""
IL_0033: add
IL_0034: ret
}");
}
// Member in intermediate base that hides abstract property. Not supported.
[WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")]
[Fact]
public void Inheritance_38()
{
var source =
@"using static System.Console;
abstract record A
{
public abstract object X { get; init; }
public abstract object Y { get; init; }
}
abstract record B : A
{
public new void X() { }
public new struct Y { }
}
record C(object X, object Y) : B;
class Program
{
static void Main()
{
C c = new C(1, 2);
A a = c;
WriteLine((a.X, a.Y));
var (x, y) = c;
WriteLine((x, y));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics(
// (9,21): error CS0533: 'B.X()' hides inherited abstract member 'A.X'
// public new void X() { }
Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "X").WithArguments("B.X()", "A.X").WithLocation(9, 21),
// (10,23): error CS0533: 'B.Y' hides inherited abstract member 'A.Y'
// public new struct Y { }
Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "Y").WithArguments("B.Y", "A.Y").WithLocation(10, 23),
// (12,8): error CS0534: 'C' does not implement inherited abstract member 'A.Y.get'
// record C(object X, object Y) : B;
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "C").WithArguments("C", "A.Y.get").WithLocation(12, 8),
// (12,8): error CS0534: 'C' does not implement inherited abstract member 'A.X.get'
// record C(object X, object Y) : B;
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "C").WithArguments("C", "A.X.get").WithLocation(12, 8),
// (12,8): error CS0534: 'C' does not implement inherited abstract member 'A.X.init'
// record C(object X, object Y) : B;
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "C").WithArguments("C", "A.X.init").WithLocation(12, 8),
// (12,8): error CS0534: 'C' does not implement inherited abstract member 'A.Y.init'
// record C(object X, object Y) : B;
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "C").WithArguments("C", "A.Y.init").WithLocation(12, 8),
// (12,17): error CS8866: Record member 'B.X' must be a readable instance property or field of type 'object' to match positional parameter 'X'.
// record C(object X, object Y) : B;
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("B.X", "object", "X").WithLocation(12, 17),
// (12,17): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record C(object X, object Y) : B;
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(12, 17),
// (12,27): error CS8866: Record member 'B.Y' must be a readable instance property or field of type 'object' to match positional parameter 'Y'.
// record C(object X, object Y) : B;
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Y").WithArguments("B.Y", "object", "Y").WithLocation(12, 27),
// (12,27): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// record C(object X, object Y) : B;
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(12, 27));
AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }", }, GetProperties(comp, "C").ToTestDisplayStrings());
}
// Member in intermediate base that hides abstract property. Not supported.
[WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")]
[Fact]
public void Inheritance_39()
{
var sourceA =
@".class public System.Runtime.CompilerServices.IsExternalInit
{
.method public hidebysig specialname rtspecialname instance void .ctor() { ldnull throw }
}
.class public abstract A
{
.method family hidebysig specialname rtspecialname instance void .ctor()
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.method family hidebysig specialname rtspecialname instance void .ctor(class A A_1) { ldnull throw }
.method public hidebysig newslot specialname abstract virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { }
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.property instance object P()
{
.get instance object A::get_P()
.set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) A::set_P(object)
}
.method family virtual instance class [mscorlib]System.Type get_EqualityContract() { ldnull ret }
.method public abstract virtual instance object get_P() { }
.method public abstract virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(object 'value') { }
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}
.class public abstract B extends A
{
.method family hidebysig specialname rtspecialname instance void .ctor()
{
ldarg.0
call instance void A::.ctor()
ret
}
.method family hidebysig specialname rtspecialname instance void .ctor(class B A_1) { ldnull throw }
.method public hidebysig specialname abstract virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { }
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type B::get_EqualityContract()
}
.method family virtual instance class [mscorlib]System.Type get_EqualityContract() { ldnull ret }
.method public hidebysig instance object P() { ldnull ret }
.method public newslot virtual
instance bool Equals (
class B ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method B::Equals
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}";
var refA = CompileIL(sourceA);
var sourceB =
@"record CA(object P) : A;
record CB(object P) : B;
";
var comp = CreateCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (2,8): error CS0534: 'CB' does not implement inherited abstract member 'A.P.get'
// record CB(object P) : B;
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "CB").WithArguments("CB", "A.P.get").WithLocation(2, 8),
// (2,8): error CS0534: 'CB' does not implement inherited abstract member 'A.P.init'
// record CB(object P) : B;
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "CB").WithArguments("CB", "A.P.init").WithLocation(2, 8),
// (2,18): error CS8866: Record member 'B.P' must be a readable instance property or field of type 'object' to match positional parameter 'P'.
// record CB(object P) : B;
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("B.P", "object", "P").WithLocation(2, 18),
// (2,18): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name?
// record CB(object P) : B;
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 18));
AssertEx.Equal(new[] { "System.Type CA.EqualityContract { get; }", "System.Object CA.P { get; init; }" }, GetProperties(comp, "CA").ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.Type CB.EqualityContract { get; }" }, GetProperties(comp, "CB").ToTestDisplayStrings());
}
// Accessor names that do not match the property name.
[WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")]
[Fact]
public void Inheritance_40()
{
var sourceA =
@".class public System.Runtime.CompilerServices.IsExternalInit
{
.method public hidebysig specialname rtspecialname instance void .ctor() { ldnull throw }
}
.class public abstract A
{
.method family hidebysig specialname rtspecialname instance void .ctor()
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.method family hidebysig specialname rtspecialname instance void .ctor(class A A_1) { ldnull throw }
.method public hidebysig newslot specialname abstract virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { }
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::GetProperty1()
}
.property instance object P()
{
.get instance object A::GetProperty2()
.set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) A::SetProperty2(object)
}
.method family virtual instance class [mscorlib]System.Type GetProperty1() { ldnull ret }
.method public abstract virtual instance object GetProperty2() { }
.method public abstract virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) SetProperty2(object 'value') { }
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}";
var refA = CompileIL(sourceA);
var sourceB =
@"using static System.Console;
record B(object P) : A
{
static void Main()
{
B b = new B(3);
WriteLine(b.P);
WriteLine(((A)b).P);
b = new B(1) { P = 2 };
WriteLine(b.P);
WriteLine(b.EqualityContract.Name);
}
}";
var comp = CreateCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput:
@"3
3
2
B").VerifyDiagnostics();
var actualMembers = GetProperties(comp, "B");
Assert.Equal(2, actualMembers.Length);
VerifyProperty(actualMembers[0], "System.Type B.EqualityContract { get; }", "GetProperty1", null);
VerifyProperty(actualMembers[1], "System.Object B.P { get; init; }", "GetProperty2", "SetProperty2");
}
// Accessor names that do not match the property name and are not valid C# names.
[WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")]
[Fact]
public void Inheritance_41()
{
var sourceA =
@".class public System.Runtime.CompilerServices.IsExternalInit
{
.method public hidebysig specialname rtspecialname instance void .ctor() { ldnull throw }
}
.class public abstract A
{
.method family hidebysig specialname rtspecialname instance void .ctor()
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.method family hidebysig specialname rtspecialname instance void .ctor(class A A_1) { ldnull throw }
.method public hidebysig newslot specialname abstract virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { }
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::'EqualityContract<>get'()
}
.property instance object P()
{
.get instance object A::'P<>get'()
.set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) A::'P<>set'(object)
}
.method family virtual instance class [mscorlib]System.Type 'EqualityContract<>get'() { ldnull ret }
.method public abstract virtual instance object 'P<>get'() { }
.method public abstract virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) 'P<>set'(object 'value') { }
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}";
var refA = CompileIL(sourceA);
var sourceB =
@"using static System.Console;
record B(object P) : A
{
static void Main()
{
B b = new B(3);
WriteLine(b.P);
WriteLine(((A)b).P);
b = new B(1) { P = 2 };
WriteLine(b.P);
WriteLine(b.EqualityContract.Name);
}
}";
var comp = CreateCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput:
@"3
3
2
B").VerifyDiagnostics();
var actualMembers = GetProperties(comp, "B");
Assert.Equal(2, actualMembers.Length);
VerifyProperty(actualMembers[0], "System.Type B.EqualityContract { get; }", "EqualityContract<>get", null);
VerifyProperty(actualMembers[1], "System.Object B.P { get; init; }", "P<>get", "P<>set");
}
private static void VerifyProperty(Symbol symbol, string propertyDescription, string? getterName, string? setterName)
{
var property = (PropertySymbol)symbol;
Assert.Equal(propertyDescription, symbol.ToTestDisplayString());
VerifyAccessor(property.GetMethod, getterName);
VerifyAccessor(property.SetMethod, setterName);
}
private static void VerifyAccessor(MethodSymbol? accessor, string? name)
{
Assert.Equal(name, accessor?.Name);
if (accessor is object)
{
Assert.True(accessor.HasSpecialName);
foreach (var parameter in accessor.Parameters)
{
Assert.Same(accessor, parameter.ContainingSymbol);
}
}
}
[WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")]
[Fact]
public void Inheritance_42()
{
var sourceA =
@".class public System.Runtime.CompilerServices.IsExternalInit
{
.method public hidebysig specialname rtspecialname instance void .ctor() { ldnull throw }
}
.class public abstract A
{
.method family hidebysig specialname rtspecialname instance void .ctor()
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.method family hidebysig specialname rtspecialname instance void .ctor(class A A_1) { ldnull throw }
.method public hidebysig newslot specialname abstract virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { }
.property instance class [mscorlib]System.Type modopt(int32) EqualityContract()
{
.get instance class [mscorlib]System.Type modopt(int32) A::get_EqualityContract()
}
.property instance object modopt(uint16) P()
{
.get instance object modopt(uint16) A::get_P()
.set instance void modopt(uint8) modreq(System.Runtime.CompilerServices.IsExternalInit) A::set_P(object modopt(uint16))
}
.method family virtual instance class [mscorlib]System.Type modopt(int32) get_EqualityContract() { ldnull ret }
.method public abstract virtual instance object modopt(uint16) get_P() { }
.method public abstract virtual instance void modopt(uint8) modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(object modopt(uint16) 'value') { }
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance string ToString () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}";
var refA = CompileIL(sourceA);
var sourceB =
@"using static System.Console;
record B(object P) : A
{
static void Main()
{
B b = new B(3);
WriteLine(b.P);
WriteLine(((A)b).P);
b = new B(1) { P = 2 };
WriteLine(b.P);
WriteLine(b.EqualityContract.Name);
}
}";
var comp = CreateCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput:
@"3
3
2
B").VerifyDiagnostics();
var actualMembers = GetProperties(comp, "B");
Assert.Equal(2, actualMembers.Length);
var property = (PropertySymbol)actualMembers[0];
Assert.Equal("System.Type modopt(System.Int32) B.EqualityContract { get; }", property.ToTestDisplayString());
verifyReturnType(property.GetMethod, CSharpCustomModifier.CreateOptional(comp.GetSpecialType(SpecialType.System_Int32)));
property = (PropertySymbol)actualMembers[1];
Assert.Equal("System.Object modopt(System.UInt16) B.P { get; init; }", property.ToTestDisplayString());
verifyReturnType(property.GetMethod,
CSharpCustomModifier.CreateOptional(comp.GetSpecialType(SpecialType.System_UInt16)));
verifyReturnType(property.SetMethod,
CSharpCustomModifier.CreateRequired(comp.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_IsExternalInit)),
CSharpCustomModifier.CreateOptional(comp.GetSpecialType(SpecialType.System_Byte)));
verifyParameterType(property.SetMethod,
CSharpCustomModifier.CreateOptional(comp.GetSpecialType(SpecialType.System_UInt16)));
static void verifyReturnType(MethodSymbol method, params CustomModifier[] expectedModifiers)
{
var returnType = method.ReturnTypeWithAnnotations;
Assert.True(method.OverriddenMethod.ReturnTypeWithAnnotations.Equals(returnType, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes));
AssertEx.Equal(expectedModifiers, returnType.CustomModifiers);
}
static void verifyParameterType(MethodSymbol method, params CustomModifier[] expectedModifiers)
{
var parameterType = method.Parameters[0].TypeWithAnnotations;
Assert.True(method.OverriddenMethod.Parameters[0].TypeWithAnnotations.Equals(parameterType, TypeCompareKind.ConsiderEverything));
AssertEx.Equal(expectedModifiers, parameterType.CustomModifiers);
}
}
[WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")]
[Fact]
public void Inheritance_43()
{
var source =
@"#nullable enable
record A
{
protected virtual System.Type? EqualityContract => null;
}
record B : A
{
static void Main()
{
var b = new B();
_ = b.EqualityContract.ToString();
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
Assert.Equal("System.Type! B.EqualityContract { get; }", GetProperties(comp, "B").Single().ToTestDisplayString(includeNonNullable: true));
}
// No EqualityContract property on base.
[Fact]
public void Inheritance_44()
{
var sourceA =
@".class public System.Runtime.CompilerServices.IsExternalInit
{
.method public hidebysig specialname rtspecialname instance void .ctor() { ldnull throw }
}
.class public A
{
.method family hidebysig specialname rtspecialname instance void .ctor()
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.method family hidebysig specialname rtspecialname instance void .ctor(class A A_1) { ldnull throw }
.method public hidebysig newslot specialname virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { ldnull throw }
.property instance object P()
{
.get instance object A::get_P()
.set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) A::set_P(object)
}
.method public instance object get_P() { ldnull ret }
.method public instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(object 'value') { ret }
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}";
var refA = CompileIL(sourceA);
var sourceB =
@"record B : A;
";
var comp = CreateCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (1,8): error CS0115: 'B.EqualityContract': no suitable method found to override
// record B : A;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.EqualityContract").WithLocation(1, 8));
AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, GetProperties(comp, "B").ToTestDisplayStrings());
}
[Theory, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
[InlineData(false)]
[InlineData(true)]
public void CopyCtor(bool useCompilationReference)
{
var sourceA =
@"public record B(object N1, object N2)
{
}";
var compA = CreateCompilation(RuntimeUtilities.IsCoreClrRuntime ? sourceA : new[] { sourceA, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.StandardLatest);
var verifierA = CompileAndVerify(compA, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics();
verifierA.VerifyIL("B..ctor(B)", @"
{
// Code size 31 (0x1f)
.maxstack 2
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ldarg.0
IL_0007: ldarg.1
IL_0008: ldfld ""object B.<N1>k__BackingField""
IL_000d: stfld ""object B.<N1>k__BackingField""
IL_0012: ldarg.0
IL_0013: ldarg.1
IL_0014: ldfld ""object B.<N2>k__BackingField""
IL_0019: stfld ""object B.<N2>k__BackingField""
IL_001e: ret
}");
var refA = useCompilationReference ? compA.ToMetadataReference() : compA.EmitToImageReference();
var sourceB =
@"record C(object P1, object P2) : B(3, 4)
{
static void Main()
{
var c1 = new C(1, 2);
System.Console.Write((c1.P1, c1.P2, c1.N1, c1.N2));
System.Console.Write("" "");
var c2 = new C(c1);
System.Console.Write((c2.P1, c2.P2, c2.N1, c2.N2));
System.Console.Write("" "");
var c3 = c1 with { P1 = 10, N1 = 30 };
System.Console.Write((c3.P1, c3.P2, c3.N1, c3.N2));
}
}";
var compB = CreateCompilation(RuntimeUtilities.IsCoreClrRuntime ? sourceB : new[] { sourceB, IsExternalInitTypeDefinition }, references: new[] { refA }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, targetFramework: TargetFramework.StandardLatest);
var verifierB = CompileAndVerify(compB, expectedOutput: "(1, 2, 3, 4) (1, 2, 3, 4) (10, 2, 30, 4)", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics();
// call base copy constructor B..ctor(B)
verifierB.VerifyIL("C..ctor(C)", @"
{
// Code size 32 (0x20)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""B..ctor(B)""
IL_0007: ldarg.0
IL_0008: ldarg.1
IL_0009: ldfld ""object C.<P1>k__BackingField""
IL_000e: stfld ""object C.<P1>k__BackingField""
IL_0013: ldarg.0
IL_0014: ldarg.1
IL_0015: ldfld ""object C.<P2>k__BackingField""
IL_001a: stfld ""object C.<P2>k__BackingField""
IL_001f: ret
}");
verifierA.VerifyIL($"B.{WellKnownMemberNames.CloneMethodName}()", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: newobj ""B..ctor(B)""
IL_0006: ret
}");
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_WithOtherOverload()
{
var source =
@"public record B(object N1, object N2)
{
public B(C c) : this(30, 40) => throw null;
}
public record C(object P1, object P2) : B(3, 4)
{
static void Main()
{
var c1 = new C(1, 2);
System.Console.Write((c1.P1, c1.P2, c1.N1, c1.N2));
System.Console.Write("" "");
var c2 = c1 with { P1 = 10, P2 = 20, N1 = 30, N2 = 40 };
System.Console.Write((c2.P1, c2.P2, c2.N1, c2.N2));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
var verifier = CompileAndVerify(comp, expectedOutput: "(1, 2, 3, 4) (10, 20, 30, 40)", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics();
// call base copy constructor B..ctor(B)
verifier.VerifyIL("C..ctor(C)", @"
{
// Code size 32 (0x20)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""B..ctor(B)""
IL_0007: ldarg.0
IL_0008: ldarg.1
IL_0009: ldfld ""object C.<P1>k__BackingField""
IL_000e: stfld ""object C.<P1>k__BackingField""
IL_0013: ldarg.0
IL_0014: ldarg.1
IL_0015: ldfld ""object C.<P2>k__BackingField""
IL_001a: stfld ""object C.<P2>k__BackingField""
IL_001f: ret
}");
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_WithObsoleteCopyConstructor()
{
var source =
@"public record B(object N1, object N2)
{
[System.Obsolete(""Obsolete"", true)]
public B(B b) { }
}
public record C(object P1, object P2) : B(3, 4) { }
";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_WithParamsCopyConstructor()
{
var source =
@"public record B(object N1, object N2)
{
public B(B b, params int[] i) : this(30, 40) { }
}
public record C(object P1, object P2) : B(3, 4) { }
";
var comp = CreateCompilation(source);
var actualMembers = comp.GetMember<NamedTypeSymbol>("B").GetMembers().Where(m => m.Name == ".ctor").ToTestDisplayStrings();
var expectedMembers = new[]
{
"B..ctor(System.Object N1, System.Object N2)",
"B..ctor(B b, params System.Int32[] i)",
"B..ctor(B original)"
};
AssertEx.Equal(expectedMembers, actualMembers);
var verifier = CompileAndVerify(comp, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics();
verifier.VerifyIL("C..ctor(C)", @"
{
// Code size 32 (0x20)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""B..ctor(B)""
IL_0007: ldarg.0
IL_0008: ldarg.1
IL_0009: ldfld ""object C.<P1>k__BackingField""
IL_000e: stfld ""object C.<P1>k__BackingField""
IL_0013: ldarg.0
IL_0014: ldarg.1
IL_0015: ldfld ""object C.<P2>k__BackingField""
IL_001a: stfld ""object C.<P2>k__BackingField""
IL_001f: ret
}
");
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_WithInitializers()
{
var source =
@"public record C(object N1, object N2)
{
private int field = 42;
public int Property = 43;
}";
var comp = CreateCompilation(source);
var verifier = CompileAndVerify(comp, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(
// (3,17): warning CS0414: The field 'C.field' is assigned but its value is never used
// private int field = 42;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field").WithArguments("C.field").WithLocation(3, 17)
);
verifier.VerifyIL("C..ctor(C)", @"
{
// Code size 55 (0x37)
.maxstack 2
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ldarg.0
IL_0007: ldarg.1
IL_0008: ldfld ""object C.<N1>k__BackingField""
IL_000d: stfld ""object C.<N1>k__BackingField""
IL_0012: ldarg.0
IL_0013: ldarg.1
IL_0014: ldfld ""object C.<N2>k__BackingField""
IL_0019: stfld ""object C.<N2>k__BackingField""
IL_001e: ldarg.0
IL_001f: ldarg.1
IL_0020: ldfld ""int C.field""
IL_0025: stfld ""int C.field""
IL_002a: ldarg.0
IL_002b: ldarg.1
IL_002c: ldfld ""int C.Property""
IL_0031: stfld ""int C.Property""
IL_0036: ret
}");
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_NotInRecordType()
{
var source =
@"public class C
{
public object Property { get; set; }
public int field = 42;
public C(C c)
{
}
}
public class D : C
{
public int field2 = 43;
public D(D d) : base(d)
{
}
}
";
var comp = CreateCompilation(source);
var verifier = CompileAndVerify(comp).VerifyDiagnostics();
verifier.VerifyIL("C..ctor(C)", @"
{
// Code size 15 (0xf)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 42
IL_0003: stfld ""int C.field""
IL_0008: ldarg.0
IL_0009: call ""object..ctor()""
IL_000e: ret
}");
verifier.VerifyIL("D..ctor(D)", @"
{
// Code size 16 (0x10)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 43
IL_0003: stfld ""int D.field2""
IL_0008: ldarg.0
IL_0009: ldarg.1
IL_000a: call ""C..ctor(C)""
IL_000f: ret
}");
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor()
{
var source =
@"public record B(object N1, object N2)
{
}
public record C(object P1, object P2) : B(0, 1)
{
public C(C c) // 1, 2
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,12): error CS1729: 'B' does not contain a constructor that takes 0 arguments
// public C(C c) // 1, 2
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("B", "0").WithLocation(6, 12),
// (6,12): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object.
// public C(C c) // 1, 2
Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "C").WithLocation(6, 12)
);
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_DerivesFromObject()
{
var source =
@"public record C(int I)
{
public int I { get; set; } = 42;
public C(C c)
{
}
public static void Main()
{
var c = new C(1);
c.I = 2;
var c2 = new C(c);
System.Console.Write((c.I, c2.I));
}
}
";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
var verifier = CompileAndVerify(comp, expectedOutput: "(2, 0)").VerifyDiagnostics(
// (1,21): warning CS8907: Parameter 'I' is unread. Did you forget to use it to initialize the property with that name?
// public record C(int I)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "I").WithArguments("I").WithLocation(1, 21)
);
verifier.VerifyIL("C..ctor(C)", @"
{
// Code size 9 (0x9)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: nop
IL_0007: nop
IL_0008: ret
}
");
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_DerivesFromObject_WithFieldInitializer()
{
var source =
@"public record C(int I)
{
public int I { get; set; } = 42;
public int field = 43;
public C(C c)
{
System.Console.Write("" RAN "");
}
public static void Main()
{
var c = new C(1);
c.I = 2;
c.field = 100;
System.Console.Write((c.I, c.field));
var c2 = new C(c);
System.Console.Write((c2.I, c2.field));
}
}
";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
var verifier = CompileAndVerify(comp, expectedOutput: "(2, 100) RAN (0, 0)").VerifyDiagnostics(
// (1,21): warning CS8907: Parameter 'I' is unread. Did you forget to use it to initialize the property with that name?
// public record C(int I)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "I").WithArguments("I").WithLocation(1, 21)
);
verifier.VerifyIL("C..ctor(C)", @"
{
// Code size 20 (0x14)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: nop
IL_0007: nop
IL_0008: ldstr "" RAN ""
IL_000d: call ""void System.Console.Write(string)""
IL_0012: nop
IL_0013: ret
}
");
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_DerivesFromObject_GivesParameterToBase()
{
var source = @"
public record C(object I)
{
public C(C c) : base(1) { }
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,21): error CS1729: 'object' does not contain a constructor that takes 1 arguments
// public C(C c) : base(1) { }
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "base").WithArguments("object", "1").WithLocation(4, 21),
// (4,21): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object.
// public C(C c) : base(1) { }
Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "base").WithLocation(4, 21)
);
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_DerivesFromObject_WithSomeOtherConstructor()
{
var source = @"
public record C(object I)
{
public C(int i) : this((object)null) { }
public static void Main()
{
var c = new C((object)null);
var c2 = new C(1);
var c3 = new C(c);
System.Console.Write(""RAN"");
}
}
";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
var verifier = CompileAndVerify(comp, expectedOutput: "RAN", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics();
verifier.VerifyIL("C..ctor(int)", @"
{
// Code size 10 (0xa)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldnull
IL_0002: call ""C..ctor(object)""
IL_0007: nop
IL_0008: nop
IL_0009: ret
}
");
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_DerivesFromObject_UsesThis()
{
var source =
@"public record C(int I)
{
public C(C c) : this(c.I)
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (3,21): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object.
// public C(C c) : this(c.I)
Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "this").WithLocation(3, 21)
);
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_UserDefined_DerivesFromObject_UsesBase()
{
var source =
@"public record C(int I)
{
public C(C c) : base()
{
System.Console.Write(""RAN "");
}
public static void Main()
{
var c = new C(1);
System.Console.Write(c.I);
System.Console.Write("" "");
var c2 = c with { I = 2 };
System.Console.Write(c2.I);
}
}
";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
var verifier = CompileAndVerify(comp, expectedOutput: "1 RAN 2", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics();
verifier.VerifyIL("C..ctor(C)", @"
{
// Code size 20 (0x14)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: nop
IL_0007: nop
IL_0008: ldstr ""RAN ""
IL_000d: call ""void System.Console.Write(string)""
IL_0012: nop
IL_0013: ret
}
");
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_NoPositionalMembers()
{
var source =
@"public record B(object N1, object N2)
{
}
public record C(object P1) : B(0, 1)
{
public C(C c) // 1, 2
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,12): error CS1729: 'B' does not contain a constructor that takes 0 arguments
// public C(C c) // 1, 2
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("B", "0").WithLocation(6, 12),
// (6,12): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object.
// public C(C c) // 1, 2
Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "C").WithLocation(6, 12)
);
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_UsesThis()
{
var source =
@"public record B(object N1, object N2)
{
}
public record C(object P1, object P2) : B(0, 1)
{
public C(C c) : this(1, 2) // 1
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,21): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object.
// public C(C c) : this(1, 2) // 1
Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "this").WithLocation(6, 21)
);
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_UsesBase()
{
var source =
@"public record B(int i)
{
}
public record C(int j) : B(0)
{
public C(C c) : base(1) // 1
{
}
}
#nullable enable
public record D(int j) : B(0)
{
public D(D? d) : base(1) // 2
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,21): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object.
// public C(C c) : base(1) // 1
Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "base").WithLocation(6, 21),
// (13,22): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object.
// public D(D? d) : base(1) // 2
Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "base").WithLocation(13, 22)
);
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_UserDefined_WithFieldInitializers()
{
var source =
@"public record C(int I)
{
}
public record D(int J) : C(1)
{
public int field = 42;
public D(D d) : base(d)
{
System.Console.Write(""RAN "");
}
public static void Main()
{
var d = new D(2);
System.Console.Write((d.I, d.J, d.field));
System.Console.Write("" "");
var d2 = d with { I = 10, J = 20 };
System.Console.Write((d2.I, d2.J, d.field));
}
}
";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
var verifier = CompileAndVerify(comp, expectedOutput: "(1, 2, 42) RAN (10, 20, 42)", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics();
verifier.VerifyIL("D..ctor(D)", @"
{
// Code size 21 (0x15)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""C..ctor(C)""
IL_0007: nop
IL_0008: nop
IL_0009: ldstr ""RAN ""
IL_000e: call ""void System.Console.Write(string)""
IL_0013: nop
IL_0014: ret
}
");
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_Synthesized_WithFieldInitializers()
{
var source =
@"public record C(int I)
{
}
public record D(int J) : C(1)
{
public int field = 42;
public static void Main()
{
var d = new D(2);
System.Console.Write((d.I, d.J, d.field));
System.Console.Write("" "");
var d2 = d with { I = 10, J = 20 };
System.Console.Write((d2.I, d2.J, d.field));
}
}
";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
var verifier = CompileAndVerify(comp, expectedOutput: "(1, 2, 42) (10, 20, 42)", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics();
verifier.VerifyIL("D..ctor(D)", @"
{
// Code size 33 (0x21)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""C..ctor(C)""
IL_0007: nop
IL_0008: ldarg.0
IL_0009: ldarg.1
IL_000a: ldfld ""int D.<J>k__BackingField""
IL_000f: stfld ""int D.<J>k__BackingField""
IL_0014: ldarg.0
IL_0015: ldarg.1
IL_0016: ldfld ""int D.field""
IL_001b: stfld ""int D.field""
IL_0020: ret
}
");
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_UserDefinedButPrivate()
{
var source =
@"public record B(object N1, object N2)
{
private B(B b) { }
}
public record C(object P1, object P2) : B(0, 1)
{
private C(C c) : base(2, 3) { } // 1
}
public record D(object P1, object P2) : B(0, 1)
{
private D(D d) : base(d) { } // 2
}
public record E(object P1, object P2) : B(0, 1); // 3
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (3,13): error CS8878: A copy constructor 'B.B(B)' must be public or protected because the record is not sealed.
// private B(B b) { }
Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "B").WithArguments("B.B(B)").WithLocation(3, 13),
// (7,13): error CS8878: A copy constructor 'C.C(C)' must be public or protected because the record is not sealed.
// private C(C c) : base(2, 3) { } // 1
Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "C").WithArguments("C.C(C)").WithLocation(7, 13),
// (7,22): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object.
// private C(C c) : base(2, 3) { } // 1
Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "base").WithLocation(7, 22),
// (11,13): error CS8878: A copy constructor 'D.D(D)' must be public or protected because the record is not sealed.
// private D(D d) : base(d) { } // 2
Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "D").WithArguments("D.D(D)").WithLocation(11, 13),
// (11,22): error CS0122: 'B.B(B)' is inaccessible due to its protection level
// private D(D d) : base(d) { } // 2
Diagnostic(ErrorCode.ERR_BadAccess, "base").WithArguments("B.B(B)").WithLocation(11, 22),
// (13,15): error CS8867: No accessible copy constructor found in base type 'B'.
// public record E(object P1, object P2) : B(0, 1); // 3
Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "E").WithArguments("B").WithLocation(13, 15)
);
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_InaccessibleToCaller()
{
var sourceA =
@"public record B(object N1, object N2)
{
internal B(B b) { }
}";
var compA = CreateCompilation(sourceA);
compA.VerifyDiagnostics(
// (3,14): error CS8878: A copy constructor 'B.B(B)' must be public or protected because the record is not sealed.
// internal B(B b) { }
Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "B").WithArguments("B.B(B)").WithLocation(3, 14)
);
var refA = compA.ToMetadataReference();
var sourceB = @"
record C(object P1, object P2) : B(3, 4); // 1
";
var compB = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9);
compB.VerifyDiagnostics(
// (2,8): error CS8867: No accessible copy constructor found in base type 'B'.
// record C(object P1, object P2) : B(3, 4); // 1
Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "C").WithArguments("B").WithLocation(2, 8)
);
var sourceC = @"
record C(object P1, object P2) : B(3, 4)
{
protected C(C c) : base(c) { } // 1, 2
}
";
var compC = CreateCompilation(sourceC, references: new[] { refA }, parseOptions: TestOptions.Regular9);
compC.VerifyDiagnostics(
// (4,24): error CS0122: 'B.B(B)' is inaccessible due to its protection level
// protected C(C c) : base(c) { } // 1, 2
Diagnostic(ErrorCode.ERR_BadAccess, "base").WithArguments("B.B(B)").WithLocation(4, 24)
);
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_InaccessibleToCallerFromPE_WithIVT()
{
var sourceA = @"
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo(""AssemblyB"")]
internal record B(object N1, object N2)
{
public B(B b) { }
}";
var compA = CreateCompilation(new[] { sourceA, IsExternalInitTypeDefinition }, assemblyName: "AssemblyA", parseOptions: TestOptions.Regular9);
var refA = compA.EmitToImageReference();
var sourceB = @"
record C(int j) : B(3, 4);
";
var compB = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9, assemblyName: "AssemblyB");
compB.VerifyDiagnostics();
var sourceC = @"
record C(int j) : B(3, 4)
{
protected C(C c) : base(c) { }
}
";
var compC = CreateCompilation(sourceC, references: new[] { refA }, parseOptions: TestOptions.Regular9, assemblyName: "AssemblyB");
compC.VerifyDiagnostics();
var compB2 = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9, assemblyName: "AssemblyB2");
compB2.VerifyEmitDiagnostics(
// (2,8): error CS0115: 'C.ToString()': no suitable method found to override
// record C(int j) : B(3, 4);
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.ToString()").WithLocation(2, 8),
// (2,8): error CS0115: 'C.GetHashCode()': no suitable method found to override
// record C(int j) : B(3, 4);
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.GetHashCode()").WithLocation(2, 8),
// (2,8): error CS0115: 'C.EqualityContract': no suitable method found to override
// record C(int j) : B(3, 4);
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.EqualityContract").WithLocation(2, 8),
// (2,8): error CS0115: 'C.Equals(object?)': no suitable method found to override
// record C(int j) : B(3, 4);
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.Equals(object?)").WithLocation(2, 8),
// (2,8): error CS0115: 'C.PrintMembers(StringBuilder)': no suitable method found to override
// record C(int j) : B(3, 4);
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8),
// (2,19): error CS0122: 'B' is inaccessible due to its protection level
// record C(int j) : B(3, 4);
Diagnostic(ErrorCode.ERR_BadAccess, "B").WithArguments("B").WithLocation(2, 19),
// (2,20): error CS0122: 'B.B(object, object)' is inaccessible due to its protection level
// record C(int j) : B(3, 4);
Diagnostic(ErrorCode.ERR_BadAccess, "(3, 4)").WithArguments("B.B(object, object)").WithLocation(2, 20)
);
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
[WorkItem(45012, "https://github.com/dotnet/roslyn/issues/45012")]
public void CopyCtor_UserDefinedButPrivate_InSealedType()
{
var source =
@"public record B(int i)
{
}
public sealed record C(int j) : B(0)
{
private C(C c) : base(c)
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var copyCtor = comp.GetMembers("C..ctor")[1];
Assert.Equal("C..ctor(C c)", copyCtor.ToTestDisplayString());
Assert.True(copyCtor.DeclaredAccessibility == Accessibility.Private);
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
[WorkItem(45012, "https://github.com/dotnet/roslyn/issues/45012")]
public void CopyCtor_UserDefinedButInternal()
{
var source =
@"public record B(object N1, object N2)
{
}
public sealed record Sealed(object P1, object P2) : B(0, 1)
{
internal Sealed(Sealed s) : base(s)
{
}
}
public record Unsealed(object P1, object P2) : B(0, 1)
{
internal Unsealed(Unsealed s) : base(s)
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (12,14): error CS8878: A copy constructor 'Unsealed.Unsealed(Unsealed)' must be public or protected because the record is not sealed.
// internal Unsealed(Unsealed s) : base(s)
Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "Unsealed").WithArguments("Unsealed.Unsealed(Unsealed)").WithLocation(12, 14)
);
var sealedCopyCtor = comp.GetMembers("Sealed..ctor")[1];
Assert.Equal("Sealed..ctor(Sealed s)", sealedCopyCtor.ToTestDisplayString());
Assert.True(sealedCopyCtor.DeclaredAccessibility == Accessibility.Internal);
var unsealedCopyCtor = comp.GetMembers("Unsealed..ctor")[1];
Assert.Equal("Unsealed..ctor(Unsealed s)", unsealedCopyCtor.ToTestDisplayString());
Assert.True(unsealedCopyCtor.DeclaredAccessibility == Accessibility.Internal);
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_BaseHasRefKind()
{
var source =
@"public record B(int i)
{
public B(ref B b) => throw null; // 1, not recognized as copy constructor
}
public record C(int j) : B(1)
{
protected C(C c) : base(c)
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (3,12): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer.
// public B(ref B b) => throw null; // 1, not recognized as copy constructor
Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "B").WithLocation(3, 12)
);
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_BaseHasRefKind_WithThisInitializer()
{
var source =
@"public record B(int i)
{
public B(ref B b) : this(0) => throw null; // 1, not recognized as copy constructor
}
public record C(int j) : B(1)
{
protected C(C c) : base(c)
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var actualMembers = comp.GetMember<NamedTypeSymbol>("B").GetMembers().Where(m => m.Name == ".ctor").ToTestDisplayStrings();
var expectedMembers = new[]
{
"B..ctor(System.Int32 i)",
"B..ctor(ref B b)",
"B..ctor(B original)"
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_WithPrivateField()
{
var source =
@"public record B(object N1, object N2)
{
private int field1 = 100;
public int GetField1() => field1;
}
public record C(object P1, object P2) : B(3, 4)
{
private int field2 = 200;
public int GetField2() => field2;
static void Main()
{
var c1 = new C(1, 2);
var c2 = new C(c1);
System.Console.Write((c2.P1, c2.P2, c2.N1, c2.N2, c2.GetField1(), c2.GetField2()));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
var verifier = CompileAndVerify(comp, expectedOutput: "(1, 2, 3, 4, 100, 200)", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics();
verifier.VerifyIL("C..ctor(C)", @"
{
// Code size 44 (0x2c)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""B..ctor(B)""
IL_0007: ldarg.0
IL_0008: ldarg.1
IL_0009: ldfld ""object C.<P1>k__BackingField""
IL_000e: stfld ""object C.<P1>k__BackingField""
IL_0013: ldarg.0
IL_0014: ldarg.1
IL_0015: ldfld ""object C.<P2>k__BackingField""
IL_001a: stfld ""object C.<P2>k__BackingField""
IL_001f: ldarg.0
IL_0020: ldarg.1
IL_0021: ldfld ""int C.field2""
IL_0026: stfld ""int C.field2""
IL_002b: ret
}");
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_MissingInMetadata()
{
// IL for `public record B { }`
var ilSource = @"
.class public auto ansi beforefieldinit B extends [mscorlib]System.Object
{
.method public hidebysig specialname newslot virtual instance class B '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals ( object '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public newslot virtual instance bool Equals ( class B '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
// Removed copy constructor
//.method public hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type B::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}
";
var source = @"
public record C : B {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (2,15): error CS8867: No accessible copy constructor found in base type 'B'.
// public record C : B {
Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "C").WithArguments("B").WithLocation(2, 15)
);
var source2 = @"
public record C : B
{
public C(C c) { }
}";
var comp2 = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp2.VerifyDiagnostics(
// (4,12): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object.
// public C(C c) { }
Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "C").WithLocation(4, 12)
);
}
[Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
public void CopyCtor_InaccessibleInMetadata()
{
// IL for `public record B { }`
var ilSource = @"
.class public auto ansi beforefieldinit B extends [mscorlib]System.Object
{
.method public hidebysig specialname newslot virtual instance class B '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals ( object '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public newslot virtual instance bool Equals ( class B '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
// Inaccessible copy constructor
.method private hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type B::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}
";
var source = @"
public record C : B {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (2,15): error CS8867: No accessible copy constructor found in base type 'B'.
// public record C : B {
Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "C").WithArguments("B").WithLocation(2, 15)
);
}
[Fact, WorkItem(45077, "https://github.com/dotnet/roslyn/issues/45077")]
public void CopyCtor_AmbiguitiesInMetadata()
{
// IL for a minimal `public record B { }` with injected copy constructors
var ilSource_template = @"
.class public auto ansi beforefieldinit B extends [mscorlib]System.Object
{
INJECT
.method public hidebysig specialname newslot virtual instance class B '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldarg.0
IL_0001: newobj instance void B::.ctor(class B)
IL_0006: ret
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
}
.method public newslot virtual
instance bool Equals (
class B ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
}
.method family virtual instance class [mscorlib]System.Type get_EqualityContract() { ldnull ret }
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type B::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}
";
var source = @"
public record C : B
{
public static void Main()
{
var c = new C();
_ = c with { };
}
}";
// We're going to inject various copy constructors into record B (at INJECT marker), and check which one is used
// by derived record C
// The RAN and THROW markers are shorthands for method bodies that print "RAN" and throw, respectively.
// .ctor(B) vs. .ctor(modopt B)
verifyBoth(@"
.method public hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed
RAN
",
@"
.method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed
THROW
");
// .ctor(modopt B) alone
verify(@"
.method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed
RAN
");
// .ctor(B) vs. .ctor(modreq B)
verifyBoth(@"
.method public hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed
RAN
",
@"
.method public hidebysig specialname rtspecialname instance void .ctor ( class B modreq(int64) '' ) cil managed
THROW
");
// .ctor(modopt B) vs. .ctor(modreq B)
verifyBoth(@"
.method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed
RAN
",
@"
.method public hidebysig specialname rtspecialname instance void .ctor ( class B modreq(int64) '' ) cil managed
THROW
");
// .ctor(B) vs. .ctor(modopt1 B) and .ctor(modopt2 B)
verifyBoth(@"
.method public hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed
RAN
",
@"
.method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed
THROW
.method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int32) '' ) cil managed
THROW
");
// .ctor(B) vs. .ctor(modopt1 B) and .ctor(modreq B)
verifyBoth(@"
.method public hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed
RAN
",
@"
.method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed
THROW
.method public hidebysig specialname rtspecialname instance void .ctor ( class B modreq(int32) '' ) cil managed
THROW
");
// .ctor(modeopt1 B) vs. .ctor(modopt2 B)
verifyBoth(@"
.method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed
THROW
",
@"
.method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int32) '' ) cil managed
THROW
", isError: true);
// private .ctor(B) vs. .ctor(modopt1 B) and .ctor(modopt B)
verifyBoth(@"
.method private hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed
RAN
",
@"
.method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed
THROW
.method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int32) '' ) cil managed
THROW
", isError: true);
void verifyBoth(string inject1, string inject2, bool isError = false)
{
verify(inject1 + inject2, isError);
verify(inject2 + inject1, isError);
}
void verify(string inject, bool isError = false)
{
var ranBody = @"
{
IL_0000: ldstr ""RAN""
IL_0005: call void [mscorlib]System.Console::WriteLine(string)
IL_000a: ret
}
";
var throwBody = @"
{
IL_0000: ldnull
IL_0001: throw
}
";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition },
ilSource: ilSource_template.Replace("INJECT", inject).Replace("RAN", ranBody).Replace("THROW", throwBody),
parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
var expectedDiagnostics = isError ? new[] {
// (2,15): error CS8867: No accessible copy constructor found in base type 'B'.
// public record C : B
Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "C").WithArguments("B").WithLocation(2, 15)
} : new DiagnosticDescription[] { };
comp.VerifyDiagnostics(expectedDiagnostics);
if (expectedDiagnostics is null)
{
CompileAndVerify(comp, expectedOutput: "RAN").VerifyDiagnostics();
}
}
}
[Fact, WorkItem(45077, "https://github.com/dotnet/roslyn/issues/45077")]
public void CopyCtor_AmbiguitiesInMetadata_GenericType()
{
// IL for a minimal `public record B<T> { }` with modopt in nested position of parameter type
var ilSource = @"
.class public auto ansi beforefieldinit B`1<T> extends [mscorlib]System.Object implements class [mscorlib]System.IEquatable`1<class B`1<!T>>
{
.method family hidebysig specialname rtspecialname instance void .ctor ( class B`1<!T modopt(int64)> '' ) cil managed
{
IL_0000: ldstr ""RAN""
IL_0005: call void [mscorlib]System.Console::WriteLine(string)
IL_000a: ret
}
.method public hidebysig specialname newslot virtual instance class B`1<!T> '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
IL_0000: ldarg.0
IL_0001: newobj instance void class B`1<!T>::.ctor(class B`1<!0>)
IL_0006: ret
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
}
.method public newslot virtual instance bool Equals ( class B`1<!T> '' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family virtual instance class [mscorlib]System.Type get_EqualityContract() { ldnull ret }
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type B`1::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
}
";
var source = @"
public record C<T> : B<T> { }
public class Program
{
public static void Main()
{
var c = new C<string>();
_ = c with { };
}
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition },
ilSource: ilSource,
parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "RAN").VerifyDiagnostics();
}
[Theory]
[InlineData("")]
[InlineData("private")]
[InlineData("internal")]
[InlineData("private protected")]
[InlineData("internal protected")]
public void CopyCtor_Accessibility_01(string accessibility)
{
var source =
$@"
record A(int X)
{{
{ accessibility } A(A a)
=> throw null;
}}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (4,6): error CS8878: A copy constructor 'A.A(A)' must be public or protected because the record is not sealed.
// A(A a)
Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "A").WithArguments("A.A(A)").WithLocation(4, 6 + accessibility.Length)
);
}
[Theory]
[InlineData("public")]
[InlineData("protected")]
public void CopyCtor_Accessibility_02(string accessibility)
{
var source =
$@"
record A(int X)
{{
{ accessibility } A(A a)
=> System.Console.Write(""RAN"");
public static void Main()
{{
var a = new A(123);
_ = a with {{}};
}}
}}
";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: "RAN").VerifyDiagnostics();
}
[Theory]
[InlineData("")]
[InlineData("private")]
[InlineData("internal")]
[InlineData("public")]
public void CopyCtor_Accessibility_03(string accessibility)
{
var source =
$@"
sealed record A(int X)
{{
{ accessibility } A(A a)
=> System.Console.Write(""RAN"");
public static void Main()
{{
var a = new A(123);
_ = a with {{}};
}}
}}
";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: "RAN").VerifyDiagnostics();
var clone = comp.GetMember<MethodSymbol>("A." + WellKnownMemberNames.CloneMethodName);
Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility);
Assert.False(clone.IsOverride);
Assert.False(clone.IsVirtual);
Assert.False(clone.IsAbstract);
Assert.False(clone.IsSealed);
Assert.True(clone.IsImplicitlyDeclared);
}
[Theory]
[InlineData("private protected")]
[InlineData("internal protected")]
[InlineData("protected")]
public void CopyCtor_Accessibility_04(string accessibility)
{
var source =
$@"
sealed record A(int X)
{{
{ accessibility } A(A a)
=> System.Console.Write(""RAN"");
public static void Main()
{{
var a = new A(123);
_ = a with {{}};
}}
}}
";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: "RAN").VerifyDiagnostics(
// (4,15): warning CS0628: 'A.A(A)': new protected member declared in sealed type
// protected A(A a)
Diagnostic(ErrorCode.WRN_ProtectedInSealed, "A").WithArguments("A.A(A)").WithLocation(4, 6 + accessibility.Length)
);
var clone = comp.GetMember<MethodSymbol>("A." + WellKnownMemberNames.CloneMethodName);
Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility);
Assert.False(clone.IsOverride);
Assert.False(clone.IsVirtual);
Assert.False(clone.IsAbstract);
Assert.False(clone.IsSealed);
Assert.True(clone.IsImplicitlyDeclared);
}
[Fact]
public void CopyCtor_Signature_01()
{
var source =
@"
record A(int X)
{
public A(in A a) : this(-15)
=> System.Console.Write(""RAN"");
public static void Main()
{
var a = new A(123);
System.Console.Write((a with { }).X);
}
}
";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: "123").VerifyDiagnostics();
}
[Fact]
public void Deconstruct_Simple()
{
var source =
@"using System;
record B(int X, int Y)
{
public static void Main()
{
M(new B(1, 2));
}
static void M(B b)
{
switch (b)
{
case B(int x, int y):
Console.Write(x);
Console.Write(y);
break;
}
}
}";
var verifier = CompileAndVerify(source, expectedOutput: "12");
verifier.VerifyDiagnostics();
verifier.VerifyIL("B.Deconstruct", @"
{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: call ""int B.X.get""
IL_0007: stind.i4
IL_0008: ldarg.2
IL_0009: ldarg.0
IL_000a: call ""int B.Y.get""
IL_000f: stind.i4
IL_0010: ret
}");
var deconstruct = ((CSharpCompilation)verifier.Compilation).GetMember<MethodSymbol>("B.Deconstruct");
Assert.Equal(2, deconstruct.ParameterCount);
Assert.Equal(RefKind.Out, deconstruct.Parameters[0].RefKind);
Assert.Equal("X", deconstruct.Parameters[0].Name);
Assert.Equal(RefKind.Out, deconstruct.Parameters[1].RefKind);
Assert.Equal("Y", deconstruct.Parameters[1].Name);
Assert.True(deconstruct.ReturnsVoid);
Assert.False(deconstruct.IsVirtual);
Assert.False(deconstruct.IsStatic);
Assert.Equal(Accessibility.Public, deconstruct.DeclaredAccessibility);
}
[Fact]
public void Deconstruct_PositionalAndNominalProperty()
{
var source =
@"using System;
record B(int X)
{
public int Y { get; init; }
public static void Main()
{
M(new B(1));
}
static void M(B b)
{
switch (b)
{
case B(int x):
Console.Write(x);
break;
}
}
}";
var verifier = CompileAndVerify(source, expectedOutput: "1");
verifier.VerifyDiagnostics();
Assert.Equal(
"void B.Deconstruct(out System.Int32 X)",
verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_Nested()
{
var source =
@"using System;
record B(int X, int Y);
record C(B B, int Z)
{
public static void Main()
{
M(new C(new B(1, 2), 3));
}
static void M(C c)
{
switch (c)
{
case C(B(int x, int y), int z):
Console.Write(x);
Console.Write(y);
Console.Write(z);
break;
}
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "123");
verifier.VerifyDiagnostics();
verifier.VerifyIL("B.Deconstruct", @"
{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: call ""int B.X.get""
IL_0007: stind.i4
IL_0008: ldarg.2
IL_0009: ldarg.0
IL_000a: call ""int B.Y.get""
IL_000f: stind.i4
IL_0010: ret
}");
verifier.VerifyIL("C.Deconstruct", @"
{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: call ""B C.B.get""
IL_0007: stind.ref
IL_0008: ldarg.2
IL_0009: ldarg.0
IL_000a: call ""int C.Z.get""
IL_000f: stind.i4
IL_0010: ret
}");
}
[Fact]
public void Deconstruct_PropertyCollision()
{
var source =
@"using System;
record B(int X, int Y)
{
public int X => 3;
static void M(B b)
{
switch (b)
{
case B(int x, int y):
Console.Write(x);
Console.Write(y);
break;
}
}
static void Main()
{
M(new B(1, 2));
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "32");
verifier.VerifyDiagnostics(
// (3,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record B(int X, int Y)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 14)
);
Assert.Equal(
"void B.Deconstruct(out System.Int32 X, out System.Int32 Y)",
verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_MethodCollision_01()
{
var source = @"
record B(int X, int Y)
{
public int X() => 3;
static void M(B b)
{
switch (b)
{
case B(int x, int y):
break;
}
}
static void Main()
{
M(new B(1, 2));
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,16): error CS0102: The type 'B' already contains a definition for 'X'
// public int X() => 3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("B", "X").WithLocation(4, 16)
);
Assert.Equal(
"void B.Deconstruct(out System.Int32 X, out System.Int32 Y)",
comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_MethodCollision_02()
{
var source = @"
record B
{
public int X(int y) => y;
}
record C(int X, int Y) : B
{
static void M(C c)
{
switch (c)
{
case C(int x, int y):
break;
}
}
static void Main()
{
M(new C(1, 2));
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (7,14): error CS8866: Record member 'B.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'.
// record C(int X, int Y) : B
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("B.X", "int", "X").WithLocation(7, 14),
// (7,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X, int Y) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(7, 14)
);
Assert.Equal(
"void C.Deconstruct(out System.Int32 X, out System.Int32 Y)",
comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_MethodCollision_03()
{
var source = @"
using System;
record B
{
public int X() => 3;
}
record C(int X, int Y) : B
{
public new int X { get; }
static void M(C c)
{
switch (c)
{
case C(int x, int y):
Console.Write(x);
Console.Write(y);
break;
}
}
static void Main()
{
M(new C(1, 2));
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "02");
verifier.VerifyDiagnostics(
// (9,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X, int Y) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(9, 14)
);
Assert.Equal(
"void C.Deconstruct(out System.Int32 X, out System.Int32 Y)",
verifier.Compilation.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_MethodCollision_04()
{
var source = @"
record C(int X, int Y)
{
public int X(int arg) => 3;
static void M(C c)
{
switch (c)
{
case C(int x, int y):
break;
}
}
static void Main()
{
M(new C(1, 2));
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,16): error CS0102: The type 'C' already contains a definition for 'X'
// public int X(int arg) => 3;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("C", "X").WithLocation(4, 16)
);
Assert.Equal(
"void C.Deconstruct(out System.Int32 X, out System.Int32 Y)",
comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_FieldCollision()
{
var source = @"
using System;
record C(int X)
{
int X;
static void M(C c)
{
switch (c)
{
case C(int x):
Console.Write(x);
break;
}
}
static void Main()
{
M(new C(0));
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (4,10): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater.
// record C(int X)
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int X").WithArguments("positional fields in records", "10.0").WithLocation(4, 10),
// (4,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(4, 14),
// (6,9): warning CS0169: The field 'C.X' is never used
// int X;
Diagnostic(ErrorCode.WRN_UnreferencedField, "X").WithArguments("C.X").WithLocation(6, 9)
);
comp = CreateCompilation(source, parseOptions: TestOptions.Regular10);
comp.VerifyDiagnostics(
// (4,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(4, 14),
// (6,9): warning CS0169: The field 'C.X' is never used
// int X;
Diagnostic(ErrorCode.WRN_UnreferencedField, "X").WithArguments("C.X").WithLocation(6, 9)
);
Assert.Equal(
"void C.Deconstruct(out System.Int32 X)",
comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_EventCollision()
{
var source = @"
using System;
record C(Action X)
{
event Action X;
static void M(C c)
{
switch (c)
{
case C(Action x):
Console.Write(x);
break;
}
}
static void Main()
{
M(new C(() => { }));
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,18): error CS0102: The type 'C' already contains a definition for 'X'
// event Action X;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("C", "X").WithLocation(6, 18),
// (6,18): warning CS0067: The event 'C.X' is never used
// event Action X;
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "X").WithArguments("C.X").WithLocation(6, 18)
);
Assert.Equal(
"void C.Deconstruct(out System.Action X)",
comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_WriteOnlyPropertyInBase()
{
var source = @"
using System;
record B
{
public int X { set { } }
}
record C(int X) : B
{
static void M(C c)
{
switch (c)
{
case C(int x):
Console.Write(x);
break;
}
}
static void Main()
{
M(new C(1));
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (9,14): error CS8866: Record member 'B.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'.
// record C(int X) : B
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("B.X", "int", "X").WithLocation(9, 14),
// (9,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(9, 14));
Assert.Equal(
"void C.Deconstruct(out System.Int32 X)",
comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_PrivateWriteOnlyPropertyInBase()
{
var source = @"
using System;
record B
{
private int X { set { } }
}
record C(int X) : B
{
static void M(C c)
{
switch (c)
{
case C(int x):
Console.Write(x);
break;
}
}
static void Main()
{
M(new C(1));
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "1");
verifier.VerifyDiagnostics();
Assert.Equal(
"void C.Deconstruct(out System.Int32 X)",
verifier.Compilation.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_Empty()
{
var source = @"
record C
{
static void M(C c)
{
switch (c)
{
case C():
break;
}
}
static void Main()
{
M(new C());
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,19): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?)
// case C():
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "()").WithArguments("C", "Deconstruct").WithLocation(8, 19),
// (8,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 0 out parameters and a void return type.
// case C():
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("C", "0").WithLocation(8, 19));
Assert.Null(comp.GetMember("C.Deconstruct"));
}
[Fact]
public void Deconstruct_Inheritance_01()
{
var source = @"
using System;
record B(int X, int Y)
{
internal B() : this(0, 1) { }
}
record C : B
{
static void M(C c)
{
switch (c)
{
case C(int x, int y):
Console.Write(x);
Console.Write(y);
break;
}
switch (c)
{
case B(int x, int y):
Console.Write(x);
Console.Write(y);
break;
}
}
static void Main()
{
M(new C());
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "0101");
verifier.VerifyDiagnostics();
var comp = verifier.Compilation;
Assert.Null(comp.GetMember("C.Deconstruct"));
Assert.Equal(
"void B.Deconstruct(out System.Int32 X, out System.Int32 Y)",
comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_Inheritance_02()
{
var source = @"
using System;
record B(int X, int Y)
{
// https://github.com/dotnet/roslyn/issues/44902
internal B() : this(0, 1) { }
}
record C(int X, int Y, int Z) : B(X, Y)
{
static void M(C c)
{
switch (c)
{
case C(int x, int y, int z):
Console.Write(x);
Console.Write(y);
Console.Write(z);
break;
}
switch (c)
{
case B(int x, int y):
Console.Write(x);
Console.Write(y);
break;
}
}
static void Main()
{
M(new C(0, 1, 2));
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "01201");
verifier.VerifyDiagnostics();
var comp = verifier.Compilation;
Assert.Equal(
"void C.Deconstruct(out System.Int32 X, out System.Int32 Y, out System.Int32 Z)",
comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false));
Assert.Equal(
"void B.Deconstruct(out System.Int32 X, out System.Int32 Y)",
comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_Inheritance_03()
{
var source = @"
using System;
record B(int X, int Y)
{
internal B() : this(0, 1) { }
}
record C(int X, int Y) : B
{
static void M(C c)
{
switch (c)
{
case C(int x, int y):
Console.Write(x);
Console.Write(y);
break;
}
switch (c)
{
case B(int x, int y):
Console.Write(x);
Console.Write(y);
break;
}
}
static void Main()
{
M(new C(0, 1));
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "0101");
verifier.VerifyDiagnostics(
// (9,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X, int Y) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(9, 14),
// (9,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X, int Y) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(9, 21)
);
var comp = verifier.Compilation;
Assert.Equal(
"void C.Deconstruct(out System.Int32 X, out System.Int32 Y)",
comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false));
Assert.Equal(
"void B.Deconstruct(out System.Int32 X, out System.Int32 Y)",
comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_Inheritance_04()
{
var source = @"
using System;
record A<T>(T P) { internal A() : this(default(T)) { } }
record B1(int P, object Q) : A<int>(P) { internal B1() : this(0, null) { } }
record B2(object P, object Q) : A<object>(P) { internal B2() : this(null, null) { } }
record B3<T>(T P, object Q) : A<T>(P) { internal B3() : this(default, 0) { } }
class C
{
static void M0(A<int> arg)
{
switch (arg)
{
case A<int>(int x):
Console.Write(x);
break;
}
}
static void M1(B1 arg)
{
switch (arg)
{
case B1(int p, object q):
Console.Write(p);
Console.Write(q);
break;
}
}
static void M2(B2 arg)
{
switch (arg)
{
case B2(object p, object q):
Console.Write(p);
Console.Write(q);
break;
}
}
static void M3(B3<int> arg)
{
switch (arg)
{
case B3<int>(int p, object q):
Console.Write(p);
Console.Write(q);
break;
}
}
static void Main()
{
M0(new A<int>(0));
M1(new B1(1, 2));
M2(new B2(3, 4));
M3(new B3<int>(5, 6));
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "0123456");
verifier.VerifyDiagnostics();
var comp = verifier.Compilation;
Assert.Equal(
"void A<T>.Deconstruct(out T P)",
comp.GetMember("A.Deconstruct").ToTestDisplayString(includeNonNullable: false));
Assert.Equal(
"void B1.Deconstruct(out System.Int32 P, out System.Object Q)",
comp.GetMember("B1.Deconstruct").ToTestDisplayString(includeNonNullable: false));
Assert.Equal(
"void B2.Deconstruct(out System.Object P, out System.Object Q)",
comp.GetMember("B2.Deconstruct").ToTestDisplayString(includeNonNullable: false));
Assert.Equal(
"void B3<T>.Deconstruct(out T P, out System.Object Q)",
comp.GetMember("B3.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_Conversion_01()
{
var source = @"
using System;
record C(int X, int Y)
{
public long X { get; init; }
public long Y { get; init; }
static void M(C c)
{
switch (c)
{
case C(int x, int y):
Console.Write(x);
Console.Write(y);
break;
}
}
static void Main()
{
M(new C(0, 1));
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,14): error CS8866: Record member 'C.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'.
// record C(int X, int Y)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("C.X", "int", "X").WithLocation(4, 14),
// (4,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X, int Y)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(4, 14),
// (4,21): error CS8866: Record member 'C.Y' must be a readable instance property or field of type 'int' to match positional parameter 'Y'.
// record C(int X, int Y)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Y").WithArguments("C.Y", "int", "Y").WithLocation(4, 21),
// (4,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X, int Y)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(4, 21));
Assert.Equal(
"void C.Deconstruct(out System.Int32 X, out System.Int32 Y)",
comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_Conversion_02()
{
var source = @"
#nullable enable
using System;
record C(string? X, string Y)
{
public string X { get; init; } = null!;
public string? Y { get; init; }
static void M(C c)
{
switch (c)
{
case C(var x, string y):
Console.Write(x);
Console.Write(y);
break;
}
}
static void Main()
{
M(new C(""a"", ""b""));
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (5,18): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record C(string? X, string Y)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(5, 18),
// (5,28): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// record C(string? X, string Y)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(5, 28)
);
Assert.Equal(
"void C.Deconstruct(out System.String? X, out System.String Y)",
comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_Conversion_03()
{
var source = @"
using System;
class Base { }
class Derived : Base { }
record C(Derived X, Base Y)
{
public Base X { get; init; }
public Derived Y { get; init; }
static void M(C c)
{
switch (c)
{
case C(Derived x, Base y):
Console.Write(x);
Console.Write(y);
break;
}
}
static void Main()
{
M(new C(new Derived(), new Base()));
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (7,18): error CS8866: Record member 'C.X' must be a readable instance property or field of type 'Derived' to match positional parameter 'X'.
// record C(Derived X, Base Y)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("C.X", "Derived", "X").WithLocation(7, 18),
// (7,18): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record C(Derived X, Base Y)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(7, 18),
// (7,26): error CS8866: Record member 'C.Y' must be a readable instance property or field of type 'Base' to match positional parameter 'Y'.
// record C(Derived X, Base Y)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Y").WithArguments("C.Y", "Base", "Y").WithLocation(7, 26),
// (7,26): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// record C(Derived X, Base Y)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(7, 26));
Assert.Equal(
"void C.Deconstruct(out Derived X, out Base Y)",
comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_Empty_WithParameterList()
{
var source = @"
record C()
{
static void M(C c)
{
switch (c)
{
case C():
break;
}
}
static void Main()
{
M(new C());
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,19): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?)
// case C():
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "()").WithArguments("C", "Deconstruct").WithLocation(8, 19),
// (8,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 0 out parameters and a void return type.
// case C():
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("C", "0").WithLocation(8, 19));
Assert.Null(comp.GetMember("C.Deconstruct"));
}
[Fact]
public void Deconstruct_Empty_WithParameterList_UserDefined_01()
{
var source =
@"using System;
record C()
{
public void Deconstruct()
{
}
static void M(C c)
{
switch (c)
{
case C():
Console.Write(12);
break;
}
}
public static void Main()
{
M(new C());
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "12");
verifier.VerifyDiagnostics();
}
[Fact]
public void Deconstruct_Empty_WithParameterList_UserDefined_02()
{
var source =
@"using System;
record C()
{
public void Deconstruct(out int X, out int Y)
{
X = 1;
Y = 2;
}
static void M(C c)
{
switch (c)
{
case C(int x, int y):
Console.Write(x);
Console.Write(y);
break;
}
}
public static void Main()
{
M(new C());
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "12");
verifier.VerifyDiagnostics();
}
[Fact]
public void Deconstruct_Empty_WithParameterList_UserDefined_03()
{
var source =
@"using System;
record C()
{
private void Deconstruct()
{
}
static void M(C c)
{
switch (c)
{
case C():
Console.Write(12);
break;
}
}
public static void Main()
{
M(new C());
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "12");
verifier.VerifyDiagnostics();
}
[Fact]
public void Deconstruct_Empty_WithParameterList_UserDefined_04()
{
var source = @"
record C()
{
static void M(C c)
{
switch (c)
{
case C():
break;
}
}
static void Main()
{
M(new C());
}
public static void Deconstruct()
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,19): error CS0176: Member 'C.Deconstruct()' cannot be accessed with an instance reference; qualify it with a type name instead
// case C():
Diagnostic(ErrorCode.ERR_ObjectProhibited, "()", isSuppressed: false).WithArguments("C.Deconstruct()").WithLocation(8, 19),
// (8,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 0 out parameters and a void return type.
// case C():
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("C", "0").WithLocation(8, 19));
}
[Fact]
public void Deconstruct_Empty_WithParameterList_UserDefined_05()
{
var source = @"
record C()
{
static void M(C c)
{
switch (c)
{
case C():
break;
}
}
static void Main()
{
M(new C());
}
public int Deconstruct()
{
return 1;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 0 out parameters and a void return type.
// case C():
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("C", "0").WithLocation(8, 19));
}
[Fact]
public void Deconstruct_UserDefined()
{
var source =
@"using System;
record B(int X, int Y)
{
public void Deconstruct(out int X, out int Y)
{
X = this.X + 1;
Y = this.Y + 2;
}
static void M(B b)
{
switch (b)
{
case B(int x, int y):
Console.Write(x);
Console.Write(y);
break;
}
}
public static void Main()
{
M(new B(0, 0));
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "12");
verifier.VerifyDiagnostics();
}
[Fact]
public void Deconstruct_UserDefined_DifferentSignature_01()
{
var source =
@"using System;
record B(int X, int Y)
{
public void Deconstruct(out int Z)
{
Z = X + Y;
}
static void M(B b)
{
switch (b)
{
case B(int x, int y):
Console.Write(x);
Console.Write(y);
break;
}
switch (b)
{
case B(int z):
Console.Write(z);
break;
}
}
public static void Main()
{
M(new B(1, 2));
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "123");
verifier.VerifyDiagnostics();
var expectedSymbols = new[]
{
"void B.Deconstruct(out System.Int32 X, out System.Int32 Y)",
"void B.Deconstruct(out System.Int32 Z)",
};
Assert.Equal(expectedSymbols, verifier.Compilation.GetMembers("B.Deconstruct").Select(s => s.ToTestDisplayString(includeNonNullable: false)));
}
[Fact]
public void Deconstruct_UserDefined_DifferentSignature_02()
{
var source =
@"using System;
record B(int X)
{
public int Deconstruct(out int a) => throw null;
static void M(B b)
{
switch (b)
{
case B(int x):
Console.Write(x);
break;
}
}
public static void Main()
{
M(new B(1));
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (5,16): error CS8874: Record member 'B.Deconstruct(out int)' must return 'void'.
// public int Deconstruct(out int a) => throw null;
Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "Deconstruct").WithArguments("B.Deconstruct(out int)", "void").WithLocation(5, 16),
// (11,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'B', with 1 out parameters and a void return type.
// case B(int x):
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(int x)").WithArguments("B", "1").WithLocation(11, 19));
Assert.Equal("System.Int32 B.Deconstruct(out System.Int32 a)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_UserDefined_DifferentSignature_03()
{
var source =
@"using System;
record B(int X)
{
public void Deconstruct(int X)
{
}
static void M(B b)
{
switch (b)
{
case B(int x):
Console.Write(x);
break;
}
}
public static void Main()
{
M(new B(1));
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "1");
verifier.VerifyDiagnostics();
var expectedSymbols = new[]
{
"void B.Deconstruct(out System.Int32 X)",
"void B.Deconstruct(System.Int32 X)",
};
Assert.Equal(expectedSymbols, verifier.Compilation.GetMembers("B.Deconstruct").Select(s => s.ToTestDisplayString(includeNonNullable: false)));
}
[Fact]
public void Deconstruct_UserDefined_DifferentSignature_04()
{
var source =
@"using System;
record B(int X)
{
public void Deconstruct(ref int X)
{
}
static void M(B b)
{
switch (b)
{
case B(int x):
Console.Write(x);
break;
}
}
public static void Main()
{
M(new B(1));
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (5,17): error CS0663: 'B' cannot define an overloaded method that differs only on parameter modifiers 'ref' and 'out'
// public void Deconstruct(ref int X)
Diagnostic(ErrorCode.ERR_OverloadRefKind, "Deconstruct").WithArguments("B", "method", "ref", "out").WithLocation(5, 17)
);
Assert.Equal(2, comp.GetMembers("B.Deconstruct").Length);
}
[Fact]
public void Deconstruct_UserDefined_DifferentSignature_05()
{
var source =
@"using System;
record A(int X)
{
public A() : this(0) { }
public int Deconstruct(out int a, out int b) => throw null;
}
record B(int X, int Y) : A(X)
{
static void M(B b)
{
switch (b)
{
case B(int x, int y):
Console.Write(x);
Console.Write(y);
break;
}
}
public static void Main()
{
M(new B(1, 2));
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "12");
verifier.VerifyDiagnostics();
Assert.Equal("void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact]
public void Deconstruct_UserDefined_DifferentSignature_06()
{
var source =
@"using System;
record A(int X)
{
public A() : this(0) { }
public virtual int Deconstruct(out int a, out int b) => throw null;
}
record B(int X, int Y) : A(X)
{
static void M(B b)
{
switch (b)
{
case B(int x, int y):
Console.Write(x);
Console.Write(y);
break;
}
}
public static void Main()
{
M(new B(1, 2));
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "12");
verifier.VerifyDiagnostics();
Assert.Equal("void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Theory]
[InlineData("")]
[InlineData("private")]
[InlineData("protected")]
[InlineData("internal")]
[InlineData("private protected")]
[InlineData("internal protected")]
public void Deconstruct_UserDefined_Accessibility_07(string accessibility)
{
var source =
$@"
record A(int X)
{{
{ accessibility } void Deconstruct(out int a)
=> throw null;
}}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (4,11): error CS8873: Record member 'A.Deconstruct(out int)' must be public.
// void Deconstruct(out int a)
Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Deconstruct").WithArguments("A.Deconstruct(out int)").WithLocation(4, 11 + accessibility.Length)
);
}
[Fact]
public void Deconstruct_UserDefined_Static_08()
{
var source =
@"
record A(int X)
{
public static void Deconstruct(out int a)
=> throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (4,24): error CS8877: Record member 'A.Deconstruct(out int)' may not be static.
// public static void Deconstruct(out int a)
Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "Deconstruct").WithArguments("A.Deconstruct(out int)").WithLocation(4, 24)
);
}
[Fact]
public void Deconstruct_Shadowing_01()
{
var source =
@"
abstract record A(int X)
{
public abstract int Deconstruct(out int a, out int b);
}
abstract record B(int X, int Y) : A(X)
{
public static void Main()
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (6,17): error CS0533: 'B.Deconstruct(out int, out int)' hides inherited abstract member 'A.Deconstruct(out int, out int)'
// abstract record B(int X, int Y) : A(X)
Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "B").WithArguments("B.Deconstruct(out int, out int)", "A.Deconstruct(out int, out int)").WithLocation(6, 17)
);
}
[Fact]
public void Deconstruct_TypeMismatch_01()
{
var source =
@"
record A(int X)
{
public System.Type X => throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (2,14): error CS8866: Record member 'A.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'.
// record A(int X)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("A.X", "int", "X").WithLocation(2, 14),
// (2,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record A(int X)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 14)
);
}
[Fact]
public void Deconstruct_TypeMismatch_02()
{
var source =
@"
record A
{
public System.Type X => throw null;
}
record B(int X) : A;
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (7,14): error CS8866: Record member 'A.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'.
// record B(int X) : A;
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("A.X", "int", "X").WithLocation(7, 14),
// (7,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record B(int X) : A;
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(7, 14)
);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/45010")]
[WorkItem(45010, "https://github.com/dotnet/roslyn/issues/45010")]
public void Deconstruct_ObsoleteProperty()
{
var source =
@"using System;
record B(int X)
{
[Obsolete] int X { get; } = X;
static void M(B b)
{
switch (b)
{
case B(int x):
Console.Write(x);
break;
}
}
public static void Main()
{
M(new B(1));
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "1");
verifier.VerifyDiagnostics();
Assert.Equal("void B.Deconstruct(out System.Int32 X)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/45009")]
[WorkItem(45009, "https://github.com/dotnet/roslyn/issues/45009")]
public void Deconstruct_RefProperty()
{
var source =
@"using System;
record B(int X)
{
static int _x = 2;
ref int X => ref _x;
static void M(B b)
{
switch (b)
{
case B(int x):
Console.Write(x);
break;
}
}
public static void Main()
{
M(new B(1));
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "2");
verifier.VerifyDiagnostics();
var deconstruct = verifier.Compilation.GetMember("B.Deconstruct");
Assert.Equal("void B.Deconstruct(out System.Int32 X)", deconstruct.ToTestDisplayString(includeNonNullable: false));
Assert.Equal(Accessibility.Public, deconstruct.DeclaredAccessibility);
Assert.False(deconstruct.IsAbstract);
Assert.False(deconstruct.IsVirtual);
Assert.False(deconstruct.IsOverride);
Assert.False(deconstruct.IsSealed);
Assert.True(deconstruct.IsImplicitlyDeclared);
}
[Fact]
public void Deconstruct_Static()
{
var source = @"
using System;
record B(int X, int Y)
{
static int Y { get; }
static void M(B b)
{
switch (b)
{
case B(int x, int y):
Console.Write(x);
Console.Write(y);
break;
}
}
public static void Main()
{
M(new B(1, 2));
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,21): error CS8866: Record member 'B.Y' must be a readable instance property or field of type 'int' to match positional parameter 'Y'.
// record B(int X, int Y)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Y").WithArguments("B.Y", "int", "Y").WithLocation(4, 21),
// (4,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// record B(int X, int Y)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(4, 21));
Assert.Equal(
"void B.Deconstruct(out System.Int32 X, out System.Int32 Y)",
comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false));
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Overrides_01(bool usePreview)
{
var source =
@"record A
{
public sealed override bool Equals(object other) => false;
public sealed override int GetHashCode() => 0;
public sealed override string ToString() => null;
}
record B(int X, int Y) : A
{
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: usePreview ? TestOptions.Regular10 : TestOptions.Regular9);
if (usePreview)
{
comp.VerifyDiagnostics(
// (3,33): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types
// public sealed override bool Equals(object other) => false;
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(3, 33),
// (4,32): error CS8870: 'A.GetHashCode()' cannot be sealed because containing record is not sealed.
// public sealed override int GetHashCode() => 0;
Diagnostic(ErrorCode.ERR_SealedAPIInRecord, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(4, 32),
// (7,8): error CS0239: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is sealed
// record B(int X, int Y) : A
Diagnostic(ErrorCode.ERR_CantOverrideSealed, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(7, 8)
);
}
else
{
comp.VerifyDiagnostics(
// (4,32): error CS8870: 'A.GetHashCode()' cannot be sealed because containing record is not sealed.
// public sealed override int GetHashCode() => 0;
Diagnostic(ErrorCode.ERR_SealedAPIInRecord, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(4, 32),
// (5,35): error CS8773: Feature 'sealed ToString in record' is not available in C# 9.0. Please use language version 10.0 or greater.
// public sealed override string ToString() => null;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "ToString").WithArguments("sealed ToString in record", "10.0").WithLocation(5, 35),
// (3,33): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types
// public sealed override bool Equals(object other) => false;
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(3, 33),
// (7,8): error CS0239: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is sealed
// record B(int X, int Y) : A
Diagnostic(ErrorCode.ERR_CantOverrideSealed, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(7, 8)
);
}
var actualMembers = comp.GetMember<NamedTypeSymbol>("B").GetMembers().ToTestDisplayStrings();
var expectedMembers = new[]
{
"B..ctor(System.Int32 X, System.Int32 Y)",
"System.Type B.EqualityContract.get",
"System.Type B.EqualityContract { get; }",
"System.Int32 B.<X>k__BackingField",
"System.Int32 B.X.get",
"void modreq(System.Runtime.CompilerServices.IsExternalInit) B.X.init",
"System.Int32 B.X { get; init; }",
"System.Int32 B.<Y>k__BackingField",
"System.Int32 B.Y.get",
"void modreq(System.Runtime.CompilerServices.IsExternalInit) B.Y.init",
"System.Int32 B.Y { get; init; }",
"System.Boolean B." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)",
"System.Boolean B.op_Inequality(B? left, B? right)",
"System.Boolean B.op_Equality(B? left, B? right)",
"System.Int32 B.GetHashCode()",
"System.Boolean B.Equals(System.Object? obj)",
"System.Boolean B.Equals(A? other)",
"System.Boolean B.Equals(B? other)",
"A B." + WellKnownMemberNames.CloneMethodName + "()",
"B..ctor(B original)",
"void B.Deconstruct(out System.Int32 X, out System.Int32 Y)"
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void Overrides_02()
{
var source =
@"abstract record A
{
public abstract override bool Equals(object other);
public abstract override int GetHashCode();
public abstract override string ToString();
}
record B(int X, int Y) : A
{
}";
var comp = CreateCompilation(RuntimeUtilities.IsCoreClrRuntime ? source : new[] { source, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.StandardLatest);
comp.VerifyDiagnostics(
// (3,35): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types
// public abstract override bool Equals(object other);
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(3, 35),
// (7,8): error CS0534: 'B' does not implement inherited abstract member 'A.Equals(object)'
// record B(int X, int Y) : A
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.Equals(object)").WithLocation(7, 8)
);
Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses);
string expectedClone = comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses
? "B B." + WellKnownMemberNames.CloneMethodName + "()"
: "A B." + WellKnownMemberNames.CloneMethodName + "()";
var actualMembers = comp.GetMember<NamedTypeSymbol>("B").GetMembers().ToTestDisplayStrings();
var expectedMembers = new[]
{
"B..ctor(System.Int32 X, System.Int32 Y)",
"System.Type B.EqualityContract.get",
"System.Type B.EqualityContract { get; }",
"System.Int32 B.<X>k__BackingField",
"System.Int32 B.X.get",
"void modreq(System.Runtime.CompilerServices.IsExternalInit) B.X.init",
"System.Int32 B.X { get; init; }",
"System.Int32 B.<Y>k__BackingField",
"System.Int32 B.Y.get",
"void modreq(System.Runtime.CompilerServices.IsExternalInit) B.Y.init",
"System.Int32 B.Y { get; init; }",
"System.String B.ToString()",
"System.Boolean B." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)",
"System.Boolean B.op_Inequality(B? left, B? right)",
"System.Boolean B.op_Equality(B? left, B? right)",
"System.Int32 B.GetHashCode()",
"System.Boolean B.Equals(System.Object? obj)",
"System.Boolean B.Equals(A? other)",
"System.Boolean B.Equals(B? other)",
expectedClone,
"B..ctor(B original)",
"void B.Deconstruct(out System.Int32 X, out System.Int32 Y)"
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void ObjectEquals_01()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public final hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0239: 'B.Equals(object?)': cannot override inherited member 'A.Equals(object)' because it is sealed
// public record B : A {
Diagnostic(ErrorCode.ERR_CantOverrideSealed, "B").WithArguments("B.Equals(object?)", "A.Equals(object)").WithLocation(2, 15)
);
}
[Fact]
public void ObjectEquals_02()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public newslot hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance string ToString () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS8869: 'B.Equals(object?)' does not override expected method from 'object'.
// public record B : A {
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "B").WithArguments("B.Equals(object?)").WithLocation(2, 15)
);
}
[Fact]
public void ObjectEquals_03()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public newslot hidebysig
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0506: 'B.Equals(object?)': cannot override inherited member 'A.Equals(object)' because it is not marked virtual, abstract, or override
// public record B : A {
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.Equals(object?)", "A.Equals(object)").WithLocation(2, 15)
);
}
[Fact]
public void ObjectEquals_04()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public newslot hidebysig virtual
instance int32 Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0508: 'B.Equals(object?)': return type must be 'int' to match overridden member 'A.Equals(object)'
// public record B : A {
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "B").WithArguments("B.Equals(object?)", "A.Equals(object)", "int").WithLocation(2, 15)
);
}
[Fact]
public void ObjectEquals_05()
{
var source0 =
@"namespace System
{
public class Object
{
public virtual int Equals(object other) => default;
public virtual int GetHashCode() => default;
public virtual string ToString() => """";
}
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Char { }
public struct Int32 { }
public interface IEquatable<T>
{
bool Equals(T other);
}
}
namespace System.Text
{
public class StringBuilder
{
public StringBuilder Append(string s) => null;
public StringBuilder Append(char c) => null;
public StringBuilder Append(object o) => null;
}
}
";
var comp = CreateEmptyCompilation(source0);
comp.VerifyDiagnostics();
var ref0 = comp.EmitToImageReference();
var source1 =
@"
public record A {
}
";
comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0508: 'A.Equals(object?)': return type must be 'int' to match overridden member 'object.Equals(object)'
// public record A {
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "A").WithArguments("A.Equals(object?)", "object.Equals(object)", "int").WithLocation(2, 15),
// (2,15): error CS0518: Predefined type 'System.Type' is not defined or imported
// public record A {
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 15),
// (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported
// public record A {
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A {
}").WithArguments("System.Exception").WithLocation(2, 1),
// (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported
// public record A {
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A {
}").WithArguments("System.Exception").WithLocation(2, 1),
// (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported
// public record A {
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A {
}").WithArguments("System.Exception").WithLocation(2, 1),
// error CS0518: Predefined type 'System.Attribute' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Attribute' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Byte' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Attribute' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Byte' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1),
// (2,1): error CS0656: Missing compiler required member 'System.Type.GetTypeFromHandle'
// public record A {
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A {
}").WithArguments("System.Type", "GetTypeFromHandle").WithLocation(2, 1),
// (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.GetHashCode'
// public record A {
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A {
}").WithArguments("System.Collections.Generic.EqualityComparer`1", "GetHashCode").WithLocation(2, 1),
// (2,1): error CS0656: Missing compiler required member 'System.Type.op_Equality'
// public record A {
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A {
}").WithArguments("System.Type", "op_Equality").WithLocation(2, 1)
);
}
[Fact]
public void ObjectEquals_06()
{
var source =
@"record A
{
public static new bool Equals(object obj) => throw null;
}
record B : A;
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (3,28): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types
// public static new bool Equals(object obj) => throw null;
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(3, 28)
);
}
[Fact]
public void ObjectGetHashCode_01()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public newslot hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source1 = @"
public record B : A {
}";
var source2 = @"
public record B : A {
public override int GetHashCode() => 0;
}";
var source3 = @"
public record C : B {
}
";
var source4 = @"
public record C : B {
public override int GetHashCode() => 0;
}
";
var comp = CreateCompilationWithIL(new[] { source1, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'.
// public record B : A {
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "B").WithArguments("B.GetHashCode()").WithLocation(2, 15)
);
comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (3,25): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'.
// public override int GetHashCode() => 0;
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("B.GetHashCode()").WithLocation(3, 25)
);
comp = CreateCompilationWithIL(new[] { source1 + source3, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'.
// public record B : A {
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "B").WithArguments("B.GetHashCode()").WithLocation(2, 15)
);
comp = CreateCompilationWithIL(new[] { source1 + source4, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'.
// public record B : A {
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "B").WithArguments("B.GetHashCode()").WithLocation(2, 15)
);
comp = CreateCompilationWithIL(new[] { source2 + source3, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (3,25): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'.
// public override int GetHashCode() => 0;
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("B.GetHashCode()").WithLocation(3, 25)
);
comp = CreateCompilationWithIL(new[] { source2 + source4, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (3,25): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'.
// public override int GetHashCode() => 0;
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("B.GetHashCode()").WithLocation(3, 25)
);
}
[Fact]
public void ObjectGetHashCode_02()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public newslot hidebysig
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source1 = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source1, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0506: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is not marked virtual, abstract, or override
// public record B : A {
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(2, 15)
);
var source2 = @"
public record B : A {
public override int GetHashCode() => throw null;
}";
comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (3,25): error CS0506: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is not marked virtual, abstract, or override
// public override int GetHashCode() => throw null;
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "GetHashCode").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(3, 25)
);
}
[Fact]
public void ObjectGetHashCode_03()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public newslot hidebysig virtual
instance bool GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0508: 'B.GetHashCode()': return type must be 'bool' to match overridden member 'A.GetHashCode()'
// public record B : A {
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()", "bool").WithLocation(2, 15)
);
var source2 = @"
public record B : A {
public override int GetHashCode() => throw null;
}";
comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (3,25): error CS0508: 'B.GetHashCode()': return type must be 'bool' to match overridden member 'A.GetHashCode()'
// public override int GetHashCode() => throw null;
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "GetHashCode").WithArguments("B.GetHashCode()", "A.GetHashCode()", "bool").WithLocation(3, 25)
);
}
[Fact]
public void ObjectGetHashCode_04()
{
var source =
@"record A
{
public override bool GetHashCode() => throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (3,26): error CS0508: 'A.GetHashCode()': return type must be 'int' to match overridden member 'object.GetHashCode()'
// public override bool GetHashCode() => throw null;
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "GetHashCode").WithArguments("A.GetHashCode()", "object.GetHashCode()", "int").WithLocation(3, 26)
);
}
[Fact]
public void ObjectGetHashCode_05()
{
var source =
@"record A
{
public new int GetHashCode() => throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (3,20): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'.
// public new int GetHashCode() => throw null;
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(3, 20)
);
}
[Fact]
public void ObjectGetHashCode_06()
{
var source =
@"record A
{
public static new int GetHashCode() => throw null;
}
record B : A;
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (3,27): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'.
// public static new int GetHashCode() => throw null;
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(3, 27),
// (6,8): error CS0506: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is not marked virtual, abstract, or override
// record B : A;
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(6, 8)
);
}
[Fact]
public void ObjectGetHashCode_07()
{
var source =
@"record A
{
public new int GetHashCode => throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (3,20): error CS0102: The type 'A' already contains a definition for 'GetHashCode'
// public new int GetHashCode => throw null;
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "GetHashCode").WithArguments("A", "GetHashCode").WithLocation(3, 20)
);
}
[Fact]
public void ObjectGetHashCode_08()
{
var source =
@"record A
{
public new void GetHashCode() => throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (3,21): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'.
// public new void GetHashCode() => throw null;
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(3, 21)
);
}
[Fact]
public void ObjectGetHashCode_09()
{
var source =
@"record A
{
public void GetHashCode(int x) => throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics();
Assert.Equal("System.Int32 A.GetHashCode()", comp.GetMembers("A.GetHashCode").First().ToTestDisplayString());
}
[Fact]
public void ObjectGetHashCode_10()
{
var source =
@"
record A
{
public sealed override int GetHashCode() => throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (4,32): error CS8870: 'A.GetHashCode()' cannot be sealed because containing record is not sealed.
// public sealed override int GetHashCode() => throw null;
Diagnostic(ErrorCode.ERR_SealedAPIInRecord, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(4, 32)
);
}
[Fact]
public void ObjectGetHashCode_11()
{
var source =
@"
sealed record A
{
public sealed override int GetHashCode() => throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics();
}
[Fact]
public void ObjectGetHashCode_12()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public final hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0239: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is sealed
// public record B : A {
Diagnostic(ErrorCode.ERR_CantOverrideSealed, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(2, 15)
);
var source2 = @"
public record B : A {
public override int GetHashCode() => throw null;
}";
comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (3,25): error CS0239: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is sealed
// public override int GetHashCode() => throw null;
Diagnostic(ErrorCode.ERR_CantOverrideSealed, "GetHashCode").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(3, 25)
);
}
[Fact]
public void ObjectGetHashCode_13()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public newslot hidebysig virtual
instance class A GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source2 = @"
public record B : A {
public override A GetHashCode() => default;
}";
var comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (3,23): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'.
// public override A GetHashCode() => default;
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("B.GetHashCode()").WithLocation(3, 23)
);
}
[Fact]
public void ObjectGetHashCode_14()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public newslot hidebysig virtual
instance class A GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance string ToString () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source2 = @"
public record B : A {
public override B GetHashCode() => default;
}";
var comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (3,23): error CS8830: 'B.GetHashCode()': Target runtime doesn't support covariant return types in overrides. Return type must be 'A' to match overridden member 'A.GetHashCode()'
// public override B GetHashCode() => default;
Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportCovariantReturnsOfClasses, "GetHashCode").WithArguments("B.GetHashCode()", "A.GetHashCode()", "A").WithLocation(3, 23)
);
}
[Fact]
public void ObjectGetHashCode_15()
{
var source0 =
@"namespace System
{
public class Object
{
public virtual bool Equals(object other) => false;
public virtual Something GetHashCode() => default;
public virtual string ToString() => """";
}
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Char { }
public struct Int32 { }
public interface IEquatable<T>
{
bool Equals(T other);
}
}
namespace System.Text
{
public class StringBuilder
{
public StringBuilder Append(string s) => null;
public StringBuilder Append(char c) => null;
public StringBuilder Append(object o) => null;
}
}
public class Something
{
}
";
var comp = CreateEmptyCompilation(source0);
comp.VerifyDiagnostics();
var ref0 = comp.EmitToImageReference();
var source1 =
@"
public record A {
public override Something GetHashCode() => default;
}
";
comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (3,31): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'.
// public override Something GetHashCode() => default;
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(3, 31),
// (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported
// public record A {
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A {
public override Something GetHashCode() => default;
}").WithArguments("System.Exception").WithLocation(2, 1),
// (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported
// public record A {
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A {
public override Something GetHashCode() => default;
}").WithArguments("System.Exception").WithLocation(2, 1),
// (2,15): error CS0518: Predefined type 'System.Type' is not defined or imported
// public record A {
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 15),
// error CS0518: Predefined type 'System.Attribute' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Attribute' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Byte' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Attribute' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Byte' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1),
// (2,1): error CS0656: Missing compiler required member 'System.Type.GetTypeFromHandle'
// public record A {
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A {
public override Something GetHashCode() => default;
}").WithArguments("System.Type", "GetTypeFromHandle").WithLocation(2, 1),
// (2,1): error CS0656: Missing compiler required member 'System.Type.op_Equality'
// public record A {
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A {
public override Something GetHashCode() => default;
}").WithArguments("System.Type", "op_Equality").WithLocation(2, 1)
);
}
[Fact]
public void ObjectGetHashCode_16()
{
var source0 =
@"namespace System
{
public class Object
{
public virtual bool Equals(object other) => false;
public virtual bool GetHashCode() => default;
public virtual string ToString() => """";
}
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Char { }
public struct Int32 { }
public interface IEquatable<T>
{
bool Equals(T other);
}
}
namespace System.Text
{
public class StringBuilder
{
public StringBuilder Append(string s) => null;
public StringBuilder Append(char c) => null;
public StringBuilder Append(object o) => null;
}
}
";
var comp = CreateEmptyCompilation(source0);
comp.VerifyDiagnostics();
var ref0 = comp.EmitToImageReference();
var source1 =
@"
public record A {
public override bool GetHashCode() => default;
}
";
comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (3,26): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'.
// public override bool GetHashCode() => default;
Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(3, 26),
// (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported
// public record A {
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A {
public override bool GetHashCode() => default;
}").WithArguments("System.Exception").WithLocation(2, 1),
// (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported
// public record A {
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A {
public override bool GetHashCode() => default;
}").WithArguments("System.Exception").WithLocation(2, 1),
// (2,15): error CS0518: Predefined type 'System.Type' is not defined or imported
// public record A {
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 15),
// error CS0518: Predefined type 'System.Attribute' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Attribute' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Byte' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Attribute' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Byte' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1),
// (2,1): error CS0656: Missing compiler required member 'System.Type.GetTypeFromHandle'
// public record A {
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A {
public override bool GetHashCode() => default;
}").WithArguments("System.Type", "GetTypeFromHandle").WithLocation(2, 1),
// (2,1): error CS0656: Missing compiler required member 'System.Type.op_Equality'
// public record A {
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A {
public override bool GetHashCode() => default;
}").WithArguments("System.Type", "op_Equality").WithLocation(2, 1)
);
}
[Fact]
public void ObjectGetHashCode_17()
{
var source0 =
@"namespace System
{
public class Object
{
public virtual bool Equals(object other) => false;
public virtual bool GetHashCode() => default;
public virtual string ToString() => """";
}
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Char { }
public struct Int32 { }
public interface IEquatable<T>
{
bool Equals(T other);
}
}
namespace System.Text
{
public class StringBuilder
{
public StringBuilder Append(string s) => null;
public StringBuilder Append(char c) => null;
public StringBuilder Append(object o) => null;
}
}
";
var comp = CreateEmptyCompilation(source0);
comp.VerifyDiagnostics();
var ref0 = comp.EmitToImageReference();
var source1 =
@"
public record A {
}
";
comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0508: 'A.GetHashCode()': return type must be 'bool' to match overridden member 'object.GetHashCode()'
// public record A {
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "A").WithArguments("A.GetHashCode()", "object.GetHashCode()", "bool").WithLocation(2, 15),
// (2,15): error CS0518: Predefined type 'System.Type' is not defined or imported
// public record A {
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 15),
// (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported
// public record A {
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A {
}").WithArguments("System.Exception").WithLocation(2, 1),
// (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported
// public record A {
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A {
}").WithArguments("System.Exception").WithLocation(2, 1),
// (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported
// public record A {
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A {
}").WithArguments("System.Exception").WithLocation(2, 1),
// error CS0518: Predefined type 'System.Attribute' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Attribute' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Byte' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Attribute' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Byte' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1),
// (2,1): error CS0656: Missing compiler required member 'System.Type.GetTypeFromHandle'
// public record A {
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A {
}").WithArguments("System.Type", "GetTypeFromHandle").WithLocation(2, 1),
// (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.GetHashCode'
// public record A {
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A {
}").WithArguments("System.Collections.Generic.EqualityComparer`1", "GetHashCode").WithLocation(2, 1),
// (2,1): error CS0656: Missing compiler required member 'System.Type.op_Equality'
// public record A {
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A {
}").WithArguments("System.Type", "op_Equality").WithLocation(2, 1)
);
}
[Fact]
public void BaseEquals_01()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0506: 'B.Equals(A?)': cannot override inherited member 'A.Equals(A)' because it is not marked virtual, abstract, or override
// public record B : A {
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.Equals(A?)", "A.Equals(A)").WithLocation(2, 15)
);
}
[Fact]
public void BaseEquals_02()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot final virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0506: 'B.Equals(A?)': cannot override inherited member 'A.Equals(A)' because it is not marked virtual, abstract, or override
// public record B : A {
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.Equals(A?)", "A.Equals(A)").WithLocation(2, 15)
);
}
[Fact]
public void BaseEquals_03()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance int32 Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance string ToString () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0508: 'B.Equals(A?)': return type must be 'int' to match overridden member 'A.Equals(A)'
// public record B : A {
Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "B").WithArguments("B.Equals(A?)", "A.Equals(A)", "int").WithLocation(2, 15)
);
}
[Fact]
public void BaseEquals_04()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public newslot virtual
instance bool Equals (
class B ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
.class public auto ansi beforefieldinit B
extends A
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public final virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class B ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method B::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type B::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class B
";
var source = @"
public record C : B {
}";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS8871: 'C.Equals(B?)' does not override expected method from 'B'.
// public record C : B {
Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseMethod, "C").WithArguments("C.Equals(B?)", "B").WithLocation(2, 15)
);
}
[Fact]
public void BaseEquals_05()
{
var source =
@"
record A
{
}
record B : A
{
public override bool Equals(A x) => throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (8,26): error CS0111: Type 'B' already defines a member called 'Equals' with the same parameter types
// public override bool Equals(A x) => throw null;
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "B").WithLocation(8, 26)
);
}
[Fact]
public void RecordEquals_01()
{
var source =
@"
abstract record A
{
internal static bool Report(string s) { System.Console.WriteLine(s); return false; }
public abstract bool Equals(A x);
}
record B : A
{
public virtual bool Equals(B other) => Report(""B.Equals(B)"");
}
class Program
{
static void Main()
{
A a1 = new B();
A a2 = new B();
System.Console.WriteLine(a1.Equals(a2));
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"
B.Equals(B)
False
").VerifyDiagnostics(
// (5,26): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode'
// public abstract bool Equals(A x);
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(5, 26),
// (9,25): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode'
// public virtual bool Equals(B other) => Report("B.Equals(B)");
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 25)
);
}
[Fact]
public void RecordEquals_02()
{
var source =
@"
abstract record A
{
internal static bool Report(string s) { System.Console.WriteLine(s); return false; }
public abstract bool Equals(B x);
}
record B : A
{
public override bool Equals(B other) => Report(""B.Equals(B)"");
}
class Program
{
static void Main()
{
A a1 = new B();
B b2 = new B();
System.Console.WriteLine(a1.Equals(b2));
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"
B.Equals(B)
False
").VerifyDiagnostics(
// (9,26): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode'
// public override bool Equals(B other) => Report("B.Equals(B)");
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 26)
);
var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single();
Assert.Equal("System.Boolean A.Equals(A? other)", recordEquals.ToTestDisplayString());
Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility);
Assert.False(recordEquals.IsAbstract);
Assert.True(recordEquals.IsVirtual);
Assert.False(recordEquals.IsOverride);
Assert.False(recordEquals.IsSealed);
Assert.True(recordEquals.IsImplicitlyDeclared);
}
[Fact]
public void RecordEquals_03()
{
var source =
@"
abstract record A
{
internal static bool Report(string s) { System.Console.WriteLine(s); return false; }
public abstract bool Equals(B x);
}
record B : A
{
public sealed override bool Equals(B other) => Report(""B.Equals(B)"");
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (9,33): error CS8872: 'B.Equals(B)' must allow overriding because the containing record is not sealed.
// public sealed override bool Equals(B other) => Report("B.Equals(B)");
Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "Equals").WithArguments("B.Equals(B)").WithLocation(9, 33),
// (9,33): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode'
// public sealed override bool Equals(B other) => Report("B.Equals(B)");
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 33)
);
}
[Fact]
public void RecordEquals_04()
{
var source =
@"
abstract record A
{
internal static bool Report(string s) { System.Console.WriteLine(s); return false; }
public abstract bool Equals(B x);
}
sealed record B : A
{
public sealed override bool Equals(B other) => Report(""B.Equals(B)"");
}
class Program
{
static void Main()
{
A a1 = new B();
B b2 = new B();
System.Console.WriteLine(a1.Equals(b2));
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"
B.Equals(B)
False
").VerifyDiagnostics(
// (9,33): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode'
// public sealed override bool Equals(B other) => Report("B.Equals(B)");
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 33)
);
var copyCtor = comp.GetMember<NamedTypeSymbol>("A").InstanceConstructors.Where(c => c.ParameterCount == 1).Single();
Assert.Equal(Accessibility.Protected, copyCtor.DeclaredAccessibility);
Assert.False(copyCtor.IsOverride);
Assert.False(copyCtor.IsVirtual);
Assert.False(copyCtor.IsAbstract);
Assert.False(copyCtor.IsSealed);
Assert.True(copyCtor.IsImplicitlyDeclared);
copyCtor = comp.GetMember<NamedTypeSymbol>("B").InstanceConstructors.Where(c => c.ParameterCount == 1).Single();
Assert.Equal(Accessibility.Private, copyCtor.DeclaredAccessibility);
Assert.False(copyCtor.IsOverride);
Assert.False(copyCtor.IsVirtual);
Assert.False(copyCtor.IsAbstract);
Assert.False(copyCtor.IsSealed);
Assert.True(copyCtor.IsImplicitlyDeclared);
}
[Fact]
public void RecordEquals_05()
{
var source =
@"
abstract record A
{
internal static bool Report(string s) { System.Console.WriteLine(s); return false; }
public abstract bool Equals(B x);
}
abstract record B : A
{
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (7,17): error CS0533: 'B.Equals(B?)' hides inherited abstract member 'A.Equals(B)'
// abstract record B : A
Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "B").WithArguments("B.Equals(B?)", "A.Equals(B)").WithLocation(7, 17)
);
var recordEquals = comp.GetMembers("B.Equals").OfType<SynthesizedRecordEquals>().Single();
Assert.Equal("System.Boolean B.Equals(B? other)", recordEquals.ToTestDisplayString());
Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility);
Assert.False(recordEquals.IsAbstract);
Assert.True(recordEquals.IsVirtual);
Assert.False(recordEquals.IsOverride);
Assert.False(recordEquals.IsSealed);
Assert.True(recordEquals.IsImplicitlyDeclared);
}
[Theory]
[InlineData("")]
[InlineData("sealed ")]
public void RecordEquals_06(string modifiers)
{
var source =
@"
abstract record A
{
internal static bool Report(string s) { System.Console.WriteLine(s); return false; }
public abstract bool Equals(B x);
}
" + modifiers + @"
record B : A
{
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (8,8): error CS0534: 'B' does not implement inherited abstract member 'A.Equals(B)'
// record B : A
Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.Equals(B)").WithLocation(8, 8)
);
}
[Theory]
[InlineData("")]
[InlineData("sealed ")]
public void RecordEquals_07(string modifiers)
{
var source =
@"
abstract record A
{
internal static bool Report(string s) { System.Console.WriteLine(s); return false; }
public virtual bool Equals(B x) => Report(""A.Equals(B)"");
}
" + modifiers + @"
record B : A
{
}
class Program
{
static void Main()
{
A a1 = new B();
B b2 = new B();
System.Console.WriteLine(a1.Equals(b2));
System.Console.WriteLine(b2.Equals(a1));
System.Console.WriteLine(b2.Equals((B)a1));
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"
A.Equals(B)
False
True
True
").VerifyDiagnostics();
}
[Theory]
[InlineData("")]
[InlineData("sealed ")]
public void RecordEquals_08(string modifiers)
{
var source =
@"
abstract record A
{
internal static bool Report(string s) { System.Console.WriteLine(s); return false; }
public abstract bool Equals(C x);
}
abstract record B : A
{
public override bool Equals(C x) => Report(""B.Equals(C)"");
}
" + modifiers + @"
record C : B
{
}
class Program
{
static void Main()
{
A a1 = new C();
C c2 = new C();
System.Console.WriteLine(a1.Equals(c2));
System.Console.WriteLine(c2.Equals(a1));
System.Console.WriteLine(c2.Equals((C)a1));
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"
B.Equals(C)
False
True
True
").VerifyDiagnostics();
var clone = comp.GetMember<MethodSymbol>("A." + WellKnownMemberNames.CloneMethodName);
Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility);
Assert.False(clone.IsOverride);
Assert.False(clone.IsVirtual);
Assert.True(clone.IsAbstract);
Assert.False(clone.IsSealed);
Assert.True(clone.IsImplicitlyDeclared);
clone = comp.GetMember<MethodSymbol>("B." + WellKnownMemberNames.CloneMethodName);
Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility);
Assert.True(clone.IsOverride);
Assert.False(clone.IsVirtual);
Assert.True(clone.IsAbstract);
Assert.False(clone.IsSealed);
Assert.True(clone.IsImplicitlyDeclared);
clone = comp.GetMember<MethodSymbol>("C." + WellKnownMemberNames.CloneMethodName);
Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility);
Assert.True(clone.IsOverride);
Assert.False(clone.IsVirtual);
Assert.False(clone.IsAbstract);
Assert.False(clone.IsSealed);
Assert.True(clone.IsImplicitlyDeclared);
}
[Theory]
[InlineData("")]
[InlineData("sealed ")]
public void RecordEquals_09(string modifiers)
{
var source =
@"
abstract record A
{
internal static bool Report(string s) { System.Console.WriteLine(s); return false; }
public bool Equals(B x) => Report(""A.Equals(B)"");
}
" + modifiers + @"
record B : A
{
}
class Program
{
static void Main()
{
A a1 = new B();
B b2 = new B();
System.Console.WriteLine(a1.Equals(b2));
System.Console.WriteLine(b2.Equals(a1));
System.Console.WriteLine(b2.Equals((B)a1));
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"
A.Equals(B)
False
True
True
").VerifyDiagnostics();
}
[Theory]
[InlineData("protected")]
[InlineData("internal")]
[InlineData("private protected")]
[InlineData("internal protected")]
public void RecordEquals_10(string accessibility)
{
var source =
$@"
record A
{{
{ accessibility } virtual bool Equals(A x)
=> throw null;
bool System.IEquatable<A>.Equals(A x) => throw null;
}}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (4,...): error CS8873: Record member 'A.Equals(A)' must be public.
// { accessibility } virtual bool Equals(A x)
Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 19 + accessibility.Length),
// (4,...): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode'
// { accessibility } virtual bool Equals(A x)
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 19 + accessibility.Length)
);
}
[Theory]
[InlineData("")]
[InlineData("private")]
public void RecordEquals_11(string accessibility)
{
var source =
$@"
record A
{{
{ accessibility } virtual bool Equals(A x)
=> throw null;
bool System.IEquatable<A>.Equals(A x) => throw null;
}}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (4,...): error CS0621: 'A.Equals(A)': virtual or abstract members cannot be private
// virtual bool Equals(A x)
Diagnostic(ErrorCode.ERR_VirtualPrivate, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 19 + accessibility.Length),
// (4,...): error CS8873: Record member 'A.Equals(A)' must be public.
// { accessibility } virtual bool Equals(A x)
Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 19 + accessibility.Length),
// (4,...): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode'
// virtual bool Equals(A x)
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 19 + accessibility.Length)
);
}
[Fact]
public void RecordEquals_12()
{
var source =
@"
record A
{
internal static bool Report(string s) { System.Console.WriteLine(s); return false; }
public virtual bool Equals(B other) => Report(""A.Equals(B)"");
}
class B
{
}
class Program
{
static void Main()
{
A a1 = new A();
A a2 = new A();
System.Console.WriteLine(a1.Equals(a2));
System.Console.WriteLine(a1.Equals((object)a2));
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"
True
True
").VerifyDiagnostics();
var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single();
Assert.Equal("System.Boolean A.Equals(A? other)", recordEquals.ToTestDisplayString());
Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility);
Assert.False(recordEquals.IsAbstract);
Assert.True(recordEquals.IsVirtual);
Assert.False(recordEquals.IsOverride);
Assert.False(recordEquals.IsSealed);
Assert.True(recordEquals.IsImplicitlyDeclared);
}
[Fact]
public void RecordEquals_13()
{
var source =
@"
record A
{
public virtual int Equals(A other)
=> throw null;
bool System.IEquatable<A>.Equals(A x) => throw null;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (4,24): error CS8874: Record member 'A.Equals(A)' must return 'bool'.
// public virtual int Equals(A other)
Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "Equals").WithArguments("A.Equals(A)", "bool").WithLocation(4, 24),
// (4,24): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode'
// public virtual int Equals(A other)
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24)
);
}
[Fact]
public void RecordEquals_14()
{
var source =
@"
record A
{
public virtual bool Equals(A other)
=> throw null;
System.Boolean System.IEquatable<A>.Equals(A x) => throw null;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.MakeTypeMissing(SpecialType.System_Boolean);
comp.VerifyEmitDiagnostics(
// (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported
// record A
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record A
{
public virtual bool Equals(A other)
=> throw null;
System.Boolean System.IEquatable<A>.Equals(A x) => throw null;
}").WithArguments("System.Boolean").WithLocation(2, 1),
// (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported
// record A
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record A
{
public virtual bool Equals(A other)
=> throw null;
System.Boolean System.IEquatable<A>.Equals(A x) => throw null;
}").WithArguments("System.Boolean").WithLocation(2, 1),
// (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported
// record A
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record A
{
public virtual bool Equals(A other)
=> throw null;
System.Boolean System.IEquatable<A>.Equals(A x) => throw null;
}").WithArguments("System.Boolean").WithLocation(2, 1),
// (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported
// record A
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record A
{
public virtual bool Equals(A other)
=> throw null;
System.Boolean System.IEquatable<A>.Equals(A x) => throw null;
}").WithArguments("System.Boolean").WithLocation(2, 1),
// (2,8): error CS0518: Predefined type 'System.Boolean' is not defined or imported
// record A
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 8),
// (2,8): error CS0518: Predefined type 'System.Boolean' is not defined or imported
// record A
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 8),
// (2,8): error CS0518: Predefined type 'System.Boolean' is not defined or imported
// record A
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 8),
// (2,8): error CS0518: Predefined type 'System.Boolean' is not defined or imported
// record A
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 8),
// (4,20): error CS0518: Predefined type 'System.Boolean' is not defined or imported
// public virtual bool Equals(A other)
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "bool").WithArguments("System.Boolean").WithLocation(4, 20),
// (4,25): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode'
// public virtual bool Equals(A other)
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 25)
);
}
[Fact]
public void RecordEquals_15()
{
var source =
@"
record A
{
public virtual Boolean Equals(A other)
=> throw null;
bool System.IEquatable<A>.Equals(A x) => throw null;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (4,20): error CS0246: The type or namespace name 'Boolean' could not be found (are you missing a using directive or an assembly reference?)
// public virtual Boolean Equals(A other)
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Boolean").WithArguments("Boolean").WithLocation(4, 20),
// (4,28): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode'
// public virtual Boolean Equals(A other)
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 28)
);
}
[Fact]
public void RecordEquals_16()
{
var source =
@"
abstract record A
{
}
record B : A
{
}
class Program
{
static void Main()
{
A a1 = new B();
B b2 = new B();
System.Console.WriteLine(a1.Equals(b2));
System.Console.WriteLine(b2.Equals(a1));
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"
True
True
").VerifyDiagnostics();
var recordEquals = comp.GetMembers("B.Equals").OfType<SynthesizedRecordEquals>().Single();
Assert.Equal("System.Boolean B.Equals(B? other)", recordEquals.ToTestDisplayString());
Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility);
Assert.False(recordEquals.IsAbstract);
Assert.True(recordEquals.IsVirtual);
Assert.False(recordEquals.IsOverride);
Assert.False(recordEquals.IsSealed);
Assert.True(recordEquals.IsImplicitlyDeclared);
}
[Fact]
public void RecordEquals_17()
{
var source =
@"
abstract record A
{
}
sealed record B : A
{
}
class Program
{
static void Main()
{
A a1 = new B();
B b2 = new B();
System.Console.WriteLine(a1.Equals(b2));
System.Console.WriteLine(b2.Equals(a1));
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"
True
True
").VerifyDiagnostics();
var recordEquals = comp.GetMembers("B.Equals").OfType<SynthesizedRecordEquals>().Single();
Assert.Equal("System.Boolean B.Equals(B? other)", recordEquals.ToTestDisplayString());
Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility);
Assert.False(recordEquals.IsAbstract);
Assert.False(recordEquals.IsVirtual);
Assert.False(recordEquals.IsOverride);
Assert.False(recordEquals.IsSealed);
Assert.True(recordEquals.IsImplicitlyDeclared);
}
[Fact]
public void RecordEquals_18()
{
var source =
@"
sealed record A
{
}
class Program
{
static void Main()
{
A a1 = new A();
A a2 = new A();
System.Console.WriteLine(a1.Equals(a2));
System.Console.WriteLine(a2.Equals(a1));
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"
True
True
").VerifyDiagnostics();
var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single();
Assert.Equal("System.Boolean A.Equals(A? other)", recordEquals.ToTestDisplayString());
Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility);
Assert.False(recordEquals.IsAbstract);
Assert.False(recordEquals.IsVirtual);
Assert.False(recordEquals.IsOverride);
Assert.False(recordEquals.IsSealed);
Assert.True(recordEquals.IsImplicitlyDeclared);
}
[Fact]
public void RecordEquals_19()
{
var source =
@"
record A
{
public static bool Equals(A x) => throw null;
}
record B : A;
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (2,8): error CS0736: 'A' does not implement instance interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement the interface member because it is static.
// record A
Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)").WithLocation(2, 8),
// (4,24): error CS8872: 'A.Equals(A)' must allow overriding because the containing record is not sealed.
// public static bool Equals(A x) => throw null;
Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 24),
// (4,24): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode'
// public static bool Equals(A x) => throw null;
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24),
// (7,8): error CS0506: 'B.Equals(A?)': cannot override inherited member 'A.Equals(A)' because it is not marked virtual, abstract, or override
// record B : A;
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.Equals(A?)", "A.Equals(A)").WithLocation(7, 8)
);
}
[Fact]
public void RecordEquals_20()
{
var source =
@"
sealed record A
{
public static bool Equals(A x) => throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0736: 'A' does not implement instance interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement the interface member because it is static.
// sealed record A
Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)").WithLocation(2, 15),
// (4,24): error CS8877: Record member 'A.Equals(A)' may not be static.
// public static bool Equals(A x) => throw null;
Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 24),
// (4,24): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode'
// public static bool Equals(A x) => throw null;
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24)
);
}
[Fact]
public void EqualityContract_01()
{
var source =
@"
abstract record A
{
internal static bool Report(string s) { System.Console.WriteLine(s); return false; }
protected abstract System.Type EqualityContract { get; }
}
record B : A
{
protected override System.Type EqualityContract
{
get
{
Report(""B.EqualityContract"");
return typeof(B);
}
}
}
class Program
{
static void Main()
{
A a1 = new B();
A a2 = new B();
System.Console.WriteLine(a1.Equals(a2));
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"
B.EqualityContract
B.EqualityContract
True
").VerifyDiagnostics();
}
[Fact]
public void EqualityContract_02()
{
var source =
@"
abstract record A
{
internal static bool Report(string s) { System.Console.WriteLine(s); return false; }
protected abstract System.Type EqualityContract { get; }
}
record B : A
{
protected sealed override System.Type EqualityContract
{
get
{
Report(""B.EqualityContract"");
return typeof(B);
}
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (9,43): error CS8872: 'B.EqualityContract' must allow overriding because the containing record is not sealed.
// protected sealed override System.Type EqualityContract
Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("B.EqualityContract").WithLocation(9, 43)
);
}
[Fact]
public void EqualityContract_03()
{
var source =
@"
abstract record A
{
internal static bool Report(string s) { System.Console.WriteLine(s); return false; }
protected abstract System.Type EqualityContract { get; }
}
sealed record B : A
{
protected sealed override System.Type EqualityContract
{
get
{
Report(""B.EqualityContract"");
return typeof(B);
}
}
}
class Program
{
static void Main()
{
A a1 = new B();
A a2 = new B();
System.Console.WriteLine(a1.Equals(a2));
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"
B.EqualityContract
B.EqualityContract
True
").VerifyDiagnostics();
}
[Theory]
[InlineData("")]
[InlineData("sealed ")]
public void EqualityContract_04(string modifiers)
{
var source =
@"
abstract record A
{
internal static bool Report(string s) { System.Console.WriteLine(s); return false; }
protected virtual System.Type EqualityContract
{
get
{
Report(""A.EqualityContract"");
return typeof(B);
}
}
}
" + modifiers + @"
record B : A
{
}
class Program
{
static void Main()
{
A a1 = new B();
B b2 = new B();
System.Console.WriteLine(a1.Equals(b2));
System.Console.WriteLine(b2.Equals(a1));
System.Console.WriteLine(b2.Equals((B)a1));
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"
True
True
True
").VerifyDiagnostics();
var equalityContract = comp.GetMembers("B.EqualityContract").OfType<SynthesizedRecordEqualityContractProperty>().Single();
Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString());
Assert.Equal(Accessibility.Protected, equalityContract.DeclaredAccessibility);
Assert.False(equalityContract.IsAbstract);
Assert.False(equalityContract.IsVirtual);
Assert.True(equalityContract.IsOverride);
Assert.False(equalityContract.IsSealed);
Assert.True(equalityContract.IsImplicitlyDeclared);
Assert.Empty(equalityContract.DeclaringSyntaxReferences);
var equalityContractGet = equalityContract.GetMethod;
Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString());
Assert.Equal(Accessibility.Protected, equalityContractGet!.DeclaredAccessibility);
Assert.False(equalityContractGet.IsAbstract);
Assert.False(equalityContractGet.IsVirtual);
Assert.True(equalityContractGet.IsOverride);
Assert.False(equalityContractGet.IsSealed);
Assert.True(equalityContractGet.IsImplicitlyDeclared);
Assert.Empty(equalityContractGet.DeclaringSyntaxReferences);
}
[Theory]
[InlineData("public")]
[InlineData("internal")]
[InlineData("private protected")]
[InlineData("internal protected")]
public void EqualityContract_05(string accessibility)
{
var source =
$@"
record A
{{
{ accessibility } virtual System.Type EqualityContract
=> throw null;
}}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (4,...): error CS8875: Record member 'A.EqualityContract' must be protected.
// { accessibility } virtual System.Type EqualityContract
Diagnostic(ErrorCode.ERR_NonProtectedAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(4, 26 + accessibility.Length)
);
}
[Theory]
[InlineData("")]
[InlineData("private")]
public void EqualityContract_06(string accessibility)
{
var source =
$@"
record A
{{
{ accessibility } virtual System.Type EqualityContract
=> throw null;
bool System.IEquatable<A>.Equals(A x) => throw null;
}}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (4,...): error CS0621: 'A.EqualityContract': virtual or abstract members cannot be private
// { accessibility } virtual System.Type EqualityContract
Diagnostic(ErrorCode.ERR_VirtualPrivate, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(4, 26 + accessibility.Length),
// (4,...): error CS8875: Record member 'A.EqualityContract' must be protected.
// { accessibility } virtual System.Type EqualityContract
Diagnostic(ErrorCode.ERR_NonProtectedAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(4, 26 + accessibility.Length)
);
}
[Theory]
[InlineData("")]
[InlineData("abstract ")]
[InlineData("sealed ")]
public void EqualityContract_07(string modifiers)
{
var source =
@"
record A
{
}
" + modifiers + @"
record B : A
{
public void PrintEqualityContract() => System.Console.WriteLine(EqualityContract);
}
";
if (modifiers != "abstract ")
{
source +=
@"
class Program
{
static void Main()
{
A a1 = new B();
B b2 = new B();
System.Console.WriteLine(a1.Equals(b2));
System.Console.WriteLine(b2.Equals(a1));
System.Console.WriteLine(b2.Equals((B)a1));
b2.PrintEqualityContract();
}
}";
}
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: modifiers == "abstract " ? TestOptions.ReleaseDll : TestOptions.ReleaseExe);
var verifier = CompileAndVerify(comp, expectedOutput: modifiers == "abstract " ? null :
@"
True
True
True
B
").VerifyDiagnostics();
var equalityContract = comp.GetMembers("B.EqualityContract").OfType<SynthesizedRecordEqualityContractProperty>().Single();
Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString());
Assert.Equal(Accessibility.Protected, equalityContract.DeclaredAccessibility);
Assert.False(equalityContract.IsAbstract);
Assert.False(equalityContract.IsVirtual);
Assert.True(equalityContract.IsOverride);
Assert.False(equalityContract.IsSealed);
Assert.True(equalityContract.IsImplicitlyDeclared);
Assert.Empty(equalityContract.DeclaringSyntaxReferences);
var equalityContractGet = equalityContract.GetMethod;
Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString());
Assert.Equal(Accessibility.Protected, equalityContractGet!.DeclaredAccessibility);
Assert.False(equalityContractGet.IsAbstract);
Assert.False(equalityContractGet.IsVirtual);
Assert.True(equalityContractGet.IsOverride);
Assert.False(equalityContractGet.IsSealed);
Assert.True(equalityContractGet.IsImplicitlyDeclared);
Assert.Empty(equalityContractGet.DeclaringSyntaxReferences);
verifier.VerifyIL("B.EqualityContract.get", @"
{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldtoken ""B""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ret
}
");
}
[Theory]
[InlineData("")]
[InlineData("abstract ")]
[InlineData("sealed ")]
public void EqualityContract_08(string modifiers)
{
var source =
modifiers + @"
record B
{
public void PrintEqualityContract() => System.Console.WriteLine(EqualityContract);
}
";
if (modifiers != "abstract ")
{
source +=
@"
class Program
{
static void Main()
{
B a1 = new B();
B b2 = new B();
System.Console.WriteLine(a1.Equals(b2));
System.Console.WriteLine(b2.Equals(a1));
System.Console.WriteLine(b2.Equals((B)a1));
b2.PrintEqualityContract();
}
}";
}
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: modifiers == "abstract " ? TestOptions.ReleaseDll : TestOptions.ReleaseExe);
var verifier = CompileAndVerify(comp, expectedOutput: modifiers == "abstract " ? null :
@"
True
True
True
B
").VerifyDiagnostics();
var equalityContract = comp.GetMembers("B.EqualityContract").OfType<SynthesizedRecordEqualityContractProperty>().Single();
Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString());
Assert.Equal(modifiers == "sealed " ? Accessibility.Private : Accessibility.Protected, equalityContract.DeclaredAccessibility);
Assert.False(equalityContract.IsAbstract);
Assert.Equal(modifiers != "sealed ", equalityContract.IsVirtual);
Assert.False(equalityContract.IsOverride);
Assert.False(equalityContract.IsSealed);
Assert.True(equalityContract.IsImplicitlyDeclared);
Assert.Empty(equalityContract.DeclaringSyntaxReferences);
var equalityContractGet = equalityContract.GetMethod;
Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString());
Assert.Equal(modifiers == "sealed " ? Accessibility.Private : Accessibility.Protected, equalityContractGet!.DeclaredAccessibility);
Assert.False(equalityContractGet.IsAbstract);
Assert.Equal(modifiers != "sealed ", equalityContractGet.IsVirtual);
Assert.False(equalityContractGet.IsOverride);
Assert.False(equalityContractGet.IsSealed);
Assert.True(equalityContractGet.IsImplicitlyDeclared);
Assert.Empty(equalityContractGet.DeclaringSyntaxReferences);
verifier.VerifyIL("B.EqualityContract.get", @"
{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldtoken ""B""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ret
}
");
}
[Fact]
public void EqualityContract_09()
{
var source =
@"
record A
{
protected virtual int EqualityContract
=> throw null;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (4,27): error CS8874: Record member 'A.EqualityContract' must return 'Type'.
// protected virtual int EqualityContract
Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("A.EqualityContract", "System.Type").WithLocation(4, 27)
);
}
[Fact]
public void EqualityContract_10()
{
var source =
@"
record A
{
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.MakeTypeMissing(WellKnownType.System_Type);
comp.VerifyEmitDiagnostics(
// (2,1): error CS0656: Missing compiler required member 'System.Type.GetTypeFromHandle'
// record A
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"record A
{
}").WithArguments("System.Type", "GetTypeFromHandle").WithLocation(2, 1),
// (2,1): error CS0656: Missing compiler required member 'System.Type.op_Equality'
// record A
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"record A
{
}").WithArguments("System.Type", "op_Equality").WithLocation(2, 1),
// (2,8): error CS0518: Predefined type 'System.Type' is not defined or imported
// record A
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 8)
);
}
[Fact]
public void EqualityContract_11()
{
var source =
@"
record A
{
protected virtual Type EqualityContract
=> throw null;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (4,23): error CS0246: The type or namespace name 'Type' could not be found (are you missing a using directive or an assembly reference?)
// protected virtual Type EqualityContract
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Type").WithArguments("Type").WithLocation(4, 23)
);
}
[Fact]
public void EqualityContract_12()
{
var source =
@"
record A
{
protected System.Type EqualityContract
=> throw null;
}
sealed record B
{
protected System.Type EqualityContract
=> throw null;
}
sealed record C
{
protected virtual System.Type EqualityContract
=> throw null;
}
record D
{
protected virtual System.Type EqualityContract
=> throw null;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (4,27): error CS8872: 'A.EqualityContract' must allow overriding because the containing record is not sealed.
// protected System.Type EqualityContract
Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(4, 27),
// (10,27): warning CS0628: 'B.EqualityContract': new protected member declared in sealed type
// protected System.Type EqualityContract
Diagnostic(ErrorCode.WRN_ProtectedInSealed, "EqualityContract").WithArguments("B.EqualityContract").WithLocation(10, 27),
// (10,27): error CS8879: Record member 'B.EqualityContract' must be private.
// protected System.Type EqualityContract
Diagnostic(ErrorCode.ERR_NonPrivateAPIInRecord, "EqualityContract").WithArguments("B.EqualityContract").WithLocation(10, 27),
// (11,12): warning CS0628: 'B.EqualityContract.get': new protected member declared in sealed type
// => throw null;
Diagnostic(ErrorCode.WRN_ProtectedInSealed, "throw null").WithArguments("B.EqualityContract.get").WithLocation(11, 12),
// (16,35): warning CS0628: 'C.EqualityContract': new protected member declared in sealed type
// protected virtual System.Type EqualityContract
Diagnostic(ErrorCode.WRN_ProtectedInSealed, "EqualityContract").WithArguments("C.EqualityContract").WithLocation(16, 35),
// (16,35): error CS8879: Record member 'C.EqualityContract' must be private.
// protected virtual System.Type EqualityContract
Diagnostic(ErrorCode.ERR_NonPrivateAPIInRecord, "EqualityContract").WithArguments("C.EqualityContract").WithLocation(16, 35),
// (17,12): error CS0549: 'C.EqualityContract.get' is a new virtual member in sealed type 'C'
// => throw null;
Diagnostic(ErrorCode.ERR_NewVirtualInSealed, "throw null").WithArguments("C.EqualityContract.get", "C").WithLocation(17, 12)
);
}
[Fact]
public void EqualityContract_13()
{
var source =
@"
record A
{}
record B : A
{
protected System.Type EqualityContract
=> throw null;
}
sealed record C : A
{
protected System.Type EqualityContract
=> throw null;
}
sealed record D : A
{
protected virtual System.Type EqualityContract
=> throw null;
}
record E : A
{
protected virtual System.Type EqualityContract
=> throw null;
}
record F : A
{
protected override System.Type EqualityContract
=> throw null;
}
record G : A
{
protected sealed override System.Type EqualityContract
=> throw null;
}
sealed record H : A
{
protected sealed override System.Type EqualityContract
=> throw null;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (7,27): error CS8876: 'B.EqualityContract' does not override expected property from 'A'.
// protected System.Type EqualityContract
Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("B.EqualityContract", "A").WithLocation(7, 27),
// (7,27): error CS8872: 'B.EqualityContract' must allow overriding because the containing record is not sealed.
// protected System.Type EqualityContract
Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("B.EqualityContract").WithLocation(7, 27),
// (7,27): warning CS0114: 'B.EqualityContract' hides inherited member 'A.EqualityContract'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.
// protected System.Type EqualityContract
Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "EqualityContract").WithArguments("B.EqualityContract", "A.EqualityContract").WithLocation(7, 27),
// (13,27): warning CS0628: 'C.EqualityContract': new protected member declared in sealed type
// protected System.Type EqualityContract
Diagnostic(ErrorCode.WRN_ProtectedInSealed, "EqualityContract").WithArguments("C.EqualityContract").WithLocation(13, 27),
// (13,27): error CS8876: 'C.EqualityContract' does not override expected property from 'A'.
// protected System.Type EqualityContract
Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("C.EqualityContract", "A").WithLocation(13, 27),
// (13,27): warning CS0114: 'C.EqualityContract' hides inherited member 'A.EqualityContract'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.
// protected System.Type EqualityContract
Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "EqualityContract").WithArguments("C.EqualityContract", "A.EqualityContract").WithLocation(13, 27),
// (14,12): warning CS0628: 'C.EqualityContract.get': new protected member declared in sealed type
// => throw null;
Diagnostic(ErrorCode.WRN_ProtectedInSealed, "throw null").WithArguments("C.EqualityContract.get").WithLocation(14, 12),
// (19,35): warning CS0628: 'D.EqualityContract': new protected member declared in sealed type
// protected virtual System.Type EqualityContract
Diagnostic(ErrorCode.WRN_ProtectedInSealed, "EqualityContract").WithArguments("D.EqualityContract").WithLocation(19, 35),
// (19,35): error CS8876: 'D.EqualityContract' does not override expected property from 'A'.
// protected virtual System.Type EqualityContract
Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("D.EqualityContract", "A").WithLocation(19, 35),
// (19,35): warning CS0114: 'D.EqualityContract' hides inherited member 'A.EqualityContract'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.
// protected virtual System.Type EqualityContract
Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "EqualityContract").WithArguments("D.EqualityContract", "A.EqualityContract").WithLocation(19, 35),
// (20,12): error CS0549: 'D.EqualityContract.get' is a new virtual member in sealed type 'D'
// => throw null;
Diagnostic(ErrorCode.ERR_NewVirtualInSealed, "throw null").WithArguments("D.EqualityContract.get", "D").WithLocation(20, 12),
// (25,35): error CS8876: 'E.EqualityContract' does not override expected property from 'A'.
// protected virtual System.Type EqualityContract
Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("E.EqualityContract", "A").WithLocation(25, 35),
// (25,35): warning CS0114: 'E.EqualityContract' hides inherited member 'A.EqualityContract'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.
// protected virtual System.Type EqualityContract
Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "EqualityContract").WithArguments("E.EqualityContract", "A.EqualityContract").WithLocation(25, 35),
// (37,43): error CS8872: 'G.EqualityContract' must allow overriding because the containing record is not sealed.
// protected sealed override System.Type EqualityContract
Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("G.EqualityContract").WithLocation(37, 43)
);
}
[Fact]
public void EqualityContract_14()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}
public record C : A {
new protected virtual System.Type EqualityContract
=> throw null;
}
public record D : A {
new protected virtual int EqualityContract
=> throw null;
}
public record E : A {
new protected virtual Type EqualityContract
=> throw null;
}
public record F : A {
protected override System.Type EqualityContract
=> throw null;
}
";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0506: 'B.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override
// public record B : A {
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.EqualityContract", "A.EqualityContract").WithLocation(2, 15),
// (6,39): error CS8876: 'C.EqualityContract' does not override expected property from 'A'.
// new protected virtual System.Type EqualityContract
Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("C.EqualityContract", "A").WithLocation(6, 39),
// (11,31): error CS8874: Record member 'D.EqualityContract' must return 'Type'.
// new protected virtual int EqualityContract
Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("D.EqualityContract", "System.Type").WithLocation(11, 31),
// (16,27): error CS0246: The type or namespace name 'Type' could not be found (are you missing a using directive or an assembly reference?)
// new protected virtual Type EqualityContract
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Type").WithArguments("Type").WithLocation(16, 27),
// (21,36): error CS0506: 'F.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override
// protected override System.Type EqualityContract
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "EqualityContract").WithArguments("F.EqualityContract", "A.EqualityContract").WithLocation(21, 36)
);
}
[Fact]
public void EqualityContract_15()
{
var source =
@"
record A
{
protected virtual int EqualityContract
=> throw null;
}
record B : A
{
}
record C : A
{
protected override System.Type EqualityContract
=> throw null;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.VerifyEmitDiagnostics(
// (4,27): error CS8874: Record member 'A.EqualityContract' must return 'Type'.
// protected virtual int EqualityContract
Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("A.EqualityContract", "System.Type").WithLocation(4, 27),
// (8,8): error CS1715: 'B.EqualityContract': type must be 'int' to match overridden member 'A.EqualityContract'
// record B : A
Diagnostic(ErrorCode.ERR_CantChangeTypeOnOverride, "B").WithArguments("B.EqualityContract", "A.EqualityContract", "int").WithLocation(8, 8),
// (14,36): error CS1715: 'C.EqualityContract': type must be 'int' to match overridden member 'A.EqualityContract'
// protected override System.Type EqualityContract
Diagnostic(ErrorCode.ERR_CantChangeTypeOnOverride, "EqualityContract").WithArguments("C.EqualityContract", "A.EqualityContract", "int").WithLocation(14, 36)
);
}
[Fact]
public void EqualityContract_16()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot final virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}
public record C : A {
new protected virtual System.Type EqualityContract
=> throw null;
}
public record D : A {
new protected virtual int EqualityContract
=> throw null;
}
public record E : A {
new protected virtual Type EqualityContract
=> throw null;
}
public record F : A {
protected override System.Type EqualityContract
=> throw null;
}
";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0506: 'B.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override
// public record B : A {
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.EqualityContract", "A.EqualityContract").WithLocation(2, 15),
// (6,39): error CS8876: 'C.EqualityContract' does not override expected property from 'A'.
// new protected virtual System.Type EqualityContract
Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("C.EqualityContract", "A").WithLocation(6, 39),
// (11,31): error CS8874: Record member 'D.EqualityContract' must return 'Type'.
// new protected virtual int EqualityContract
Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("D.EqualityContract", "System.Type").WithLocation(11, 31),
// (16,27): error CS0246: The type or namespace name 'Type' could not be found (are you missing a using directive or an assembly reference?)
// new protected virtual Type EqualityContract
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Type").WithArguments("Type").WithLocation(16, 27),
// (21,36): error CS0506: 'F.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override
// protected override System.Type EqualityContract
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "EqualityContract").WithArguments("F.EqualityContract", "A.EqualityContract").WithLocation(21, 36)
);
}
[Fact]
public void EqualityContract_17()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class A
";
var source = @"
public record B : A {
}
public record C : A {
protected virtual System.Type EqualityContract
=> throw null;
}
public record D : A {
protected virtual int EqualityContract
=> throw null;
}
public record E : A {
protected virtual Type EqualityContract
=> throw null;
}
public record F : A {
protected override System.Type EqualityContract
=> throw null;
}
";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS0115: 'B.EqualityContract': no suitable method found to override
// public record B : A {
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.EqualityContract").WithLocation(2, 15),
// (6,35): error CS8876: 'C.EqualityContract' does not override expected property from 'A'.
// protected virtual System.Type EqualityContract
Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("C.EqualityContract", "A").WithLocation(6, 35),
// (11,27): error CS8874: Record member 'D.EqualityContract' must return 'Type'.
// protected virtual int EqualityContract
Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("D.EqualityContract", "System.Type").WithLocation(11, 27),
// (16,23): error CS0246: The type or namespace name 'Type' could not be found (are you missing a using directive or an assembly reference?)
// protected virtual Type EqualityContract
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Type").WithArguments("Type").WithLocation(16, 23),
// (21,36): error CS0115: 'F.EqualityContract': no suitable method found to override
// protected override System.Type EqualityContract
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "EqualityContract").WithArguments("F.EqualityContract").WithLocation(21, 36)
);
}
[Fact]
public void EqualityContract_18()
{
var ilSource = @"
.class public auto ansi beforefieldinit A
extends System.Object
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public newslot virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual
instance class [mscorlib]System.Type get_EqualityContract () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::get_EqualityContract
.property instance class [mscorlib]System.Type EqualityContract()
{
.get instance class [mscorlib]System.Type A::get_EqualityContract()
}
} // end of class A
.class public auto ansi beforefieldinit B
extends A
{
// Methods
.method public hidebysig specialname newslot virtual
instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"'
.method public hidebysig virtual
instance bool Equals (
object other
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public hidebysig virtual
instance int32 GetHashCode () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::GetHashCode
.method public final virtual
instance bool Equals (
class A ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::Equals
.method public newslot virtual
instance bool Equals (
class B ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method B::Equals
.method family hidebysig specialname rtspecialname
instance void .ctor (
class B ''
) cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method B::.ctor
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
.maxstack 8
IL_0000: ldnull
IL_0001: throw
} // end of method A::.ctor
.method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
} // end of class B
";
var source = @"
public record C : B {
}
public record D : B {
new protected virtual System.Type EqualityContract
=> throw null;
}
public record E : B {
new protected virtual int EqualityContract
=> throw null;
}
public record F : B {
new protected virtual Type EqualityContract
=> throw null;
}
public record G : B {
protected override System.Type EqualityContract
=> throw null;
}
";
var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (2,15): error CS8876: 'C.EqualityContract' does not override expected property from 'B'.
// public record C : B {
Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "C").WithArguments("C.EqualityContract", "B").WithLocation(2, 15),
// (6,39): error CS8876: 'D.EqualityContract' does not override expected property from 'B'.
// new protected virtual System.Type EqualityContract
Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("D.EqualityContract", "B").WithLocation(6, 39),
// (11,31): error CS8874: Record member 'E.EqualityContract' must return 'Type'.
// new protected virtual int EqualityContract
Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("E.EqualityContract", "System.Type").WithLocation(11, 31),
// (16,27): error CS0246: The type or namespace name 'Type' could not be found (are you missing a using directive or an assembly reference?)
// new protected virtual Type EqualityContract
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Type").WithArguments("Type").WithLocation(16, 27),
// (21,36): error CS8876: 'G.EqualityContract' does not override expected property from 'B'.
// protected override System.Type EqualityContract
Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("G.EqualityContract", "B").WithLocation(21, 36)
);
}
[Fact]
public void EqualityContract_19()
{
var source =
@"sealed record A
{
protected static System.Type EqualityContract => throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (3,34): warning CS0628: 'A.EqualityContract': new protected member declared in sealed type
// protected static System.Type EqualityContract => throw null;
Diagnostic(ErrorCode.WRN_ProtectedInSealed, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(3, 34),
// (3,34): error CS8879: Record member 'A.EqualityContract' must be private.
// protected static System.Type EqualityContract => throw null;
Diagnostic(ErrorCode.ERR_NonPrivateAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(3, 34),
// (3,34): error CS8877: Record member 'A.EqualityContract' may not be static.
// protected static System.Type EqualityContract => throw null;
Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(3, 34),
// (3,54): warning CS0628: 'A.EqualityContract.get': new protected member declared in sealed type
// protected static System.Type EqualityContract => throw null;
Diagnostic(ErrorCode.WRN_ProtectedInSealed, "throw null").WithArguments("A.EqualityContract.get").WithLocation(3, 54)
);
}
[Fact]
public void EqualityContract_20()
{
var source =
@"sealed record A
{
private static System.Type EqualityContract => throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (3,32): error CS8877: Record member 'A.EqualityContract' may not be static.
// private static System.Type EqualityContract => throw null;
Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(3, 32)
);
}
[Fact]
public void EqualityContract_21()
{
var source =
@"
sealed record A
{
static void Main()
{
A a1 = new A();
A a2 = new A();
System.Console.WriteLine(a1.Equals(a2));
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: "True").VerifyDiagnostics();
var equalityContract = comp.GetMembers("A.EqualityContract").OfType<SynthesizedRecordEqualityContractProperty>().Single();
Assert.Equal("System.Type A.EqualityContract { get; }", equalityContract.ToTestDisplayString());
Assert.Equal(Accessibility.Private, equalityContract.DeclaredAccessibility);
Assert.False(equalityContract.IsAbstract);
Assert.False(equalityContract.IsVirtual);
Assert.False(equalityContract.IsOverride);
Assert.False(equalityContract.IsSealed);
Assert.True(equalityContract.IsImplicitlyDeclared);
Assert.Empty(equalityContract.DeclaringSyntaxReferences);
}
[Fact]
public void EqualityContract_22()
{
var source =
@"
record A;
sealed record B : A
{
static void Main()
{
A a1 = new B();
A a2 = new B();
System.Console.WriteLine(a1.Equals(a2));
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: "True").VerifyDiagnostics();
var equalityContract = comp.GetMembers("B.EqualityContract").OfType<SynthesizedRecordEqualityContractProperty>().Single();
Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString());
Assert.Equal(Accessibility.Protected, equalityContract.DeclaredAccessibility);
Assert.False(equalityContract.IsAbstract);
Assert.False(equalityContract.IsVirtual);
Assert.True(equalityContract.IsOverride);
Assert.False(equalityContract.IsSealed);
Assert.True(equalityContract.IsImplicitlyDeclared);
Assert.Empty(equalityContract.DeclaringSyntaxReferences);
}
[Fact]
public void EqualityContract_23()
{
var source =
@"
record A
{
protected static System.Type EqualityContract => throw null;
}
record B : A;
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (4,34): error CS8872: 'A.EqualityContract' must allow overriding because the containing record is not sealed.
// protected static System.Type EqualityContract => throw null;
Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(4, 34),
// (7,8): error CS0506: 'B.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override
// record B : A;
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.EqualityContract", "A.EqualityContract").WithLocation(7, 8)
);
}
[Fact]
[WorkItem(48723, "https://github.com/dotnet/roslyn/issues/48723")]
public void EqualityContract_24_SetterOnlyProperty()
{
var src = @"
record R
{
protected virtual System.Type EqualityContract { set { } }
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (4,35): error CS8906: Record equality contract property 'R.EqualityContract' must have a get accessor.
// protected virtual System.Type EqualityContract { set { } }
Diagnostic(ErrorCode.ERR_EqualityContractRequiresGetter, "EqualityContract").WithArguments("R.EqualityContract").WithLocation(4, 35)
);
}
[Fact]
[WorkItem(48723, "https://github.com/dotnet/roslyn/issues/48723")]
public void EqualityContract_24_GetterAndSetterProperty()
{
var src = @"
_ = new R() == new R2();
record R
{
protected virtual System.Type EqualityContract { get { System.Console.Write(""RAN ""); return GetType(); } set { } }
}
record R2 : R;
";
var comp = CreateCompilation(src, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "RAN");
}
[Fact]
[WorkItem(48723, "https://github.com/dotnet/roslyn/issues/48723")]
public void EqualityContract_25_SetterOnlyProperty_DerivedRecord()
{
var src = @"
record Base;
record R : Base
{
protected override System.Type EqualityContract { set { } }
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (5,36): error CS8906: Record equality contract property 'R.EqualityContract' must have a get accessor.
// protected override System.Type EqualityContract { set { } }
Diagnostic(ErrorCode.ERR_EqualityContractRequiresGetter, "EqualityContract").WithArguments("R.EqualityContract").WithLocation(5, 36),
// (5,55): error CS0546: 'R.EqualityContract.set': cannot override because 'Base.EqualityContract' does not have an overridable set accessor
// protected override System.Type EqualityContract { set { } }
Diagnostic(ErrorCode.ERR_NoSetToOverride, "set").WithArguments("R.EqualityContract.set", "Base.EqualityContract").WithLocation(5, 55)
);
}
[Fact]
[WorkItem(48723, "https://github.com/dotnet/roslyn/issues/48723")]
public void EqualityContract_26_SetterOnlyProperty_InMetadata()
{
// `record Base;` with modified EqualityContract property, method bodies simplified and nullability removed
var il = @"
.class public auto ansi beforefieldinit Base
extends [mscorlib]System.Object
implements class [mscorlib]System.IEquatable`1<class Base>
{
.method public hidebysig virtual instance string ToString () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig newslot virtual instance bool PrintMembers( class [mscorlib] System.Text.StringBuilder builder ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname static bool op_Inequality( class Base r1, class Base r2 ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname static bool op_Equality( class Base r1, class Base r2 ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance int32 GetHashCode () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig virtual instance bool Equals( object obj ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig newslot virtual instance bool Equals( class Base other ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig newslot virtual instance class Base '<Clone>$'() cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig specialname rtspecialname instance void .ctor ( class Base original ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method public hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldnull
IL_0001: throw
}
.method family hidebysig specialname newslot virtual instance void set_EqualityContract ( class [mscorlib]System.Type 'value' ) cil managed
{
IL_0000: ldnull
IL_0001: throw
}
// Property has a setter but no getter
.property instance class [mscorlib]System.Type EqualityContract()
{
.set instance void Base::set_EqualityContract(class [mscorlib]System.Type)
}
}
";
var src = @"
record R : Base;
";
var comp = CreateCompilationWithIL(src, il);
comp.VerifyEmitDiagnostics(
// (2,8): error CS0545: 'R.EqualityContract.get': cannot override because 'Base.EqualityContract' does not have an overridable get accessor
// record R : Base;
Diagnostic(ErrorCode.ERR_NoGetToOverride, "R").WithArguments("R.EqualityContract.get", "Base.EqualityContract").WithLocation(2, 8)
);
var src2 = @"
record R : Base
{
protected override System.Type EqualityContract => typeof(R);
}
";
var comp2 = CreateCompilationWithIL(src2, il);
comp2.VerifyEmitDiagnostics(
// (4,56): error CS0545: 'R.EqualityContract.get': cannot override because 'Base.EqualityContract' does not have an overridable get accessor
// protected override System.Type EqualityContract => typeof(R);
Diagnostic(ErrorCode.ERR_NoGetToOverride, "typeof(R)").WithArguments("R.EqualityContract.get", "Base.EqualityContract").WithLocation(4, 56)
);
}
[Fact]
[WorkItem(48723, "https://github.com/dotnet/roslyn/issues/48723")]
public void EqualityContract_27_GetterAndSetterProperty_ExplicitlyOverridden()
{
var src = @"
_ = new R() == new R2();
record R
{
protected virtual System.Type EqualityContract { get { System.Console.Write(""RAN ""); return GetType(); } set { } }
}
record R2 : R
{
protected override System.Type EqualityContract { get { System.Console.Write(""RAN2 ""); return GetType(); } }
}
";
var comp = CreateCompilation(src, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "RAN RAN2");
}
[Fact]
public void EqualityOperators_01()
{
var source =
@"
record A(int X)
{
public virtual bool Equals(ref A other)
=> throw null;
static void Main()
{
Test(null, null);
Test(null, new A(0));
Test(new A(1), new A(1));
Test(new A(2), new A(3));
Test(new A(4), new B(4, 5));
Test(new B(6, 7), new B(6, 7));
Test(new B(8, 9), new B(8, 10));
var a = new A(11);
Test(a, a);
}
static void Test(A a1, A a2)
{
System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == a2, a2 == a1, a1 != a2, a2 != a1);
}
}
record B(int X, int Y) : A(X);
";
var verifier = CompileAndVerify(source, expectedOutput:
@"
True True False False
False False True True
True True False False
False False True True
False False True True
True True False False
False False True True
True True False False
").VerifyDiagnostics();
var comp = (CSharpCompilation)verifier.Compilation;
MethodSymbol op = comp.GetMembers("A." + WellKnownMemberNames.EqualityOperatorName).OfType<SynthesizedRecordEqualityOperator>().Single();
Assert.Equal("System.Boolean A.op_Equality(A? left, A? right)", op.ToTestDisplayString());
Assert.Equal(Accessibility.Public, op.DeclaredAccessibility);
Assert.True(op.IsStatic);
Assert.False(op.IsAbstract);
Assert.False(op.IsVirtual);
Assert.False(op.IsOverride);
Assert.False(op.IsSealed);
Assert.True(op.IsImplicitlyDeclared);
op = comp.GetMembers("A." + WellKnownMemberNames.InequalityOperatorName).OfType<SynthesizedRecordInequalityOperator>().Single();
Assert.Equal("System.Boolean A.op_Inequality(A? left, A? right)", op.ToTestDisplayString());
Assert.Equal(Accessibility.Public, op.DeclaredAccessibility);
Assert.True(op.IsStatic);
Assert.False(op.IsAbstract);
Assert.False(op.IsVirtual);
Assert.False(op.IsOverride);
Assert.False(op.IsSealed);
Assert.True(op.IsImplicitlyDeclared);
verifier.VerifyIL("bool A.op_Equality(A, A)", @"
{
// Code size 19 (0x13)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_0011
IL_0004: ldarg.0
IL_0005: brfalse.s IL_000f
IL_0007: ldarg.0
IL_0008: ldarg.1
IL_0009: callvirt ""bool A.Equals(A)""
IL_000e: ret
IL_000f: ldc.i4.0
IL_0010: ret
IL_0011: ldc.i4.1
IL_0012: ret
}
");
verifier.VerifyIL("bool A.op_Inequality(A, A)", @"
{
// Code size 11 (0xb)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""bool A.op_Equality(A, A)""
IL_0007: ldc.i4.0
IL_0008: ceq
IL_000a: ret
}
");
}
[Fact]
public void EqualityOperators_02()
{
var source =
@"
record B;
record A(int X) : B
{
public virtual bool Equals(A other)
{
System.Console.WriteLine(""Equals(A other)"");
return base.Equals(other) && X == other.X;
}
static void Main()
{
Test(null, null);
Test(null, new A(0));
Test(new A(1), new A(1));
Test(new A(2), new A(3));
var a = new A(11);
Test(a, a);
Test(new A(3), new B());
}
static void Test(A a1, A a2)
{
System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == a2, a2 == a1, a1 != a2, a2 != a1);
}
static void Test(A a1, B b2)
{
System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == b2, b2 == a1, a1 != b2, b2 != a1);
}
}
";
var verifier = CompileAndVerify(source, expectedOutput:
@"
True True False False
Equals(A other)
Equals(A other)
False False True True
Equals(A other)
Equals(A other)
Equals(A other)
Equals(A other)
True True False False
Equals(A other)
Equals(A other)
Equals(A other)
Equals(A other)
False False True True
True True False False
Equals(A other)
Equals(A other)
False False True True
").VerifyDiagnostics(
// (6,25): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode'
// public virtual bool Equals(A other)
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(6, 25)
);
var comp = (CSharpCompilation)verifier.Compilation;
MethodSymbol op = comp.GetMembers("A." + WellKnownMemberNames.EqualityOperatorName).OfType<SynthesizedRecordEqualityOperator>().Single();
Assert.Equal("System.Boolean A.op_Equality(A? left, A? right)", op.ToTestDisplayString());
Assert.Equal(Accessibility.Public, op.DeclaredAccessibility);
Assert.True(op.IsStatic);
Assert.False(op.IsAbstract);
Assert.False(op.IsVirtual);
Assert.False(op.IsOverride);
Assert.False(op.IsSealed);
Assert.True(op.IsImplicitlyDeclared);
op = comp.GetMembers("A." + WellKnownMemberNames.InequalityOperatorName).OfType<SynthesizedRecordInequalityOperator>().Single();
Assert.Equal("System.Boolean A.op_Inequality(A? left, A? right)", op.ToTestDisplayString());
Assert.Equal(Accessibility.Public, op.DeclaredAccessibility);
Assert.True(op.IsStatic);
Assert.False(op.IsAbstract);
Assert.False(op.IsVirtual);
Assert.False(op.IsOverride);
Assert.False(op.IsSealed);
Assert.True(op.IsImplicitlyDeclared);
verifier.VerifyIL("bool A.op_Equality(A, A)", @"
{
// Code size 19 (0x13)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_0011
IL_0004: ldarg.0
IL_0005: brfalse.s IL_000f
IL_0007: ldarg.0
IL_0008: ldarg.1
IL_0009: callvirt ""bool A.Equals(A)""
IL_000e: ret
IL_000f: ldc.i4.0
IL_0010: ret
IL_0011: ldc.i4.1
IL_0012: ret
}
");
verifier.VerifyIL("bool A.op_Inequality(A, A)", @"
{
// Code size 11 (0xb)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""bool A.op_Equality(A, A)""
IL_0007: ldc.i4.0
IL_0008: ceq
IL_000a: ret
}
");
}
[Fact]
public void EqualityOperators_03()
{
var source =
@"
record A
{
public static bool operator==(A r1, A r2)
=> throw null;
public static bool operator==(A r1, string r2)
=> throw null;
public static bool operator!=(A r1, string r2)
=> throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (4,32): error CS0111: Type 'A' already defines a member called 'op_Equality' with the same parameter types
// public static bool operator==(A r1, A r2)
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "==").WithArguments("op_Equality", "A").WithLocation(4, 32)
);
}
[Fact]
public void EqualityOperators_04()
{
var source =
@"
record A
{
public static bool operator!=(A r1, A r2)
=> throw null;
public static bool operator!=(string r1, A r2)
=> throw null;
public static bool operator==(string r1, A r2)
=> throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (4,32): error CS0111: Type 'A' already defines a member called 'op_Inequality' with the same parameter types
// public static bool operator!=(A r1, A r2)
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "!=").WithArguments("op_Inequality", "A").WithLocation(4, 32)
);
}
[Fact]
public void EqualityOperators_05()
{
var source =
@"
record A
{
public static bool op_Equality(A r1, A r2)
=> throw null;
public static bool op_Equality(string r1, A r2)
=> throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (4,24): error CS0111: Type 'A' already defines a member called 'op_Equality' with the same parameter types
// public static bool op_Equality(A r1, A r2)
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "op_Equality").WithArguments("op_Equality", "A").WithLocation(4, 24)
);
}
[Fact]
public void EqualityOperators_06()
{
var source =
@"
record A
{
public static bool op_Inequality(A r1, A r2)
=> throw null;
public static bool op_Inequality(A r1, string r2)
=> throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (4,24): error CS0111: Type 'A' already defines a member called 'op_Inequality' with the same parameter types
// public static bool op_Inequality(A r1, A r2)
Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "op_Inequality").WithArguments("op_Inequality", "A").WithLocation(4, 24)
);
}
[Fact]
public void EqualityOperators_07()
{
var source =
@"
record A
{
public static bool Equals(A other)
=> throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (2,8): error CS0736: 'A' does not implement instance interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement the interface member because it is static.
// record A
Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)").WithLocation(2, 8),
// (4,24): error CS8872: 'A.Equals(A)' must allow overriding because the containing record is not sealed.
// public static bool Equals(A other)
Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 24),
// (4,24): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode'
// public static bool Equals(A other)
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24)
);
}
[Fact]
public void EqualityOperators_08()
{
var source =
@"
record A
{
public virtual string Equals(A other)
=> throw null;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (2,8): error CS0738: 'A' does not implement interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement 'IEquatable<A>.Equals(A)' because it does not have the matching return type of 'bool'.
// record A
Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)", "bool").WithLocation(2, 8),
// (4,27): error CS8874: Record member 'A.Equals(A)' must return 'bool'.
// public virtual string Equals(A other)
Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "Equals").WithArguments("A.Equals(A)", "bool").WithLocation(4, 27),
// (4,27): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode'
// public virtual string Equals(A other)
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 27)
);
}
[Theory]
[CombinatorialData]
public void EqualityOperators_09(bool useImageReference)
{
var source1 =
@"
public record A(int X)
{
}
";
var comp1 = CreateCompilation(source1);
var source2 =
@"
class Program
{
static void Main()
{
Test(null, null);
Test(null, new A(0));
Test(new A(1), new A(1));
Test(new A(2), new A(3));
}
static void Test(A a1, A a2)
{
System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == a2, a2 == a1, a1 != a2, a2 != a1);
}
}
";
CompileAndVerify(source2, references: new[] { useImageReference ? comp1.EmitToImageReference() : comp1.ToMetadataReference() }, expectedOutput:
@"
True True False False
False False True True
True True False False
False False True True
").VerifyDiagnostics();
}
[WorkItem(44692, "https://github.com/dotnet/roslyn/issues/44692")]
[Fact]
public void DuplicateProperty_01()
{
var src =
@"record C(object Q)
{
public object P { get; }
public object P { get; }
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (4,19): error CS0102: The type 'C' already contains a definition for 'P'
// public object P { get; }
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C", "P").WithLocation(4, 19));
var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type C.EqualityContract { get; }",
"System.Object C.Q { get; init; }",
"System.Object C.P { get; }",
"System.Object C.P { get; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[WorkItem(44692, "https://github.com/dotnet/roslyn/issues/44692")]
[Fact]
public void DuplicateProperty_02()
{
var src =
@"record C(object P, object Q)
{
public object P { get; }
public int P { get; }
public int Q { get; }
public object Q { get; }
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (1,17): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P, object Q)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(1, 17),
// (1,27): error CS8866: Record member 'C.Q' must be a readable instance property or field of type 'object' to match positional parameter 'Q'.
// record C(object P, object Q)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Q").WithArguments("C.Q", "object", "Q").WithLocation(1, 27),
// (1,27): warning CS8907: Parameter 'Q' is unread. Did you forget to use it to initialize the property with that name?
// record C(object P, object Q)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Q").WithArguments("Q").WithLocation(1, 27),
// (4,16): error CS0102: The type 'C' already contains a definition for 'P'
// public int P { get; }
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C", "P").WithLocation(4, 16),
// (6,19): error CS0102: The type 'C' already contains a definition for 'Q'
// public object Q { get; }
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Q").WithArguments("C", "Q").WithLocation(6, 19));
var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type C.EqualityContract { get; }",
"System.Object C.P { get; }",
"System.Int32 C.P { get; }",
"System.Int32 C.Q { get; }",
"System.Object C.Q { get; }",
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void DuplicateProperty_03()
{
var src =
@"record A
{
public object P { get; }
public object P { get; }
public object Q { get; }
public int Q { get; }
}
record B(object Q) : A
{
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (4,19): error CS0102: The type 'A' already contains a definition for 'P'
// public object P { get; }
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("A", "P").WithLocation(4, 19),
// (6,16): error CS0102: The type 'A' already contains a definition for 'Q'
// public int Q { get; }
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Q").WithArguments("A", "Q").WithLocation(6, 16),
// (8,17): warning CS8907: Parameter 'Q' is unread. Did you forget to use it to initialize the property with that name?
// record B(object Q) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Q").WithArguments("Q").WithLocation(8, 17));
var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings();
AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers);
}
[Fact]
public void NominalRecordWith()
{
var src = @"
using System;
record C
{
public int X { get; init; }
public string Y;
public int Z { get; set; }
public static void Main()
{
var c = new C() { X = 1, Y = ""2"", Z = 3 };
var c2 = new C() { X = 1, Y = ""2"", Z = 3 };
Console.WriteLine(c.Equals(c2));
var c3 = c2 with { X = 3, Y = ""2"", Z = 1 };
Console.WriteLine(c.Equals(c2));
Console.WriteLine(c3.Equals(c2));
Console.WriteLine(c2.X + "" "" + c2.Y + "" "" + c2.Z);
}
}";
CompileAndVerify(src, expectedOutput: @"
True
True
False
1 2 3").VerifyDiagnostics();
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void WithExprReference(bool emitRef)
{
var src = @"
public record C
{
public int X { get; init; }
}
public record D(int Y) : C;";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics();
var src2 = @"
using System;
class E
{
public static void Main()
{
var c = new C() { X = 1 };
var c2 = c with { X = 2 };
Console.WriteLine(c.X);
Console.WriteLine(c2.X);
var d = new D(2) { X = 1 };
var d2 = d with { X = 2, Y = 3 };
Console.WriteLine(d.X + "" "" + d.Y);
Console.WriteLine(d2.X + "" "" + d2.Y);
C c3 = d;
C c4 = d2;
c3 = c3 with { X = 3 };
c4 = c4 with { X = 4 };
d = (D)c3;
d2 = (D)c4;
Console.WriteLine(d.X + "" "" + d.Y);
Console.WriteLine(d2.X + "" "" + d2.Y);
}
}";
var verifier = CompileAndVerify(src2,
references: new[] { emitRef ? comp.EmitToImageReference() : comp.ToMetadataReference() },
expectedOutput: @"
1
2
1 2
2 3
3 2
4 3").VerifyDiagnostics();
verifier.VerifyIL("E.Main", @"
{
// Code size 318 (0x13e)
.maxstack 3
.locals init (C V_0, //c
D V_1, //d
D V_2, //d2
C V_3, //c3
C V_4, //c4
int V_5)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: ldc.i4.1
IL_0007: callvirt ""void C.X.init""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()""
IL_0013: dup
IL_0014: ldc.i4.2
IL_0015: callvirt ""void C.X.init""
IL_001a: ldloc.0
IL_001b: callvirt ""int C.X.get""
IL_0020: call ""void System.Console.WriteLine(int)""
IL_0025: callvirt ""int C.X.get""
IL_002a: call ""void System.Console.WriteLine(int)""
IL_002f: ldc.i4.2
IL_0030: newobj ""D..ctor(int)""
IL_0035: dup
IL_0036: ldc.i4.1
IL_0037: callvirt ""void C.X.init""
IL_003c: stloc.1
IL_003d: ldloc.1
IL_003e: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()""
IL_0043: castclass ""D""
IL_0048: dup
IL_0049: ldc.i4.2
IL_004a: callvirt ""void C.X.init""
IL_004f: dup
IL_0050: ldc.i4.3
IL_0051: callvirt ""void D.Y.init""
IL_0056: stloc.2
IL_0057: ldloc.1
IL_0058: callvirt ""int C.X.get""
IL_005d: stloc.s V_5
IL_005f: ldloca.s V_5
IL_0061: call ""string int.ToString()""
IL_0066: ldstr "" ""
IL_006b: ldloc.1
IL_006c: callvirt ""int D.Y.get""
IL_0071: stloc.s V_5
IL_0073: ldloca.s V_5
IL_0075: call ""string int.ToString()""
IL_007a: call ""string string.Concat(string, string, string)""
IL_007f: call ""void System.Console.WriteLine(string)""
IL_0084: ldloc.2
IL_0085: callvirt ""int C.X.get""
IL_008a: stloc.s V_5
IL_008c: ldloca.s V_5
IL_008e: call ""string int.ToString()""
IL_0093: ldstr "" ""
IL_0098: ldloc.2
IL_0099: callvirt ""int D.Y.get""
IL_009e: stloc.s V_5
IL_00a0: ldloca.s V_5
IL_00a2: call ""string int.ToString()""
IL_00a7: call ""string string.Concat(string, string, string)""
IL_00ac: call ""void System.Console.WriteLine(string)""
IL_00b1: ldloc.1
IL_00b2: stloc.3
IL_00b3: ldloc.2
IL_00b4: stloc.s V_4
IL_00b6: ldloc.3
IL_00b7: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()""
IL_00bc: dup
IL_00bd: ldc.i4.3
IL_00be: callvirt ""void C.X.init""
IL_00c3: stloc.3
IL_00c4: ldloc.s V_4
IL_00c6: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()""
IL_00cb: dup
IL_00cc: ldc.i4.4
IL_00cd: callvirt ""void C.X.init""
IL_00d2: stloc.s V_4
IL_00d4: ldloc.3
IL_00d5: castclass ""D""
IL_00da: stloc.1
IL_00db: ldloc.s V_4
IL_00dd: castclass ""D""
IL_00e2: stloc.2
IL_00e3: ldloc.1
IL_00e4: callvirt ""int C.X.get""
IL_00e9: stloc.s V_5
IL_00eb: ldloca.s V_5
IL_00ed: call ""string int.ToString()""
IL_00f2: ldstr "" ""
IL_00f7: ldloc.1
IL_00f8: callvirt ""int D.Y.get""
IL_00fd: stloc.s V_5
IL_00ff: ldloca.s V_5
IL_0101: call ""string int.ToString()""
IL_0106: call ""string string.Concat(string, string, string)""
IL_010b: call ""void System.Console.WriteLine(string)""
IL_0110: ldloc.2
IL_0111: callvirt ""int C.X.get""
IL_0116: stloc.s V_5
IL_0118: ldloca.s V_5
IL_011a: call ""string int.ToString()""
IL_011f: ldstr "" ""
IL_0124: ldloc.2
IL_0125: callvirt ""int D.Y.get""
IL_012a: stloc.s V_5
IL_012c: ldloca.s V_5
IL_012e: call ""string int.ToString()""
IL_0133: call ""string string.Concat(string, string, string)""
IL_0138: call ""void System.Console.WriteLine(string)""
IL_013d: ret
}");
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void WithExprReference_WithCovariantReturns(bool emitRef)
{
var src = @"
public record C
{
public int X { get; init; }
}
public record D(int Y) : C;";
var comp = CreateCompilation(RuntimeUtilities.IsCoreClrRuntime ? src : new[] { src, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.StandardLatest);
comp.VerifyDiagnostics();
var src2 = @"
using System;
class E
{
public static void Main()
{
var c = new C() { X = 1 };
var c2 = CHelper(c);
Console.WriteLine(c.X);
Console.WriteLine(c2.X);
var d = new D(2) { X = 1 };
var d2 = DHelper(d);
Console.WriteLine(d.X + "" "" + d.Y);
Console.WriteLine(d2.X + "" "" + d2.Y);
}
private static C CHelper(C c)
{
return c with { X = 2 };
}
private static D DHelper(D d)
{
return d with { X = 2, Y = 3 };
}
}";
var verifier = CompileAndVerify(RuntimeUtilities.IsCoreClrRuntime ? src2 : new[] { src2, IsExternalInitTypeDefinition },
references: new[] { emitRef ? comp.EmitToImageReference() : comp.ToMetadataReference() },
expectedOutput: @"
1
2
1 2
2 3", targetFramework: TargetFramework.StandardLatest).VerifyDiagnostics().VerifyIL("E.CHelper", @"
{
// Code size 14 (0xe)
.maxstack 3
IL_0000: ldarg.0
IL_0001: callvirt ""C C.<Clone>$()""
IL_0006: dup
IL_0007: ldc.i4.2
IL_0008: callvirt ""void C.X.init""
IL_000d: ret
}
");
if (RuntimeUtilities.IsCoreClrRuntime)
{
verifier.VerifyIL("E.DHelper", @"
{
// Code size 21 (0x15)
.maxstack 3
IL_0000: ldarg.0
IL_0001: callvirt ""D D.<Clone>$()""
IL_0006: dup
IL_0007: ldc.i4.2
IL_0008: callvirt ""void C.X.init""
IL_000d: dup
IL_000e: ldc.i4.3
IL_000f: callvirt ""void D.Y.init""
IL_0014: ret
}
");
}
else
{
verifier.VerifyIL("E.DHelper", @"
{
// Code size 26 (0x1a)
.maxstack 3
IL_0000: ldarg.0
IL_0001: callvirt ""C C.<Clone>$()""
IL_0006: castclass ""D""
IL_000b: dup
IL_000c: ldc.i4.2
IL_000d: callvirt ""void C.X.init""
IL_0012: dup
IL_0013: ldc.i4.3
IL_0014: callvirt ""void D.Y.init""
IL_0019: ret
}
");
}
}
private static ImmutableArray<Symbol> GetProperties(CSharpCompilation comp, string typeName)
{
return comp.GetMember<NamedTypeSymbol>(typeName).GetMembers().WhereAsArray(m => m.Kind == SymbolKind.Property);
}
[Fact]
public void BaseArguments_01()
{
var src = @"
using System;
record Base
{
public Base(int X, int Y)
{
Console.WriteLine(X);
Console.WriteLine(Y);
}
public Base() {}
}
record C(int X, int Y = 123) : Base(X, Y)
{
int Z = 123;
public static void Main()
{
var c = new C(1, 2);
Console.WriteLine(c.Z);
}
C(int X, int Y, int Z = 124) : this(X, Y) {}
}";
var verifier = CompileAndVerify(src, expectedOutput: @"
1
2
123").VerifyDiagnostics();
verifier.VerifyIL("C..ctor(int, int)", @"
{
// Code size 31 (0x1f)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld ""int C.<X>k__BackingField""
IL_0007: ldarg.0
IL_0008: ldarg.2
IL_0009: stfld ""int C.<Y>k__BackingField""
IL_000e: ldarg.0
IL_000f: ldc.i4.s 123
IL_0011: stfld ""int C.Z""
IL_0016: ldarg.0
IL_0017: ldarg.1
IL_0018: ldarg.2
IL_0019: call ""Base..ctor(int, int)""
IL_001e: ret
}
");
var comp = CreateCompilation(src);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ElementAt(1);
Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString());
var symbol = model.GetSymbolInfo(x).Symbol;
Assert.Equal(SymbolKind.Parameter, symbol!.Kind);
Assert.Equal("System.Int32 X", symbol.ToTestDisplayString());
Assert.Equal("C..ctor(System.Int32 X, [System.Int32 Y = 123])", symbol.ContainingSymbol.ToTestDisplayString());
Assert.Equal(Accessibility.Public, symbol.ContainingSymbol.DeclaredAccessibility);
Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart));
Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X"));
Assert.Contains("X", model.LookupNames(x.SpanStart));
{
var baseWithargs = tree.GetRoot().DescendantNodes().OfType<PrimaryConstructorBaseTypeSyntax>().Single();
Assert.Equal("Base(X, Y)", baseWithargs.ToString());
Assert.Equal("Base", model.GetTypeInfo(baseWithargs.Type).Type.ToTestDisplayString());
Assert.Equal(TypeInfo.None, model.GetTypeInfo(baseWithargs));
Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", model.GetSymbolInfo((SyntaxNode)baseWithargs).Symbol.ToTestDisplayString());
Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", model.GetSymbolInfo(baseWithargs).Symbol.ToTestDisplayString());
Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", CSharpExtensions.GetSymbolInfo(model, baseWithargs).Symbol.ToTestDisplayString());
Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs));
Assert.Empty(model.GetMemberGroup(baseWithargs));
model = comp.GetSemanticModel(tree);
Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", model.GetSymbolInfo((SyntaxNode)baseWithargs).Symbol.ToTestDisplayString());
model = comp.GetSemanticModel(tree);
Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", model.GetSymbolInfo(baseWithargs).Symbol.ToTestDisplayString());
model = comp.GetSemanticModel(tree);
Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", CSharpExtensions.GetSymbolInfo(model, baseWithargs).Symbol.ToTestDisplayString());
model = comp.GetSemanticModel(tree);
Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs));
model = comp.GetSemanticModel(tree);
Assert.Empty(model.GetMemberGroup(baseWithargs));
model = comp.GetSemanticModel(tree);
#nullable disable
var operation = model.GetOperation(baseWithargs);
VerifyOperationTree(comp, operation,
@"
IInvocationOperation ( Base..ctor(System.Int32 X, System.Int32 Y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Base(X, Y)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: 'Base(X, Y)')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X')
IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y')
IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
Assert.Null(model.GetOperation(baseWithargs.Type));
Assert.Null(model.GetOperation(baseWithargs.Parent));
Assert.Same(operation.Parent.Parent, model.GetOperation(baseWithargs.Parent.Parent));
Assert.Equal(SyntaxKind.RecordDeclaration, baseWithargs.Parent.Parent.Kind());
VerifyOperationTree(comp, operation.Parent.Parent,
@"
IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null) (Syntax: 'record C(in ... }')
Initializer:
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'Base(X, Y)')
Expression:
IInvocationOperation ( Base..ctor(System.Int32 X, System.Int32 Y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Base(X, Y)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: 'Base(X, Y)')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X')
IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y')
IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
BlockBody:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'record C(in ... }')
ExpressionBody:
null
");
Assert.Null(operation.Parent.Parent.Parent);
VerifyFlowGraph(comp, operation.Parent.Parent.Syntax, @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'Base(X, Y)')
Expression:
IInvocationOperation ( Base..ctor(System.Int32 X, System.Int32 Y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Base(X, Y)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: 'Base(X, Y)')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X')
IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y')
IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
");
var equalsValue = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().First();
Assert.Equal("= 123", equalsValue.ToString());
model.VerifyOperationTree(equalsValue,
@"
IParameterInitializerOperation (Parameter: [System.Int32 Y = 123]) (OperationKind.ParameterInitializer, Type: null) (Syntax: '= 123')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 123) (Syntax: '123')
");
#nullable enable
}
{
var baseWithargs = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single();
Assert.Equal(": this(X, Y)", baseWithargs.ToString());
Assert.Equal("C..ctor(System.Int32 X, [System.Int32 Y = 123])", model.GetSymbolInfo((SyntaxNode)baseWithargs).Symbol.ToTestDisplayString());
Assert.Equal("C..ctor(System.Int32 X, [System.Int32 Y = 123])", model.GetSymbolInfo(baseWithargs).Symbol.ToTestDisplayString());
Assert.Equal("C..ctor(System.Int32 X, [System.Int32 Y = 123])", CSharpExtensions.GetSymbolInfo(model, baseWithargs).Symbol.ToTestDisplayString());
Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs).Select(m => m.ToTestDisplayString()));
Assert.Empty(model.GetMemberGroup(baseWithargs).Select(m => m.ToTestDisplayString()));
Assert.Empty(CSharpExtensions.GetMemberGroup(model, baseWithargs).Select(m => m.ToTestDisplayString()));
model.VerifyOperationTree(baseWithargs,
@"
IInvocationOperation ( C..ctor(System.Int32 X, [System.Int32 Y = 123])) (OperationKind.Invocation, Type: System.Void) (Syntax: ': this(X, Y)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: ': this(X, Y)')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X')
IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y')
IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
var equalsValue = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Last();
Assert.Equal("= 124", equalsValue.ToString());
model.VerifyOperationTree(equalsValue,
@"
IParameterInitializerOperation (Parameter: [System.Int32 Z = 124]) (OperationKind.ParameterInitializer, Type: null) (Syntax: '= 124')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 124) (Syntax: '124')
");
model.VerifyOperationTree(baseWithargs.Parent,
@"
IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null) (Syntax: 'C(int X, in ... is(X, Y) {}')
Initializer:
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: ': this(X, Y)')
Expression:
IInvocationOperation ( C..ctor(System.Int32 X, [System.Int32 Y = 123])) (OperationKind.Invocation, Type: System.Void) (Syntax: ': this(X, Y)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: ': this(X, Y)')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X')
IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y')
IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
BlockBody:
IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{}')
ExpressionBody:
null
");
}
}
[Fact]
public void BaseArguments_02()
{
var src = @"
using System;
record Base
{
public Base(int X, int Y)
{
Console.WriteLine(X);
Console.WriteLine(Y);
}
public Base() {}
}
record C(int X) : Base(Test(X, out var y), y)
{
public static void Main()
{
var c = new C(1);
}
private static int Test(int x, out int y)
{
y = 2;
return x;
}
}";
var verifier = CompileAndVerify(src, expectedOutput: @"
1
2").VerifyDiagnostics();
var comp = CreateCompilation(src);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var yDecl = OutVarTests.GetOutVarDeclaration(tree, "y");
var yRef = OutVarTests.GetReferences(tree, "y").ToArray();
Assert.Equal(2, yRef.Length);
OutVarTests.VerifyModelForOutVar(model, yDecl, yRef[0]);
OutVarTests.VerifyNotAnOutLocal(model, yRef[1]);
var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ElementAt(1);
Assert.Equal("Test(X, out var y)", x.Parent!.Parent!.Parent!.ToString());
var symbol = model.GetSymbolInfo(x).Symbol;
Assert.Equal(SymbolKind.Parameter, symbol!.Kind);
Assert.Equal("System.Int32 X", symbol.ToTestDisplayString());
Assert.Equal("C..ctor(System.Int32 X)", symbol.ContainingSymbol.ToTestDisplayString());
Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart));
Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X"));
Assert.Contains("X", model.LookupNames(x.SpanStart));
var y = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "y").First();
Assert.Equal("y", y.Parent!.ToString());
Assert.Equal("(Test(X, out var y), y)", y.Parent!.Parent!.ToString());
Assert.Equal("Base(Test(X, out var y), y)", y.Parent!.Parent!.Parent!.ToString());
symbol = model.GetSymbolInfo(y).Symbol;
Assert.Equal(SymbolKind.Local, symbol!.Kind);
Assert.Equal("System.Int32 y", symbol.ToTestDisplayString());
Assert.Equal("C..ctor(System.Int32 X)", symbol.ContainingSymbol.ToTestDisplayString());
Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart));
Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "y"));
Assert.Contains("y", model.LookupNames(x.SpanStart));
var test = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test").First();
Assert.Equal("(Test(X, out var y), y)", test.Parent!.Parent!.Parent!.ToString());
symbol = model.GetSymbolInfo(test).Symbol;
Assert.Equal(SymbolKind.Method, symbol!.Kind);
Assert.Equal("System.Int32 C.Test(System.Int32 x, out System.Int32 y)", symbol.ToTestDisplayString());
Assert.Equal("C", symbol.ContainingSymbol.ToTestDisplayString());
Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "Test"));
Assert.Contains("Test", model.LookupNames(x.SpanStart));
}
[Fact]
public void BaseArguments_03()
{
var src = @"
using System;
record Base
{
public Base(int X, int Y)
{
}
public Base() {}
}
record C : Base(X, Y)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (13,16): error CS8861: Unexpected argument list.
// record C : Base(X, Y)
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(13, 16)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First();
Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString());
var symbolInfo = model.GetSymbolInfo(x);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString());
Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X"));
Assert.DoesNotContain("X", model.LookupNames(x.SpanStart));
}
[Fact]
public void BaseArguments_04()
{
var src = @"
using System;
record Base
{
public Base(int X, int Y)
{
}
public Base() {}
}
partial record C(int X, int Y)
{
}
partial record C : Base(X, Y)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (17,24): error CS8861: Unexpected argument list.
// partial record C : Base(X, Y)
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(17, 24)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First();
Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString());
var symbolInfo = model.GetSymbolInfo(x);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString());
Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X"));
Assert.DoesNotContain("X", model.LookupNames(x.SpanStart));
var recordDeclarations = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Skip(1).ToArray();
Assert.Equal("C", recordDeclarations[0].Identifier.ValueText);
Assert.Null(model.GetOperation(recordDeclarations[0]));
Assert.Equal("C", recordDeclarations[1].Identifier.ValueText);
Assert.Null(model.GetOperation(recordDeclarations[1]));
}
[Fact]
public void BaseArguments_05()
{
var src = @"
using System;
record Base
{
public Base(int X, int Y)
{
}
public Base() {}
}
partial record C : Base(X, Y)
{
}
partial record C : Base(X, Y)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (13,24): error CS8861: Unexpected argument list.
// partial record C : Base(X, Y)
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(13, 24),
// (17,24): error CS8861: Unexpected argument list.
// partial record C : Base(X, Y)
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(17, 24)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var xs = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ToArray();
Assert.Equal(2, xs.Length);
foreach (var x in xs)
{
Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString());
var symbolInfo = model.GetSymbolInfo(x);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString());
Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X"));
Assert.DoesNotContain("X", model.LookupNames(x.SpanStart));
}
var recordDeclarations = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Skip(1).ToArray();
Assert.Equal("C", recordDeclarations[0].Identifier.ValueText);
Assert.Null(model.GetOperation(recordDeclarations[0]));
Assert.Equal("C", recordDeclarations[1].Identifier.ValueText);
Assert.Null(model.GetOperation(recordDeclarations[1]));
}
[Fact]
public void BaseArguments_06()
{
var src = @"
using System;
record Base
{
public Base(int X, int Y)
{
}
public Base() {}
}
partial record C(int X, int Y) : Base(X, Y)
{
}
partial record C : Base(X, Y)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (17,24): error CS8861: Unexpected argument list.
// partial record C : Base(X, Y)
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(17, 24)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var xs = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ToArray();
Assert.Equal(2, xs.Length);
var x = xs[0];
Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString());
var symbol = model.GetSymbolInfo(x).Symbol;
Assert.Equal(SymbolKind.Parameter, symbol!.Kind);
Assert.Equal("System.Int32 X", symbol.ToTestDisplayString());
Assert.Equal("C..ctor(System.Int32 X, System.Int32 Y)", symbol.ContainingSymbol.ToTestDisplayString());
Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart));
Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X"));
Assert.Contains("X", model.LookupNames(x.SpanStart));
x = xs[1];
Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString());
var symbolInfo = model.GetSymbolInfo(x);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString());
Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X"));
Assert.DoesNotContain("X", model.LookupNames(x.SpanStart));
var recordDeclarations = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Skip(1).ToArray();
Assert.Equal("C", recordDeclarations[0].Identifier.ValueText);
model.VerifyOperationTree(recordDeclarations[0],
@"
IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null) (Syntax: 'partial rec ... }')
Initializer:
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'Base(X, Y)')
Expression:
IInvocationOperation ( Base..ctor(System.Int32 X, System.Int32 Y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Base(X, Y)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: 'Base(X, Y)')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X')
IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y')
IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
BlockBody:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'partial rec ... }')
ExpressionBody:
null
");
Assert.Equal("C", recordDeclarations[1].Identifier.ValueText);
Assert.Null(model.GetOperation(recordDeclarations[1]));
}
[Fact]
public void BaseArguments_07()
{
var src = @"
using System;
record Base
{
public Base(int X, int Y)
{
}
public Base() {}
}
partial record C : Base(X, Y)
{
}
partial record C(int X, int Y) : Base(X, Y)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (13,24): error CS8861: Unexpected argument list.
// partial record C : Base(X, Y)
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(13, 24)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var xs = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ToArray();
Assert.Equal(2, xs.Length);
var x = xs[1];
Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString());
var symbol = model.GetSymbolInfo(x).Symbol;
Assert.Equal(SymbolKind.Parameter, symbol!.Kind);
Assert.Equal("System.Int32 X", symbol.ToTestDisplayString());
Assert.Equal("C..ctor(System.Int32 X, System.Int32 Y)", symbol.ContainingSymbol.ToTestDisplayString());
Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart));
Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X"));
Assert.Contains("X", model.LookupNames(x.SpanStart));
x = xs[0];
Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString());
var symbolInfo = model.GetSymbolInfo(x);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString());
Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X"));
Assert.DoesNotContain("X", model.LookupNames(x.SpanStart));
var recordDeclarations = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Skip(1).ToArray();
Assert.Equal("C", recordDeclarations[0].Identifier.ValueText);
Assert.Null(model.GetOperation(recordDeclarations[0]));
Assert.Equal("C", recordDeclarations[1].Identifier.ValueText);
model.VerifyOperationTree(recordDeclarations[1],
@"
IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null) (Syntax: 'partial rec ... }')
Initializer:
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'Base(X, Y)')
Expression:
IInvocationOperation ( Base..ctor(System.Int32 X, System.Int32 Y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Base(X, Y)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: 'Base(X, Y)')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X')
IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y')
IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
BlockBody:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'partial rec ... }')
ExpressionBody:
null
");
}
[Fact]
public void BaseArguments_08()
{
var src = @"
record Base
{
public Base(int Y)
{
}
public Base() {}
}
record C(int X) : Base(Y)
{
public int Y = 0;
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (11,24): error CS0120: An object reference is required for the non-static field, method, or property 'C.Y'
// record C(int X) : Base(Y)
Diagnostic(ErrorCode.ERR_ObjectRequired, "Y").WithArguments("C.Y").WithLocation(11, 24)
);
}
[Fact]
public void BaseArguments_09()
{
var src = @"
record Base
{
public Base(int X)
{
}
public Base() {}
}
record C(int X) : Base(this.X)
{
public int Y = 0;
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (11,24): error CS0027: Keyword 'this' is not available in the current context
// record C(int X) : Base(this.X)
Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(11, 24)
);
}
[Fact]
public void BaseArguments_10()
{
var src = @"
record Base
{
public Base(int X)
{
}
public Base() {}
}
record C(dynamic X) : Base(X)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (11,27): error CS1975: The constructor call needs to be dynamically dispatched, but cannot be because it is part of a constructor initializer. Consider casting the dynamic arguments.
// record C(dynamic X) : Base(X)
Diagnostic(ErrorCode.ERR_NoDynamicPhantomOnBaseCtor, "(X)").WithLocation(11, 27)
);
}
[Fact]
public void BaseArguments_11()
{
var src = @"
record Base
{
public Base(int X, int Y)
{
}
public Base() {}
}
record C(int X) : Base(Test(X, out var y), y)
{
int Z = y;
private static int Test(int x, out int y)
{
y = 2;
return x;
}
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (13,13): error CS0103: The name 'y' does not exist in the current context
// int Z = y;
Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(13, 13)
);
}
[Fact]
public void BaseArguments_12()
{
var src = @"
using System;
class Base
{
public Base(int X)
{
}
}
class C : Base(X)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (11,7): error CS7036: There is no argument given that corresponds to the required formal parameter 'X' of 'Base.Base(int)'
// class C : Base(X)
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("X", "Base.Base(int)").WithLocation(11, 7),
// (11,15): error CS8861: Unexpected argument list.
// class C : Base(X)
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(11, 15)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First();
Assert.Equal("Base(X)", x.Parent!.Parent!.Parent!.ToString());
var symbolInfo = model.GetSymbolInfo(x);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString());
Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X"));
Assert.DoesNotContain("X", model.LookupNames(x.SpanStart));
}
[Fact]
public void BaseArguments_13()
{
var src = @"
using System;
interface Base
{
}
struct C : Base(X)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (8,16): error CS8861: Unexpected argument list.
// struct C : Base(X)
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(8, 16)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First();
Assert.Equal("Base(X)", x.Parent!.Parent!.Parent!.ToString());
var symbolInfo = model.GetSymbolInfo(x);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString());
Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X"));
Assert.DoesNotContain("X", model.LookupNames(x.SpanStart));
}
[Fact]
public void BaseArguments_14()
{
var src = @"
using System;
interface Base
{
}
interface C : Base(X)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (8,19): error CS8861: Unexpected argument list.
// interface C : Base(X)
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(8, 19)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First();
Assert.Equal("Base(X)", x.Parent!.Parent!.Parent!.ToString());
var symbolInfo = model.GetSymbolInfo(x);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString());
Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X"));
Assert.DoesNotContain("X", model.LookupNames(x.SpanStart));
}
[Fact]
public void BaseArguments_15()
{
var src = @"
using System;
record Base
{
public Base(int X, int Y)
{
Console.WriteLine(X);
Console.WriteLine(Y);
}
public Base() {}
}
partial record C
{
}
partial record C(int X, int Y) : Base(X, Y)
{
int Z = 123;
public static void Main()
{
var c = new C(1, 2);
Console.WriteLine(c.Z);
}
}
partial record C
{
}
";
var verifier = CompileAndVerify(src, expectedOutput: @"
1
2
123").VerifyDiagnostics();
verifier.VerifyIL("C..ctor(int, int)", @"
{
// Code size 31 (0x1f)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld ""int C.<X>k__BackingField""
IL_0007: ldarg.0
IL_0008: ldarg.2
IL_0009: stfld ""int C.<Y>k__BackingField""
IL_000e: ldarg.0
IL_000f: ldc.i4.s 123
IL_0011: stfld ""int C.Z""
IL_0016: ldarg.0
IL_0017: ldarg.1
IL_0018: ldarg.2
IL_0019: call ""Base..ctor(int, int)""
IL_001e: ret
}
");
var comp = CreateCompilation(src);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ElementAt(1);
Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString());
var symbol = model.GetSymbolInfo(x).Symbol;
Assert.Equal(SymbolKind.Parameter, symbol!.Kind);
Assert.Equal("System.Int32 X", symbol.ToTestDisplayString());
Assert.Equal("C..ctor(System.Int32 X, System.Int32 Y)", symbol.ContainingSymbol.ToTestDisplayString());
Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart));
Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X"));
Assert.Contains("X", model.LookupNames(x.SpanStart));
}
[Fact]
public void BaseArguments_16()
{
var src = @"
using System;
record Base
{
public Base(Func<int> X)
{
Console.WriteLine(X());
}
public Base() {}
}
record C(int X) : Base(() => X)
{
public static void Main()
{
var c = new C(1);
}
}";
var verifier = CompileAndVerify(src, expectedOutput: @"1").VerifyDiagnostics();
}
[Fact]
public void BaseArguments_17()
{
var src = @"
record Base
{
public Base(int X, int Y)
{
}
public Base() {}
}
record C(int X, int y)
: Base(Test(X, out var y),
Test(X, out var z))
{
int Z = z;
private static int Test(int x, out int y)
{
y = 2;
return x;
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (12,28): error CS0136: A local or parameter named 'y' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// : Base(Test(X, out var y),
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y").WithArguments("y").WithLocation(12, 28),
// (15,13): error CS0103: The name 'z' does not exist in the current context
// int Z = z;
Diagnostic(ErrorCode.ERR_NameNotInContext, "z").WithArguments("z").WithLocation(15, 13)
);
}
[Fact]
public void BaseArguments_18()
{
var src = @"
record Base
{
public Base(int X, int Y)
{
}
public Base() {}
}
record C(int X, int y)
: Base(Test(X + 1, out var z),
Test(X + 2, out var z))
{
private static int Test(int x, out int y)
{
y = 2;
return x;
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (13,32): error CS0128: A local variable or function named 'z' is already defined in this scope
// Test(X + 2, out var z))
Diagnostic(ErrorCode.ERR_LocalDuplicate, "z").WithArguments("z").WithLocation(13, 32)
);
}
[Fact]
public void BaseArguments_19()
{
var src = @"
record Base
{
public Base(int X)
{
}
public Base() {}
}
record C(int X, int Y) : Base(GetInt(X, out var xx) + xx, Y), I
{
C(int X, int Y, int Z) : this(X, Y, Z, 1) { return; }
static int GetInt(int x1, out int x2)
{
throw null;
}
}
interface I {}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (11,30): error CS1729: 'Base' does not contain a constructor that takes 2 arguments
// record C(int X, int Y) : Base(GetInt(X, out var xx) + xx, Y)
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(GetInt(X, out var xx) + xx, Y)").WithArguments("Base", "2").WithLocation(11, 30),
// (13,30): error CS1729: 'C' does not contain a constructor that takes 4 arguments
// C(int X, int Y, int Z) : this(X, Y, Z, 1) {}
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "this").WithArguments("C", "4").WithLocation(13, 30)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
SymbolInfo symbolInfo;
PrimaryConstructorBaseTypeSyntax speculativePrimaryInitializer;
ConstructorInitializerSyntax speculativeBaseInitializer;
{
var baseWithargs = tree.GetRoot().DescendantNodes().OfType<PrimaryConstructorBaseTypeSyntax>().Single();
Assert.Equal("Base(GetInt(X, out var xx) + xx, Y)", baseWithargs.ToString());
Assert.Equal("Base", model.GetTypeInfo(baseWithargs.Type).Type.ToTestDisplayString());
Assert.Equal(TypeInfo.None, model.GetTypeInfo(baseWithargs));
symbolInfo = model.GetSymbolInfo((SyntaxNode)baseWithargs);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason);
string[] candidates = new[] { "Base..ctor(Base original)", "Base..ctor(System.Int32 X)", "Base..ctor()" };
Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString()));
symbolInfo = model.GetSymbolInfo(baseWithargs);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason);
Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString()));
symbolInfo = CSharpExtensions.GetSymbolInfo(model, baseWithargs);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason);
Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString()));
Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs));
Assert.Empty(model.GetMemberGroup(baseWithargs));
model = comp.GetSemanticModel(tree);
symbolInfo = model.GetSymbolInfo((SyntaxNode)baseWithargs);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason);
Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString()));
model = comp.GetSemanticModel(tree);
symbolInfo = model.GetSymbolInfo(baseWithargs);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason);
Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString()));
model = comp.GetSemanticModel(tree);
symbolInfo = CSharpExtensions.GetSymbolInfo(model, baseWithargs);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason);
Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString()));
model = comp.GetSemanticModel(tree);
Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs));
model = comp.GetSemanticModel(tree);
Assert.Empty(model.GetMemberGroup(baseWithargs));
model = comp.GetSemanticModel(tree);
SemanticModel speculativeModel;
speculativePrimaryInitializer = baseWithargs.WithArgumentList(baseWithargs.ArgumentList.WithArguments(baseWithargs.ArgumentList.Arguments.RemoveAt(1)));
speculativeBaseInitializer = SyntaxFactory.ConstructorInitializer(SyntaxKind.BaseConstructorInitializer, speculativePrimaryInitializer.ArgumentList);
Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer, out _));
symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativeBaseInitializer, SpeculativeBindingOption.BindAsExpression);
Assert.Equal(SymbolInfo.None, symbolInfo);
symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer);
Assert.Equal(SymbolInfo.None, symbolInfo);
Assert.False(model.TryGetSpeculativeSemanticModel(tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single().SpanStart,
speculativeBaseInitializer, out _));
var otherBasePosition = ((BaseListSyntax)baseWithargs.Parent!).Types[1].SpanStart;
Assert.False(model.TryGetSpeculativeSemanticModel(otherBasePosition, speculativePrimaryInitializer, out _));
Assert.True(model.TryGetSpeculativeSemanticModel(baseWithargs.SpanStart, speculativePrimaryInitializer, out speculativeModel!));
Assert.Equal("Base..ctor(System.Int32 X)", speculativeModel!.GetSymbolInfo((SyntaxNode)speculativePrimaryInitializer).Symbol.ToTestDisplayString());
Assert.Equal("Base..ctor(System.Int32 X)", speculativeModel.GetSymbolInfo(speculativePrimaryInitializer).Symbol.ToTestDisplayString());
Assert.Equal("Base..ctor(System.Int32 X)", CSharpExtensions.GetSymbolInfo(speculativeModel, speculativePrimaryInitializer).Symbol.ToTestDisplayString());
Assert.True(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer, out speculativeModel!));
var xxDecl = OutVarTests.GetOutVarDeclaration(speculativePrimaryInitializer.SyntaxTree, "xx");
var xxRef = OutVarTests.GetReferences(speculativePrimaryInitializer.SyntaxTree, "xx").ToArray();
Assert.Equal(1, xxRef.Length);
OutVarTests.VerifyModelForOutVar(speculativeModel, xxDecl, xxRef);
Assert.Equal("Base..ctor(System.Int32 X)", speculativeModel!.GetSymbolInfo((SyntaxNode)speculativePrimaryInitializer).Symbol.ToTestDisplayString());
Assert.Equal("Base..ctor(System.Int32 X)", speculativeModel.GetSymbolInfo(speculativePrimaryInitializer).Symbol.ToTestDisplayString());
Assert.Equal("Base..ctor(System.Int32 X)", CSharpExtensions.GetSymbolInfo(speculativeModel, speculativePrimaryInitializer).Symbol.ToTestDisplayString());
Assert.Throws<ArgumentNullException>(() => model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (PrimaryConstructorBaseTypeSyntax)null!, out _));
Assert.Throws<ArgumentException>(() => model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, baseWithargs, out _));
symbolInfo = model.GetSpeculativeSymbolInfo(otherBasePosition, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression);
Assert.Equal(SymbolInfo.None, symbolInfo);
symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, otherBasePosition, speculativePrimaryInitializer);
Assert.Equal(SymbolInfo.None, symbolInfo);
symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression);
Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString());
symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.SpanStart, speculativePrimaryInitializer);
Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString());
symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression);
Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString());
symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer);
Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression));
Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single().ArgumentList.OpenParenToken.SpanStart,
(SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression));
}
{
var baseWithargs = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single();
Assert.Equal(": this(X, Y, Z, 1)", baseWithargs.ToString());
symbolInfo = model.GetSymbolInfo((SyntaxNode)baseWithargs);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason);
string[] candidates = new[] { "C..ctor(System.Int32 X, System.Int32 Y)", "C..ctor(C original)", "C..ctor(System.Int32 X, System.Int32 Y, System.Int32 Z)" };
Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString()));
symbolInfo = model.GetSymbolInfo(baseWithargs);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason);
Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString()));
symbolInfo = CSharpExtensions.GetSymbolInfo(model, baseWithargs);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason);
Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString()));
Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs).Select(m => m.ToTestDisplayString()));
Assert.Empty(model.GetMemberGroup(baseWithargs).Select(m => m.ToTestDisplayString()));
Assert.Empty(CSharpExtensions.GetMemberGroup(model, baseWithargs).Select(m => m.ToTestDisplayString()));
Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer, out _));
symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer);
Assert.Equal(SymbolInfo.None, symbolInfo);
symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativeBaseInitializer, SpeculativeBindingOption.BindAsExpression);
Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString());
symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer);
Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression));
}
}
[Fact]
public void BaseArguments_20()
{
var src = @"
class Base
{
public Base(int X)
{
}
public Base() {}
}
class C : Base(GetInt(X, out var xx) + xx, Y), I
{
C(int X, int Y, int Z) : base(X, Y, Z, 1) { return; }
static int GetInt(int x1, out int x2)
{
throw null;
}
}
interface I {}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (11,15): error CS8861: Unexpected argument list.
// class C : Base(GetInt(X, out var xx) + xx, Y), I
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(GetInt(X, out var xx) + xx, Y)").WithLocation(11, 15),
// (13,30): error CS1729: 'Base' does not contain a constructor that takes 4 arguments
// C(int X, int Y, int Z) : base(X, Y, Z, 1) { return; }
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "base").WithArguments("Base", "4").WithLocation(13, 30)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
SymbolInfo symbolInfo;
PrimaryConstructorBaseTypeSyntax speculativePrimaryInitializer;
ConstructorInitializerSyntax speculativeBaseInitializer;
{
var baseWithargs = tree.GetRoot().DescendantNodes().OfType<PrimaryConstructorBaseTypeSyntax>().Single();
Assert.Equal("Base(GetInt(X, out var xx) + xx, Y)", baseWithargs.ToString());
Assert.Equal("Base", model.GetTypeInfo(baseWithargs.Type).Type.ToTestDisplayString());
Assert.Equal(TypeInfo.None, model.GetTypeInfo(baseWithargs));
symbolInfo = model.GetSymbolInfo((SyntaxNode)baseWithargs);
Assert.Equal(SymbolInfo.None, symbolInfo);
symbolInfo = model.GetSymbolInfo(baseWithargs);
Assert.Equal(SymbolInfo.None, symbolInfo);
symbolInfo = CSharpExtensions.GetSymbolInfo(model, baseWithargs);
Assert.Equal(SymbolInfo.None, symbolInfo);
Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs));
Assert.Empty(model.GetMemberGroup(baseWithargs));
speculativePrimaryInitializer = baseWithargs.WithArgumentList(baseWithargs.ArgumentList.WithArguments(baseWithargs.ArgumentList.Arguments.RemoveAt(1)));
speculativeBaseInitializer = SyntaxFactory.ConstructorInitializer(SyntaxKind.BaseConstructorInitializer, speculativePrimaryInitializer.ArgumentList);
Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer, out _));
symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativeBaseInitializer, SpeculativeBindingOption.BindAsExpression);
Assert.Equal(SymbolInfo.None, symbolInfo);
symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer);
Assert.Equal(SymbolInfo.None, symbolInfo);
Assert.False(model.TryGetSpeculativeSemanticModel(tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single().SpanStart,
speculativeBaseInitializer, out _));
var otherBasePosition = ((BaseListSyntax)baseWithargs.Parent!).Types[1].SpanStart;
Assert.False(model.TryGetSpeculativeSemanticModel(otherBasePosition, speculativePrimaryInitializer, out _));
Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.SpanStart, speculativePrimaryInitializer, out _));
Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer, out _));
Assert.Throws<ArgumentNullException>(() => model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (PrimaryConstructorBaseTypeSyntax)null!, out _));
Assert.Throws<ArgumentException>(() => model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, baseWithargs, out _));
symbolInfo = model.GetSpeculativeSymbolInfo(otherBasePosition, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression);
Assert.Equal(SymbolInfo.None, symbolInfo);
symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, otherBasePosition, speculativePrimaryInitializer);
Assert.Equal(SymbolInfo.None, symbolInfo);
symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression);
Assert.Equal(SymbolInfo.None, symbolInfo);
symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.SpanStart, speculativePrimaryInitializer);
Assert.Equal(SymbolInfo.None, symbolInfo);
symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression);
Assert.Equal(SymbolInfo.None, symbolInfo);
symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer);
Assert.Equal(SymbolInfo.None, symbolInfo);
Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression));
Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single().ArgumentList.OpenParenToken.SpanStart,
(SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression));
}
{
var baseWithargs = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single();
Assert.Equal(": base(X, Y, Z, 1)", baseWithargs.ToString());
symbolInfo = model.GetSymbolInfo((SyntaxNode)baseWithargs);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason);
string[] candidates = new[] { "Base..ctor(System.Int32 X)", "Base..ctor()" };
Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString()));
symbolInfo = model.GetSymbolInfo(baseWithargs);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason);
Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString()));
symbolInfo = CSharpExtensions.GetSymbolInfo(model, baseWithargs);
Assert.Null(symbolInfo.Symbol);
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason);
Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString()));
Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs).Select(m => m.ToTestDisplayString()));
Assert.Empty(model.GetMemberGroup(baseWithargs).Select(m => m.ToTestDisplayString()));
Assert.Empty(CSharpExtensions.GetMemberGroup(model, baseWithargs).Select(m => m.ToTestDisplayString()));
Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer, out _));
symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer);
Assert.Equal(SymbolInfo.None, symbolInfo);
symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativeBaseInitializer, SpeculativeBindingOption.BindAsExpression);
Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString());
symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer);
Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression));
}
}
[Fact]
public void Equality_02()
{
var source =
@"using static System.Console;
record C;
class Program
{
static void Main()
{
var x = new C();
var y = new C();
WriteLine(x.Equals(y) && x.GetHashCode() == y.GetHashCode());
WriteLine(((object)x).Equals(y));
WriteLine(((System.IEquatable<C>)x).Equals(y));
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
var ordinaryMethods = comp.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind == MethodKind.Ordinary).ToArray();
Assert.Equal(6, ordinaryMethods.Length);
foreach (var m in ordinaryMethods)
{
Assert.True(m.IsImplicitlyDeclared);
}
var verifier = CompileAndVerify(comp, expectedOutput:
@"True
True
True").VerifyDiagnostics();
verifier.VerifyIL("C.Equals(C)",
@"{
// Code size 29 (0x1d)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_001b
IL_0004: ldarg.1
IL_0005: brfalse.s IL_0019
IL_0007: ldarg.0
IL_0008: callvirt ""System.Type C.EqualityContract.get""
IL_000d: ldarg.1
IL_000e: callvirt ""System.Type C.EqualityContract.get""
IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)""
IL_0018: ret
IL_0019: ldc.i4.0
IL_001a: ret
IL_001b: ldc.i4.1
IL_001c: ret
}");
verifier.VerifyIL("C.Equals(object)",
@"{
// Code size 13 (0xd)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: isinst ""C""
IL_0007: callvirt ""bool C.Equals(C)""
IL_000c: ret
}");
verifier.VerifyIL("C.GetHashCode()",
@"{
// Code size 17 (0x11)
.maxstack 2
IL_0000: call ""System.Collections.Generic.EqualityComparer<System.Type> System.Collections.Generic.EqualityComparer<System.Type>.Default.get""
IL_0005: ldarg.0
IL_0006: callvirt ""System.Type C.EqualityContract.get""
IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<System.Type>.GetHashCode(System.Type)""
IL_0010: ret
}");
}
[Fact]
public void Equality_03()
{
var source =
@"using static System.Console;
record C
{
private static int _nextId = 0;
private int _id;
public C() { _id = _nextId++; }
}
class Program
{
static void Main()
{
var x = new C();
var y = new C();
WriteLine(x.Equals(x));
WriteLine(x.Equals(y));
WriteLine(y.Equals(y));
}
}";
var verifier = CompileAndVerify(source, expectedOutput:
@"True
False
True").VerifyDiagnostics();
verifier.VerifyIL("C.Equals(C)",
@"{
// Code size 53 (0x35)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_0033
IL_0004: ldarg.1
IL_0005: brfalse.s IL_0031
IL_0007: ldarg.0
IL_0008: callvirt ""System.Type C.EqualityContract.get""
IL_000d: ldarg.1
IL_000e: callvirt ""System.Type C.EqualityContract.get""
IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)""
IL_0018: brfalse.s IL_0031
IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get""
IL_001f: ldarg.0
IL_0020: ldfld ""int C._id""
IL_0025: ldarg.1
IL_0026: ldfld ""int C._id""
IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)""
IL_0030: ret
IL_0031: ldc.i4.0
IL_0032: ret
IL_0033: ldc.i4.1
IL_0034: ret
}");
verifier.VerifyIL("C.GetHashCode()",
@"{
// Code size 40 (0x28)
.maxstack 3
IL_0000: call ""System.Collections.Generic.EqualityComparer<System.Type> System.Collections.Generic.EqualityComparer<System.Type>.Default.get""
IL_0005: ldarg.0
IL_0006: callvirt ""System.Type C.EqualityContract.get""
IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<System.Type>.GetHashCode(System.Type)""
IL_0010: ldc.i4 0xa5555529
IL_0015: mul
IL_0016: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get""
IL_001b: ldarg.0
IL_001c: ldfld ""int C._id""
IL_0021: callvirt ""int System.Collections.Generic.EqualityComparer<int>.GetHashCode(int)""
IL_0026: add
IL_0027: ret
}");
var clone = ((CSharpCompilation)verifier.Compilation).GetMember<MethodSymbol>("C." + WellKnownMemberNames.CloneMethodName);
Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility);
Assert.False(clone.IsOverride);
Assert.True(clone.IsVirtual);
Assert.False(clone.IsAbstract);
Assert.False(clone.IsSealed);
Assert.True(clone.IsImplicitlyDeclared);
}
[Fact]
public void Equality_04()
{
var source =
@"using static System.Console;
record A;
record B1(int P) : A
{
internal B1() : this(0) { } // Use record base call syntax instead
internal int P { get; set; } // Use record base call syntax instead
}
record B2(int P) : A
{
internal B2() : this(0) { } // Use record base call syntax instead
internal int P { get; set; } // Use record base call syntax instead
}
class Program
{
static B1 NewB1(int p) => new B1 { P = p }; // Use record base call syntax instead
static B2 NewB2(int p) => new B2 { P = p }; // Use record base call syntax instead
static void Main()
{
WriteLine(new A().Equals(NewB1(1)));
WriteLine(NewB1(1).Equals(new A()));
WriteLine(NewB1(1).Equals(NewB2(1)));
WriteLine(new A().Equals((A)NewB2(1)));
WriteLine(((A)NewB2(1)).Equals(new A()));
WriteLine(((A)NewB2(1)).Equals(NewB2(1)) && ((A)NewB2(1)).GetHashCode() == NewB2(1).GetHashCode());
WriteLine(NewB2(1).Equals((A)NewB2(1)));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
var verifier = CompileAndVerify(comp, expectedOutput:
@"False
False
False
False
False
True
True").VerifyDiagnostics(
// (3,15): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name?
// record B1(int P) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(3, 15),
// (8,15): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name?
// record B2(int P) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(8, 15)
);
verifier.VerifyIL("A.Equals(A)",
@"{
// Code size 29 (0x1d)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_001b
IL_0004: ldarg.1
IL_0005: brfalse.s IL_0019
IL_0007: ldarg.0
IL_0008: callvirt ""System.Type A.EqualityContract.get""
IL_000d: ldarg.1
IL_000e: callvirt ""System.Type A.EqualityContract.get""
IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)""
IL_0018: ret
IL_0019: ldc.i4.0
IL_001a: ret
IL_001b: ldc.i4.1
IL_001c: ret
}");
verifier.VerifyIL("B1.Equals(B1)",
@"{
// Code size 40 (0x28)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_0026
IL_0004: ldarg.0
IL_0005: ldarg.1
IL_0006: call ""bool A.Equals(A)""
IL_000b: brfalse.s IL_0024
IL_000d: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get""
IL_0012: ldarg.0
IL_0013: ldfld ""int B1.<P>k__BackingField""
IL_0018: ldarg.1
IL_0019: ldfld ""int B1.<P>k__BackingField""
IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)""
IL_0023: ret
IL_0024: ldc.i4.0
IL_0025: ret
IL_0026: ldc.i4.1
IL_0027: ret
}");
verifier.VerifyIL("B1.GetHashCode()",
@"{
// Code size 30 (0x1e)
.maxstack 3
IL_0000: ldarg.0
IL_0001: call ""int A.GetHashCode()""
IL_0006: ldc.i4 0xa5555529
IL_000b: mul
IL_000c: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get""
IL_0011: ldarg.0
IL_0012: ldfld ""int B1.<P>k__BackingField""
IL_0017: callvirt ""int System.Collections.Generic.EqualityComparer<int>.GetHashCode(int)""
IL_001c: add
IL_001d: ret
}");
}
[Fact]
public void Equality_05()
{
var source =
@"using static System.Console;
record A(int P)
{
internal A() : this(0) { } // Use record base call syntax instead
internal int P { get; set; } // Use record base call syntax instead
}
record B1(int P) : A
{
internal B1() : this(0) { } // Use record base call syntax instead
}
record B2(int P) : A
{
internal B2() : this(0) { } // Use record base call syntax instead
}
class Program
{
static A NewA(int p) => new A { P = p }; // Use record base call syntax instead
static B1 NewB1(int p) => new B1 { P = p }; // Use record base call syntax instead
static B2 NewB2(int p) => new B2 { P = p }; // Use record base call syntax instead
static void Main()
{
WriteLine(NewA(1).Equals(NewA(2)));
WriteLine(NewA(1).Equals(NewA(1)) && NewA(1).GetHashCode() == NewA(1).GetHashCode());
WriteLine(NewA(1).Equals(NewB1(1)));
WriteLine(NewB1(1).Equals(NewA(1)));
WriteLine(NewB1(1).Equals(NewB2(1)));
WriteLine(NewA(1).Equals((A)NewB2(1)));
WriteLine(((A)NewB2(1)).Equals(NewA(1)));
WriteLine(((A)NewB2(1)).Equals(NewB2(1)));
WriteLine(NewB2(1).Equals((A)NewB2(1)));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
var verifier = CompileAndVerify(comp, expectedOutput:
@"False
True
False
False
False
False
False
True
True").VerifyDiagnostics(
// (2,14): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name?
// record A(int P)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 14),
// (7,15): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name?
// record B1(int P) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(7, 15),
// (11,15): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name?
// record B2(int P) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(11, 15)
);
verifier.VerifyIL("A.Equals(A)",
@"{
// Code size 53 (0x35)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_0033
IL_0004: ldarg.1
IL_0005: brfalse.s IL_0031
IL_0007: ldarg.0
IL_0008: callvirt ""System.Type A.EqualityContract.get""
IL_000d: ldarg.1
IL_000e: callvirt ""System.Type A.EqualityContract.get""
IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)""
IL_0018: brfalse.s IL_0031
IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get""
IL_001f: ldarg.0
IL_0020: ldfld ""int A.<P>k__BackingField""
IL_0025: ldarg.1
IL_0026: ldfld ""int A.<P>k__BackingField""
IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)""
IL_0030: ret
IL_0031: ldc.i4.0
IL_0032: ret
IL_0033: ldc.i4.1
IL_0034: ret
}");
verifier.VerifyIL("B1.Equals(B1)",
@"{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_000c
IL_0004: ldarg.0
IL_0005: ldarg.1
IL_0006: call ""bool A.Equals(A)""
IL_000b: ret
IL_000c: ldc.i4.1
IL_000d: ret
}");
verifier.VerifyIL("B1.GetHashCode()",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""int A.GetHashCode()""
IL_0006: ret
}");
}
[Fact]
public void Equality_06()
{
var source =
@"
using System;
using static System.Console;
record A;
record B : A
{
protected override Type EqualityContract => typeof(A);
public virtual bool Equals(B b) => base.Equals((A)b);
}
record C : B;
class Program
{
static void Main()
{
WriteLine(new A().Equals(new A()));
WriteLine(new A().Equals(new B()));
WriteLine(new A().Equals(new C()));
WriteLine(new B().Equals(new A()));
WriteLine(new B().Equals(new B()));
WriteLine(new B().Equals(new C()));
WriteLine(new C().Equals(new A()));
WriteLine(new C().Equals(new B()));
WriteLine(new C().Equals(new C()));
WriteLine(((A)new C()).Equals(new A()));
WriteLine(((A)new C()).Equals(new B()));
WriteLine(((A)new C()).Equals(new C()));
WriteLine(new C().Equals((A)new C()));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var recordDeclaration = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().First();
Assert.Null(model.GetOperation(recordDeclaration));
var verifier = CompileAndVerify(comp, expectedOutput:
@"True
True
False
False
True
False
False
False
True
False
False
True
True").VerifyDiagnostics(
// (8,25): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode'
// public virtual bool Equals(B b) => base.Equals((A)b);
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(8, 25)
);
verifier.VerifyIL("A.Equals(A)",
@"{
// Code size 29 (0x1d)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_001b
IL_0004: ldarg.1
IL_0005: brfalse.s IL_0019
IL_0007: ldarg.0
IL_0008: callvirt ""System.Type A.EqualityContract.get""
IL_000d: ldarg.1
IL_000e: callvirt ""System.Type A.EqualityContract.get""
IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)""
IL_0018: ret
IL_0019: ldc.i4.0
IL_001a: ret
IL_001b: ldc.i4.1
IL_001c: ret
}");
verifier.VerifyIL("C.Equals(C)",
@"{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_000c
IL_0004: ldarg.0
IL_0005: ldarg.1
IL_0006: call ""bool B.Equals(B)""
IL_000b: ret
IL_000c: ldc.i4.1
IL_000d: ret
}");
}
[Fact]
public void Equality_07()
{
var source =
@"using System;
using static System.Console;
record A;
record B : A;
record C : B;
class Program
{
static void Main()
{
WriteLine(new A().Equals(new A()));
WriteLine(new A().Equals(new B()));
WriteLine(new A().Equals(new C()));
WriteLine(new B().Equals(new A()));
WriteLine(new B().Equals(new B()));
WriteLine(new B().Equals(new C()));
WriteLine(new C().Equals(new A()));
WriteLine(new C().Equals(new B()));
WriteLine(new C().Equals(new C()));
WriteLine(((A)new B()).Equals(new A()));
WriteLine(((A)new B()).Equals(new B()));
WriteLine(((A)new B()).Equals(new C()));
WriteLine(((A)new C()).Equals(new A()));
WriteLine(((A)new C()).Equals(new B()));
WriteLine(((A)new C()).Equals(new C()));
WriteLine(((B)new C()).Equals(new A()));
WriteLine(((B)new C()).Equals(new B()));
WriteLine(((B)new C()).Equals(new C()));
WriteLine(new C().Equals((A)new C()));
WriteLine(((IEquatable<A>)new B()).Equals(new A()));
WriteLine(((IEquatable<A>)new B()).Equals(new B()));
WriteLine(((IEquatable<A>)new B()).Equals(new C()));
WriteLine(((IEquatable<A>)new C()).Equals(new A()));
WriteLine(((IEquatable<A>)new C()).Equals(new B()));
WriteLine(((IEquatable<A>)new C()).Equals(new C()));
WriteLine(((IEquatable<B>)new C()).Equals(new A()));
WriteLine(((IEquatable<B>)new C()).Equals(new B()));
WriteLine(((IEquatable<B>)new C()).Equals(new C()));
WriteLine(((IEquatable<C>)new C()).Equals(new C()));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
var verifier = CompileAndVerify(comp, expectedOutput:
@"True
False
False
False
True
False
False
False
True
False
True
False
False
False
True
False
False
True
True
False
True
False
False
False
True
False
False
True
True").VerifyDiagnostics();
verifier.VerifyIL("A.Equals(A)",
@"{
// Code size 29 (0x1d)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_001b
IL_0004: ldarg.1
IL_0005: brfalse.s IL_0019
IL_0007: ldarg.0
IL_0008: callvirt ""System.Type A.EqualityContract.get""
IL_000d: ldarg.1
IL_000e: callvirt ""System.Type A.EqualityContract.get""
IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)""
IL_0018: ret
IL_0019: ldc.i4.0
IL_001a: ret
IL_001b: ldc.i4.1
IL_001c: ret
}");
verifier.VerifyIL("B.Equals(A)",
@"{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: callvirt ""bool object.Equals(object)""
IL_0007: ret
}");
verifier.VerifyIL("C.Equals(B)",
@"{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: callvirt ""bool object.Equals(object)""
IL_0007: ret
}");
verifier.VerifyIL("C.Equals(C)",
@"{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_000c
IL_0004: ldarg.0
IL_0005: ldarg.1
IL_0006: call ""bool B.Equals(B)""
IL_000b: ret
IL_000c: ldc.i4.1
IL_000d: ret
}");
VerifyVirtualMethod(comp.GetMember<MethodSymbol>("A.get_EqualityContract"), isOverride: false);
VerifyVirtualMethod(comp.GetMember<MethodSymbol>("B.get_EqualityContract"), isOverride: true);
VerifyVirtualMethod(comp.GetMember<MethodSymbol>("C.get_EqualityContract"), isOverride: true);
VerifyVirtualMethod(comp.GetMember<MethodSymbol>("A." + WellKnownMemberNames.CloneMethodName), isOverride: false);
VerifyVirtualMethod(comp.GetMember<MethodSymbol>("B." + WellKnownMemberNames.CloneMethodName), isOverride: true);
VerifyVirtualMethod(comp.GetMember<MethodSymbol>("C." + WellKnownMemberNames.CloneMethodName), isOverride: true);
VerifyVirtualMethod(comp.GetMember<MethodSymbol>("A.GetHashCode"), isOverride: true);
VerifyVirtualMethod(comp.GetMember<MethodSymbol>("B.GetHashCode"), isOverride: true);
VerifyVirtualMethod(comp.GetMember<MethodSymbol>("C.GetHashCode"), isOverride: true);
VerifyVirtualMethods(comp.GetMembers("A.Equals"), ("System.Boolean A.Equals(A? other)", false), ("System.Boolean A.Equals(System.Object? obj)", true));
VerifyVirtualMethods(comp.GetMembers("B.Equals"), ("System.Boolean B.Equals(B? other)", false), ("System.Boolean B.Equals(A? other)", true), ("System.Boolean B.Equals(System.Object? obj)", true));
ImmutableArray<Symbol> cEquals = comp.GetMembers("C.Equals");
VerifyVirtualMethods(cEquals, ("System.Boolean C.Equals(C? other)", false), ("System.Boolean C.Equals(B? other)", true), ("System.Boolean C.Equals(System.Object? obj)", true));
var baseEquals = cEquals[1];
Assert.Equal("System.Boolean C.Equals(B? other)", baseEquals.ToTestDisplayString());
Assert.Equal(Accessibility.Public, baseEquals.DeclaredAccessibility);
Assert.True(baseEquals.IsOverride);
Assert.True(baseEquals.IsSealed);
Assert.True(baseEquals.IsImplicitlyDeclared);
}
private static void VerifyVirtualMethod(MethodSymbol method, bool isOverride)
{
Assert.Equal(!isOverride, method.IsVirtual);
Assert.Equal(isOverride, method.IsOverride);
Assert.True(method.IsMetadataVirtual());
Assert.Equal(!isOverride, method.IsMetadataNewSlot());
}
private static void VerifyVirtualMethods(ImmutableArray<Symbol> members, params (string displayString, bool isOverride)[] values)
{
Assert.Equal(members.Length, values.Length);
for (int i = 0; i < members.Length; i++)
{
var method = (MethodSymbol)members[i];
(string displayString, bool isOverride) = values[i];
Assert.Equal(displayString, method.ToTestDisplayString(includeNonNullable: true));
VerifyVirtualMethod(method, isOverride);
}
}
[WorkItem(44895, "https://github.com/dotnet/roslyn/issues/44895")]
[Fact]
public void Equality_08()
{
var source =
@"
using System;
using static System.Console;
record A(int X)
{
internal A() : this(0) { } // Use record base call syntax instead
internal int X { get; set; } // Use record base call syntax instead
}
record B : A
{
internal B() { } // Use record base call syntax instead
internal B(int X, int Y) : base(X) { this.Y = Y; }
internal int Y { get; set; }
protected override Type EqualityContract => typeof(A);
public virtual bool Equals(B b) => base.Equals((A)b);
}
record C(int X, int Y, int Z) : B
{
internal C() : this(0, 0, 0) { } // Use record base call syntax instead
internal int Z { get; set; } // Use record base call syntax instead
}
class Program
{
static A NewA(int x) => new A { X = x }; // Use record base call syntax instead
static B NewB(int x, int y) => new B { X = x, Y = y };
static C NewC(int x, int y, int z) => new C { X = x, Y = y, Z = z };
static void Main()
{
WriteLine(NewA(1).Equals(NewA(1)));
WriteLine(NewA(1).Equals(NewB(1, 2)));
WriteLine(NewA(1).Equals(NewC(1, 2, 3)));
WriteLine(NewB(1, 2).Equals(NewA(1)));
WriteLine(NewB(1, 2).Equals(NewB(1, 2)));
WriteLine(NewB(1, 2).Equals(NewC(1, 2, 3)));
WriteLine(NewC(1, 2, 3).Equals(NewA(1)));
WriteLine(NewC(1, 2, 3).Equals(NewB(1, 2)));
WriteLine(NewC(1, 2, 3).Equals(NewC(1, 2, 3)));
WriteLine(NewC(1, 2, 3).Equals(NewC(4, 2, 3)));
WriteLine(NewC(1, 2, 3).Equals(NewC(1, 4, 3)));
WriteLine(NewC(1, 2, 3).Equals(NewC(1, 4, 4)));
WriteLine(((A)NewB(1, 2)).Equals(NewA(1)));
WriteLine(((A)NewB(1, 2)).Equals(NewB(1, 2)));
WriteLine(((A)NewB(1, 2)).Equals(NewC(1, 2, 3)));
WriteLine(((A)NewC(1, 2, 3)).Equals(NewA(1)));
WriteLine(((A)NewC(1, 2, 3)).Equals(NewB(1, 2)));
WriteLine(((A)NewC(1, 2, 3)).Equals(NewC(1, 2, 3)));
WriteLine(((B)NewC(1, 2, 3)).Equals(NewA(1)));
WriteLine(((B)NewC(1, 2, 3)).Equals(NewB(1, 2)));
WriteLine(((B)NewC(1, 2, 3)).Equals(NewC(1, 2, 3)) && NewC(1, 2, 3).GetHashCode() == NewC(1, 2, 3).GetHashCode());
WriteLine(NewC(1, 2, 3).Equals((A)NewC(1, 2, 3)));
}
}";
// https://github.com/dotnet/roslyn/issues/44895: C.Equals() should compare B.Y.
var verifier = CompileAndVerify(source, expectedOutput:
@"True
True
False
False
True
False
False
False
True
False
True
False
False
True
False
False
False
True
False
False
True
True").VerifyDiagnostics(
// (4,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record A(int X)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(4, 14),
// (15,25): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode'
// public virtual bool Equals(B b) => base.Equals((A)b);
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(15, 25),
// (17,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X, int Y, int Z) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(17, 14),
// (17,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X, int Y, int Z) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(17, 21),
// (17,28): warning CS8907: Parameter 'Z' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X, int Y, int Z) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Z").WithArguments("Z").WithLocation(17, 28)
);
verifier.VerifyIL("A.Equals(A)",
@"{
// Code size 53 (0x35)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_0033
IL_0004: ldarg.1
IL_0005: brfalse.s IL_0031
IL_0007: ldarg.0
IL_0008: callvirt ""System.Type A.EqualityContract.get""
IL_000d: ldarg.1
IL_000e: callvirt ""System.Type A.EqualityContract.get""
IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)""
IL_0018: brfalse.s IL_0031
IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get""
IL_001f: ldarg.0
IL_0020: ldfld ""int A.<X>k__BackingField""
IL_0025: ldarg.1
IL_0026: ldfld ""int A.<X>k__BackingField""
IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)""
IL_0030: ret
IL_0031: ldc.i4.0
IL_0032: ret
IL_0033: ldc.i4.1
IL_0034: ret
}");
// https://github.com/dotnet/roslyn/issues/44895: C.Equals() should compare B.Y.
verifier.VerifyIL("C.Equals(C)",
@"{
// Code size 40 (0x28)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_0026
IL_0004: ldarg.0
IL_0005: ldarg.1
IL_0006: call ""bool B.Equals(B)""
IL_000b: brfalse.s IL_0024
IL_000d: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get""
IL_0012: ldarg.0
IL_0013: ldfld ""int C.<Z>k__BackingField""
IL_0018: ldarg.1
IL_0019: ldfld ""int C.<Z>k__BackingField""
IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)""
IL_0023: ret
IL_0024: ldc.i4.0
IL_0025: ret
IL_0026: ldc.i4.1
IL_0027: ret
}");
verifier.VerifyIL("C.GetHashCode()",
@"{
// Code size 30 (0x1e)
.maxstack 3
IL_0000: ldarg.0
IL_0001: call ""int B.GetHashCode()""
IL_0006: ldc.i4 0xa5555529
IL_000b: mul
IL_000c: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get""
IL_0011: ldarg.0
IL_0012: ldfld ""int C.<Z>k__BackingField""
IL_0017: callvirt ""int System.Collections.Generic.EqualityComparer<int>.GetHashCode(int)""
IL_001c: add
IL_001d: ret
}");
}
[Fact]
public void Equality_09()
{
var source =
@"using static System.Console;
record A(int X)
{
internal A() : this(0) { } // Use record base call syntax instead
internal int X { get; set; } // Use record base call syntax instead
}
record B(int X, int Y) : A
{
internal B() : this(0, 0) { } // Use record base call syntax instead
internal int Y { get; set; }
}
record C(int X, int Y, int Z) : B
{
internal C() : this(0, 0, 0) { } // Use record base call syntax instead
internal int Z { get; set; } // Use record base call syntax instead
}
class Program
{
static A NewA(int x) => new A { X = x }; // Use record base call syntax instead
static B NewB(int x, int y) => new B { X = x, Y = y };
static C NewC(int x, int y, int z) => new C { X = x, Y = y, Z = z };
static void Main()
{
WriteLine(NewA(1).Equals(NewA(1)));
WriteLine(NewA(1).Equals(NewB(1, 2)));
WriteLine(NewA(1).Equals(NewC(1, 2, 3)));
WriteLine(NewB(1, 2).Equals(NewA(1)));
WriteLine(NewB(1, 2).Equals(NewB(1, 2)));
WriteLine(NewB(1, 2).Equals(NewC(1, 2, 3)));
WriteLine(NewC(1, 2, 3).Equals(NewA(1)));
WriteLine(NewC(1, 2, 3).Equals(NewB(1, 2)));
WriteLine(NewC(1, 2, 3).Equals(NewC(1, 2, 3)));
WriteLine(NewC(1, 2, 3).Equals(NewC(4, 2, 3)));
WriteLine(NewC(1, 2, 3).Equals(NewC(1, 4, 3)));
WriteLine(NewC(1, 2, 3).Equals(NewC(1, 4, 4)));
WriteLine(((A)NewB(1, 2)).Equals(NewA(1)));
WriteLine(((A)NewB(1, 2)).Equals(NewB(1, 2)));
WriteLine(((A)NewB(1, 2)).Equals(NewC(1, 2, 3)));
WriteLine(((A)NewC(1, 2, 3)).Equals(NewA(1)));
WriteLine(((A)NewC(1, 2, 3)).Equals(NewB(1, 2)));
WriteLine(((A)NewC(1, 2, 3)).Equals(NewC(1, 2, 3)));
WriteLine(((B)NewC(1, 2, 3)).Equals(NewA(1)));
WriteLine(((B)NewC(1, 2, 3)).Equals(NewB(1, 2)));
WriteLine(((B)NewC(1, 2, 3)).Equals(NewC(1, 2, 3)));
WriteLine(NewC(1, 2, 3).Equals((A)NewC(1, 2, 3)));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var recordDeclaration = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().ElementAt(1);
Assert.Equal("B", recordDeclaration.Identifier.ValueText);
Assert.Null(model.GetOperation(recordDeclaration));
var verifier = CompileAndVerify(comp, expectedOutput:
@"True
False
False
False
True
False
False
False
True
False
False
False
False
True
False
False
False
True
False
False
True
True").VerifyDiagnostics(
// (2,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record A(int X)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 14),
// (7,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record B(int X, int Y) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(7, 14),
// (7,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// record B(int X, int Y) : A
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(7, 21),
// (12,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X, int Y, int Z) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(12, 14),
// (12,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X, int Y, int Z) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(12, 21),
// (12,28): warning CS8907: Parameter 'Z' is unread. Did you forget to use it to initialize the property with that name?
// record C(int X, int Y, int Z) : B
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Z").WithArguments("Z").WithLocation(12, 28)
);
verifier.VerifyIL("A.Equals(A)",
@"{
// Code size 53 (0x35)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_0033
IL_0004: ldarg.1
IL_0005: brfalse.s IL_0031
IL_0007: ldarg.0
IL_0008: callvirt ""System.Type A.EqualityContract.get""
IL_000d: ldarg.1
IL_000e: callvirt ""System.Type A.EqualityContract.get""
IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)""
IL_0018: brfalse.s IL_0031
IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get""
IL_001f: ldarg.0
IL_0020: ldfld ""int A.<X>k__BackingField""
IL_0025: ldarg.1
IL_0026: ldfld ""int A.<X>k__BackingField""
IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)""
IL_0030: ret
IL_0031: ldc.i4.0
IL_0032: ret
IL_0033: ldc.i4.1
IL_0034: ret
}");
verifier.VerifyIL("B.Equals(A)",
@"{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: callvirt ""bool object.Equals(object)""
IL_0007: ret
}");
verifier.VerifyIL("B.Equals(B)",
@"{
// Code size 40 (0x28)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_0026
IL_0004: ldarg.0
IL_0005: ldarg.1
IL_0006: call ""bool A.Equals(A)""
IL_000b: brfalse.s IL_0024
IL_000d: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get""
IL_0012: ldarg.0
IL_0013: ldfld ""int B.<Y>k__BackingField""
IL_0018: ldarg.1
IL_0019: ldfld ""int B.<Y>k__BackingField""
IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)""
IL_0023: ret
IL_0024: ldc.i4.0
IL_0025: ret
IL_0026: ldc.i4.1
IL_0027: ret
}");
verifier.VerifyIL("C.Equals(B)",
@"{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: callvirt ""bool object.Equals(object)""
IL_0007: ret
}");
verifier.VerifyIL("C.Equals(C)",
@"{
// Code size 40 (0x28)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_0026
IL_0004: ldarg.0
IL_0005: ldarg.1
IL_0006: call ""bool B.Equals(B)""
IL_000b: brfalse.s IL_0024
IL_000d: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get""
IL_0012: ldarg.0
IL_0013: ldfld ""int C.<Z>k__BackingField""
IL_0018: ldarg.1
IL_0019: ldfld ""int C.<Z>k__BackingField""
IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)""
IL_0023: ret
IL_0024: ldc.i4.0
IL_0025: ret
IL_0026: ldc.i4.1
IL_0027: ret
}");
}
[Fact]
public void Equality_11()
{
var source =
@"using System;
record A
{
protected virtual Type EqualityContract => typeof(object);
}
record B1(object P) : A;
record B2(object P) : A;
class Program
{
static void Main()
{
Console.WriteLine(new A().Equals(new A()));
Console.WriteLine(new A().Equals(new B1((object)null)));
Console.WriteLine(new B1((object)null).Equals(new A()));
Console.WriteLine(new B1((object)null).Equals(new B1((object)null)));
Console.WriteLine(new B1((object)null).Equals(new B2((object)null)));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
// init-only is unverifiable
CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput:
@"True
False
False
True
False").VerifyDiagnostics();
}
[Fact]
public void Equality_12()
{
var source =
@"using System;
abstract record A
{
public A() { }
protected abstract Type EqualityContract { get; }
}
record B1(object P) : A;
record B2(object P) : A;
class Program
{
static void Main()
{
var b1 = new B1((object)null);
var b2 = new B2((object)null);
Console.WriteLine(b1.Equals(b1));
Console.WriteLine(b1.Equals(b2));
Console.WriteLine(((A)b1).Equals(b1));
Console.WriteLine(((A)b1).Equals(b2));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
// init-only is unverifiable
CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput:
@"True
False
True
False").VerifyDiagnostics();
}
[Fact]
public void Equality_13()
{
var source =
@"record A
{
protected System.Type EqualityContract => typeof(A);
}
record B : A;
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (3,27): error CS8872: 'A.EqualityContract' must allow overriding because the containing record is not sealed.
// protected System.Type EqualityContract => typeof(A);
Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(3, 27),
// (5,8): error CS0506: 'B.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override
// record B : A;
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.EqualityContract", "A.EqualityContract").WithLocation(5, 8));
}
[Fact]
public void Equality_14()
{
var source =
@"record A;
record B : A
{
protected sealed override System.Type EqualityContract => typeof(B);
}
record C : B;
";
var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardLatest);
comp.VerifyDiagnostics(
// (4,43): error CS8872: 'B.EqualityContract' must allow overriding because the containing record is not sealed.
// protected sealed override System.Type EqualityContract => typeof(B);
Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("B.EqualityContract").WithLocation(4, 43),
// (6,8): error CS0239: 'C.EqualityContract': cannot override inherited member 'B.EqualityContract' because it is sealed
// record C : B;
Diagnostic(ErrorCode.ERR_CantOverrideSealed, "C").WithArguments("C.EqualityContract", "B.EqualityContract").WithLocation(6, 8));
Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses);
string expectedClone = comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses
? "B B." + WellKnownMemberNames.CloneMethodName + "()"
: "A B." + WellKnownMemberNames.CloneMethodName + "()";
var actualMembers = comp.GetMember<NamedTypeSymbol>("B").GetMembers().ToTestDisplayStrings();
var expectedMembers = new[]
{
"System.Type B.EqualityContract { get; }",
"System.Type B.EqualityContract.get",
"System.String B.ToString()",
"System.Boolean B." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)",
"System.Boolean B.op_Inequality(B? left, B? right)",
"System.Boolean B.op_Equality(B? left, B? right)",
"System.Int32 B.GetHashCode()",
"System.Boolean B.Equals(System.Object? obj)",
"System.Boolean B.Equals(A? other)",
"System.Boolean B.Equals(B? other)",
expectedClone,
"B..ctor(B original)",
"B..ctor()",
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact]
public void Equality_15()
{
var source =
@"using System;
record A;
record B1 : A
{
public B1(int p) { P = p; }
public int P { get; set; }
protected override Type EqualityContract => typeof(A);
public virtual bool Equals(B1 o) => base.Equals((A)o);
}
record B2 : A
{
public B2(int p) { P = p; }
public int P { get; set; }
protected override Type EqualityContract => typeof(B2);
public virtual bool Equals(B2 o) => base.Equals((A)o);
}
class Program
{
static void Main()
{
Console.WriteLine(new B1(1).Equals(new B1(2)));
Console.WriteLine(new B1(1).Equals(new B2(1)));
Console.WriteLine(new B2(1).Equals(new B2(2)));
}
}";
CompileAndVerify(source, expectedOutput:
@"True
False
True").VerifyDiagnostics(
// (8,25): warning CS8851: 'B1' defines 'Equals' but not 'GetHashCode'
// public virtual bool Equals(B1 o) => base.Equals((A)o);
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B1").WithLocation(8, 25),
// (15,25): warning CS8851: 'B2' defines 'Equals' but not 'GetHashCode'
// public virtual bool Equals(B2 o) => base.Equals((A)o);
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B2").WithLocation(15, 25)
);
}
[Fact]
public void Equality_16()
{
var source =
@"using System;
record A;
record B1 : A
{
public B1(int p) { P = p; }
public int P { get; set; }
protected override Type EqualityContract => typeof(string);
public virtual bool Equals(B1 b) => base.Equals((A)b);
}
record B2 : A
{
public B2(int p) { P = p; }
public int P { get; set; }
protected override Type EqualityContract => typeof(string);
public virtual bool Equals(B2 b) => base.Equals((A)b);
}
class Program
{
static void Main()
{
Console.WriteLine(new B1(1).Equals(new B1(2)));
Console.WriteLine(new B1(1).Equals(new B2(2)));
Console.WriteLine(new B2(1).Equals(new B2(2)));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"True
False
True").VerifyDiagnostics(
// (8,25): warning CS8851: 'B1' defines 'Equals' but not 'GetHashCode'
// public virtual bool Equals(B1 b) => base.Equals((A)b);
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B1").WithLocation(8, 25),
// (15,25): warning CS8851: 'B2' defines 'Equals' but not 'GetHashCode'
// public virtual bool Equals(B2 b) => base.Equals((A)b);
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B2").WithLocation(15, 25)
);
}
[Fact]
public void Equality_17()
{
var source =
@"using static System.Console;
record A;
record B1(int P) : A
{
}
record B2(int P) : A
{
}
class Program
{
static void Main()
{
WriteLine(new B1(1).Equals(new B1(1)));
WriteLine(new B1(1).Equals(new B1(2)));
WriteLine(new B2(3).Equals(new B2(3)));
WriteLine(new B2(3).Equals(new B2(4)));
WriteLine(((A)new B1(1)).Equals(new B1(1)));
WriteLine(((A)new B1(1)).Equals(new B1(2)));
WriteLine(((A)new B2(3)).Equals(new B2(3)));
WriteLine(((A)new B2(3)).Equals(new B2(4)));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
// init-only is unverifiable
CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput:
@"True
False
True
False
True
False
True
False").VerifyDiagnostics();
var actualMembers = comp.GetMember<NamedTypeSymbol>("B1").GetMembers().ToTestDisplayStrings();
var expectedMembers = new[]
{
"B1..ctor(System.Int32 P)",
"System.Type B1.EqualityContract.get",
"System.Type B1.EqualityContract { get; }",
"System.Int32 B1.<P>k__BackingField",
"System.Int32 B1.P.get",
"void modreq(System.Runtime.CompilerServices.IsExternalInit) B1.P.init",
"System.Int32 B1.P { get; init; }",
"System.String B1.ToString()",
"System.Boolean B1." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)",
"System.Boolean B1.op_Inequality(B1? left, B1? right)",
"System.Boolean B1.op_Equality(B1? left, B1? right)",
"System.Int32 B1.GetHashCode()",
"System.Boolean B1.Equals(System.Object? obj)",
"System.Boolean B1.Equals(A? other)",
"System.Boolean B1.Equals(B1? other)",
"A B1." + WellKnownMemberNames.CloneMethodName + "()",
"B1..ctor(B1 original)",
"void B1.Deconstruct(out System.Int32 P)"
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Equality_18(bool useCompilationReference)
{
var sourceA = @"public record A;";
var comp = CreateCompilation(sourceA);
comp.VerifyDiagnostics();
var refA = useCompilationReference ? comp.ToMetadataReference() : comp.EmitToImageReference();
VerifyVirtualMethod(comp.GetMember<MethodSymbol>("A.get_EqualityContract"), isOverride: false);
VerifyVirtualMethods(comp.GetMembers("A.Equals"), ("System.Boolean A.Equals(A? other)", false), ("System.Boolean A.Equals(System.Object? obj)", true));
var sourceB = @"record B : A;";
comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
VerifyVirtualMethod(comp.GetMember<MethodSymbol>("B.get_EqualityContract"), isOverride: true);
VerifyVirtualMethods(comp.GetMembers("B.Equals"), ("System.Boolean B.Equals(B? other)", false), ("System.Boolean B.Equals(A? other)", true), ("System.Boolean B.Equals(System.Object? obj)", true));
}
[Fact]
public void Equality_19()
{
var source =
@"using static System.Console;
record A<T>;
record B : A<int>;
class Program
{
static void Main()
{
WriteLine(new A<int>().Equals(new A<int>()));
WriteLine(new A<int>().Equals(new B()));
WriteLine(new B().Equals(new A<int>()));
WriteLine(new B().Equals(new B()));
WriteLine(((A<int>)new B()).Equals(new A<int>()));
WriteLine(((A<int>)new B()).Equals(new B()));
WriteLine(new B().Equals((A<int>)new B()));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
var verifier = CompileAndVerify(comp, expectedOutput:
@"True
False
False
True
False
True
True").VerifyDiagnostics();
verifier.VerifyIL("A<T>.Equals(A<T>)",
@"{
// Code size 29 (0x1d)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_001b
IL_0004: ldarg.1
IL_0005: brfalse.s IL_0019
IL_0007: ldarg.0
IL_0008: callvirt ""System.Type A<T>.EqualityContract.get""
IL_000d: ldarg.1
IL_000e: callvirt ""System.Type A<T>.EqualityContract.get""
IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)""
IL_0018: ret
IL_0019: ldc.i4.0
IL_001a: ret
IL_001b: ldc.i4.1
IL_001c: ret
}");
verifier.VerifyIL("B.Equals(A<int>)",
@"{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: callvirt ""bool object.Equals(object)""
IL_0007: ret
}");
verifier.VerifyIL("B.Equals(B)",
@"{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: beq.s IL_000c
IL_0004: ldarg.0
IL_0005: ldarg.1
IL_0006: call ""bool A<int>.Equals(A<int>)""
IL_000b: ret
IL_000c: ldc.i4.1
IL_000d: ret
}");
}
[Fact]
public void Equality_20()
{
var source =
@"
record C;
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.MakeMemberMissing(WellKnownMember.System_Collections_Generic_EqualityComparer_T__GetHashCode);
comp.VerifyEmitDiagnostics(
// (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.GetHashCode'
// record C;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C;").WithArguments("System.Collections.Generic.EqualityComparer`1", "GetHashCode").WithLocation(2, 1)
);
}
[Fact]
public void Equality_21()
{
var source =
@"
record C;
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.MakeMemberMissing(WellKnownMember.System_Collections_Generic_EqualityComparer_T__get_Default);
comp.VerifyEmitDiagnostics(
// (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.get_Default'
// record C;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C;").WithArguments("System.Collections.Generic.EqualityComparer`1", "get_Default").WithLocation(2, 1)
);
}
[Fact]
[WorkItem(44988, "https://github.com/dotnet/roslyn/issues/44988")]
public void Equality_22()
{
var source =
@"
record C
{
int x = 0;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll);
comp.MakeMemberMissing(WellKnownMember.System_Collections_Generic_EqualityComparer_T__get_Default);
comp.VerifyEmitDiagnostics(
// (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.get_Default'
// record C
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"record C
{
int x = 0;
}").WithArguments("System.Collections.Generic.EqualityComparer`1", "get_Default").WithLocation(2, 1),
// (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.get_Default'
// record C
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"record C
{
int x = 0;
}").WithArguments("System.Collections.Generic.EqualityComparer`1", "get_Default").WithLocation(2, 1),
// (4,9): warning CS0414: The field 'C.x' is assigned but its value is never used
// int x = 0;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x").WithArguments("C.x").WithLocation(4, 9)
);
}
[Fact]
public void IEquatableT_01()
{
var source =
@"record A<T>;
record B : A<int>;
class Program
{
static void F<T>(System.IEquatable<T> t)
{
}
static void M<T>()
{
F(new A<T>());
F(new B());
F<A<int>>(new B());
F<B>(new B());
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (11,9): error CS0411: The type arguments for method 'Program.F<T>(IEquatable<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// F(new B());
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(System.IEquatable<T>)").WithLocation(11, 9));
}
[Fact]
public void IEquatableT_02()
{
var source =
@"using System;
record A;
record B<T> : A;
record C : B<int>;
class Program
{
static string F<T>(IEquatable<T> t)
{
return typeof(T).Name;
}
static void Main()
{
Console.WriteLine(F(new A()));
Console.WriteLine(F<A>(new C()));
Console.WriteLine(F<B<int>>(new C()));
Console.WriteLine(F<C>(new C()));
}
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"A
A
B`1
C").VerifyDiagnostics();
}
[Fact]
public void IEquatableT_03()
{
var source =
@"#nullable enable
using System;
record A<T> : IEquatable<A<T>>
{
}
record B : A<object>, IEquatable<A<object>>, IEquatable<B?>;
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var type = comp.GetMember<NamedTypeSymbol>("A");
AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
type = comp.GetMember<NamedTypeSymbol>("B");
AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B?>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B?>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
}
[Fact]
public void IEquatableT_04()
{
var source =
@"using System;
record A<T>
{
internal static bool Report(string s) { Console.WriteLine(s); return false; }
public virtual bool Equals(A<T> other) => Report(""A<T>.Equals(A<T>)"");
}
record B : A<object>
{
public virtual bool Equals(B other) => Report(""B.Equals(B)"");
}
class Program
{
static void Main()
{
var a = new A<object>();
var b = new B();
_ = a.Equals(b);
_ = ((A<object>)b).Equals(b);
_ = b.Equals(a);
_ = b.Equals(b);
_ = ((IEquatable<A<object>>)a).Equals(b);
_ = ((IEquatable<A<object>>)b).Equals(b);
_ = ((IEquatable<B>)b).Equals(b);
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"A<T>.Equals(A<T>)
B.Equals(B)
B.Equals(B)
B.Equals(B)
A<T>.Equals(A<T>)
B.Equals(B)
B.Equals(B)").VerifyDiagnostics(
// (5,25): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode'
// public virtual bool Equals(A<T> other) => Report("A<T>.Equals(A<T>)");
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(5, 25),
// (9,25): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode'
// public virtual bool Equals(B other) => Report("B.Equals(B)");
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 25)
);
var type = comp.GetMember<NamedTypeSymbol>("A");
AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
type = comp.GetMember<NamedTypeSymbol>("B");
AssertEx.Equal(new[] { "System.IEquatable<B>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
}
[Fact]
public void IEquatableT_05()
{
var source =
@"using System;
record A<T> : IEquatable<A<T>>
{
internal static bool Report(string s) { Console.WriteLine(s); return false; }
public virtual bool Equals(A<T> other) => Report(""A<T>.Equals(A<T>)"");
}
record B : A<object>, IEquatable<A<object>>, IEquatable<B>
{
public virtual bool Equals(B other) => Report(""B.Equals(B)"");
}
record C : A<object>, IEquatable<A<object>>, IEquatable<C>
{
}
class Program
{
static void Main()
{
var a = new A<object>();
var b = new B();
_ = a.Equals(b);
_ = ((A<object>)b).Equals(b);
_ = b.Equals(a);
_ = b.Equals(b);
_ = ((IEquatable<A<object>>)a).Equals(b);
_ = ((IEquatable<A<object>>)b).Equals(b);
_ = ((IEquatable<B>)b).Equals(b);
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"A<T>.Equals(A<T>)
B.Equals(B)
B.Equals(B)
B.Equals(B)
A<T>.Equals(A<T>)
B.Equals(B)
B.Equals(B)",
symbolValidator: m =>
{
var b = m.GlobalNamespace.GetTypeMember("B");
Assert.Equal("B.Equals(B)", b.FindImplementationForInterfaceMember(b.InterfacesNoUseSiteDiagnostics()[1].GetMember("Equals")).ToDisplayString());
var c = m.GlobalNamespace.GetTypeMember("C");
Assert.Equal("C.Equals(C?)", c.FindImplementationForInterfaceMember(c.InterfacesNoUseSiteDiagnostics()[1].GetMember("Equals")).ToDisplayString());
}).VerifyDiagnostics(
// (5,25): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode'
// public virtual bool Equals(A<T> other) => Report("A<T>.Equals(A<T>)");
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(5, 25),
// (9,25): warning CS8851: '{B}' defines 'Equals' but not 'GetHashCode'
// public virtual bool Equals(B other) => Report("B.Equals(B)");
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 25)
);
var type = comp.GetMember<NamedTypeSymbol>("A");
AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
type = comp.GetMember<NamedTypeSymbol>("B");
AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
}
[Fact]
public void IEquatableT_06()
{
var source =
@"using System;
record A<T> : IEquatable<A<T>>
{
internal static bool Report(string s) { Console.WriteLine(s); return false; }
bool IEquatable<A<T>>.Equals(A<T> other) => Report(""A<T>.Equals(A<T>)"");
}
record B : A<object>, IEquatable<A<object>>, IEquatable<B>
{
bool IEquatable<A<object>>.Equals(A<object> other) => Report(""B.Equals(A<object>)"");
bool IEquatable<B>.Equals(B other) => Report(""B.Equals(B)"");
}
class Program
{
static void Main()
{
var a = new A<object>();
var b = new B();
_ = a.Equals(b);
_ = ((A<object>)b).Equals(b);
_ = b.Equals(a);
_ = b.Equals(b);
_ = ((IEquatable<A<object>>)a).Equals(b);
_ = ((IEquatable<A<object>>)b).Equals(b);
_ = ((IEquatable<B>)b).Equals(b);
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput:
@"A<T>.Equals(A<T>)
B.Equals(A<object>)
B.Equals(B)").VerifyDiagnostics();
var type = comp.GetMember<NamedTypeSymbol>("A");
AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
type = comp.GetMember<NamedTypeSymbol>("B");
AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
}
[Fact]
public void IEquatableT_07()
{
var source =
@"using System;
record A<T> : IEquatable<B1>, IEquatable<B2>
{
bool IEquatable<B1>.Equals(B1 other) => false;
bool IEquatable<B2>.Equals(B2 other) => false;
}
record B1 : A<object>;
record B2 : A<int>;
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var type = comp.GetMember<NamedTypeSymbol>("A");
AssertEx.Equal(new[] { "System.IEquatable<B1>", "System.IEquatable<B2>", "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<B1>", "System.IEquatable<B2>", "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
type = comp.GetMember<NamedTypeSymbol>("B1");
AssertEx.Equal(new[] { "System.IEquatable<B1>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<B2>", "System.IEquatable<A<System.Object>>", "System.IEquatable<B1>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
type = comp.GetMember<NamedTypeSymbol>("B2");
AssertEx.Equal(new[] { "System.IEquatable<B2>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<B1>", "System.IEquatable<A<System.Int32>>", "System.IEquatable<B2>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
}
[Fact]
public void IEquatableT_08()
{
var source =
@"interface I<T>
{
}
record A<T> : I<A<T>>
{
}
record B : A<object>, I<A<object>>, I<B>
{
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var type = comp.GetMember<NamedTypeSymbol>("A");
AssertEx.Equal(new[] { "I<A<T>>", "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "I<A<T>>", "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
type = comp.GetMember<NamedTypeSymbol>("B");
AssertEx.Equal(new[] { "I<A<System.Object>>", "I<B>", "System.IEquatable<B>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "I<A<System.Object>>", "I<B>", "System.IEquatable<B>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
}
[Fact]
public void IEquatableT_09()
{
var source0 =
@"namespace System
{
public class Object
{
public virtual bool Equals(object other) => false;
public virtual int GetHashCode() => 0;
public virtual string ToString() => """";
}
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
}
namespace System.Text
{
public class StringBuilder
{
public StringBuilder Append(string s) => null;
public StringBuilder Append(object s) => null;
}
}";
var comp = CreateEmptyCompilation(source0);
comp.VerifyDiagnostics();
var ref0 = comp.EmitToImageReference();
var source1 =
@"record A<T>;
record B : A<int>;
";
comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (1,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported
// record A<T>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(1, 8),
// (1,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported
// record A<T>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(1, 8),
// (1,8): error CS0518: Predefined type 'System.Type' is not defined or imported
// record A<T>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(1, 8),
// (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported
// record B : A<int>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(2, 8),
// (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported
// record B : A<int>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(2, 8),
// (2,8): error CS0518: Predefined type 'System.Type' is not defined or imported
// record B : A<int>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.Type").WithLocation(2, 8)
);
var type = comp.GetMember<NamedTypeSymbol>("A");
AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
type = comp.GetMember<NamedTypeSymbol>("B");
AssertEx.Equal(new[] { "System.IEquatable<B>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<A<System.Int32>>[missing]", "System.IEquatable<B>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
}
[Fact]
public void IEquatableT_10()
{
var source0 =
@"namespace System
{
public class Object
{
public virtual bool Equals(object other) => false;
public virtual int GetHashCode() => 0;
public virtual string ToString() => """";
}
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
}
namespace System.Text
{
public class StringBuilder
{
public StringBuilder Append(string s) => null;
public StringBuilder Append(object s) => null;
}
}";
var comp = CreateEmptyCompilation(source0);
comp.VerifyDiagnostics();
var ref0 = comp.EmitToImageReference();
var source1 =
@"record A<T> : System.IEquatable<A<T>>;
record B : A<int>, System.IEquatable<B>;
";
comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (1,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported
// record A<T> : System.IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(1, 8),
// (1,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported
// record A<T> : System.IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(1, 8),
// (1,8): error CS0518: Predefined type 'System.Type' is not defined or imported
// record A<T> : System.IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(1, 8),
// (1,8): error CS0115: 'A<T>.ToString()': no suitable method found to override
// record A<T> : System.IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.ToString()").WithLocation(1, 8),
// (1,8): error CS0115: 'A<T>.EqualityContract': no suitable method found to override
// record A<T> : System.IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.EqualityContract").WithLocation(1, 8),
// (1,8): error CS0115: 'A<T>.Equals(object?)': no suitable method found to override
// record A<T> : System.IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.Equals(object?)").WithLocation(1, 8),
// (1,8): error CS0115: 'A<T>.GetHashCode()': no suitable method found to override
// record A<T> : System.IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.GetHashCode()").WithLocation(1, 8),
// (1,8): error CS0115: 'A<T>.PrintMembers(StringBuilder)': no suitable method found to override
// record A<T> : System.IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.PrintMembers(System.Text.StringBuilder)").WithLocation(1, 8),
// (1,22): error CS0234: The type or namespace name 'IEquatable<>' does not exist in the namespace 'System' (are you missing an assembly reference?)
// record A<T> : System.IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "IEquatable<A<T>>").WithArguments("IEquatable<>", "System").WithLocation(1, 22),
// (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported
// record B : A<int>, System.IEquatable<B>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(2, 8),
// (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported
// record B : A<int>, System.IEquatable<B>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(2, 8),
// (2,8): error CS0518: Predefined type 'System.Type' is not defined or imported
// record B : A<int>, System.IEquatable<B>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.Type").WithLocation(2, 8),
// (2,27): error CS0234: The type or namespace name 'IEquatable<>' does not exist in the namespace 'System' (are you missing an assembly reference?)
// record B : A<int>, System.IEquatable<B>;
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "IEquatable<B>").WithArguments("IEquatable<>", "System").WithLocation(2, 27));
var type = comp.GetMember<NamedTypeSymbol>("A");
AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
type = comp.GetMember<NamedTypeSymbol>("B");
AssertEx.Equal(new[] { "System.IEquatable<B>", "System.IEquatable<B>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<A<System.Int32>>[missing]", "System.IEquatable<B>", "System.IEquatable<B>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
}
[Fact]
public void IEquatableT_11()
{
var source0 =
@"namespace System
{
public class Object
{
public virtual bool Equals(object other) => false;
public virtual int GetHashCode() => 0;
public virtual string ToString() => """";
}
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
}
namespace System.Text
{
public class StringBuilder
{
public StringBuilder Append(string s) => null;
public StringBuilder Append(object s) => null;
}
}";
var comp = CreateEmptyCompilation(source0);
comp.VerifyDiagnostics();
var ref0 = comp.EmitToImageReference();
var source1 =
@"using System;
record A<T> : IEquatable<A<T>>;
record B : A<int>, IEquatable<B>;
";
comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (1,1): hidden CS8019: Unnecessary using directive.
// using System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;").WithLocation(1, 1),
// (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported
// record A<T> : IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(2, 8),
// (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported
// record A<T> : IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(2, 8),
// (2,8): error CS0518: Predefined type 'System.Type' is not defined or imported
// record A<T> : IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 8),
// (2,8): error CS0115: 'A<T>.ToString()': no suitable method found to override
// record A<T> : IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.ToString()").WithLocation(2, 8),
// (2,8): error CS0115: 'A<T>.EqualityContract': no suitable method found to override
// record A<T> : IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.EqualityContract").WithLocation(2, 8),
// (2,8): error CS0115: 'A<T>.Equals(object?)': no suitable method found to override
// record A<T> : IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.Equals(object?)").WithLocation(2, 8),
// (2,8): error CS0115: 'A<T>.GetHashCode()': no suitable method found to override
// record A<T> : IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.GetHashCode()").WithLocation(2, 8),
// (2,8): error CS0115: 'A<T>.PrintMembers(StringBuilder)': no suitable method found to override
// record A<T> : IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8),
// (2,15): error CS0246: The type or namespace name 'IEquatable<>' could not be found (are you missing a using directive or an assembly reference?)
// record A<T> : IEquatable<A<T>>;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IEquatable<A<T>>").WithArguments("IEquatable<>").WithLocation(2, 15),
// (3,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported
// record B : A<int>, IEquatable<B>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(3, 8),
// (3,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported
// record B : A<int>, IEquatable<B>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(3, 8),
// (3,8): error CS0518: Predefined type 'System.Type' is not defined or imported
// record B : A<int>, IEquatable<B>;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.Type").WithLocation(3, 8),
// (3,20): error CS0246: The type or namespace name 'IEquatable<>' could not be found (are you missing a using directive or an assembly reference?)
// record B : A<int>, IEquatable<B>;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IEquatable<B>").WithArguments("IEquatable<>").WithLocation(3, 20));
var type = comp.GetMember<NamedTypeSymbol>("A");
AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
type = comp.GetMember<NamedTypeSymbol>("B");
AssertEx.Equal(new[] { "IEquatable<B>", "System.IEquatable<B>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings());
AssertEx.Equal(new[] { "System.IEquatable<A<System.Int32>>[missing]", "IEquatable<B>", "System.IEquatable<B>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings());
}
[Fact]
public void IEquatableT_12()
{
var source0 =
@"namespace System
{
public class Object
{
public virtual bool Equals(object other) => false;
public virtual int GetHashCode() => 0;
public virtual string ToString() => """";
}
public class String { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public interface IEquatable<T>
{
bool Equals(T other);
void Other();
}
}
namespace System.Text
{
public class StringBuilder
{
public StringBuilder Append(string s) => null;
public StringBuilder Append(object s) => null;
}
}";
var comp = CreateEmptyCompilation(source0);
comp.VerifyDiagnostics();
var ref0 = comp.EmitToImageReference();
var source1 =
@"record A;
class Program
{
static void Main()
{
System.IEquatable<A> a = new A();
_ = a.Equals(null);
}
}";
comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (1,8): error CS0518: Predefined type 'System.Type' is not defined or imported
// record A;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(1, 8),
// (1,8): error CS0535: 'A' does not implement interface member 'IEquatable<A>.Other()'
// record A;
Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "A").WithArguments("A", "System.IEquatable<A>.Other()").WithLocation(1, 8));
}
[Fact]
public void IEquatableT_13()
{
var source =
@"record A
{
internal virtual bool Equals(A other) => false;
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (1,8): error CS0737: 'A' does not implement interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement an interface member because it is not public.
// record A
Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)").WithLocation(1, 8),
// (3,27): error CS8873: Record member 'A.Equals(A)' must be public.
// internal virtual bool Equals(A other) => false;
Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(3, 27),
// (3,27): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode'
// internal virtual bool Equals(A other) => false;
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(3, 27)
);
}
[Fact]
public void IEquatableT_14()
{
var source =
@"record A
{
public bool Equals(A other) => false;
}
record B : A
{
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (3,17): error CS8872: 'A.Equals(A)' must allow overriding because the containing record is not sealed.
// public bool Equals(A other) => false;
Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(3, 17),
// (3,17): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode'
// public bool Equals(A other) => false;
Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(3, 17),
// (5,8): error CS0506: 'B.Equals(A?)': cannot override inherited member 'A.Equals(A)' because it is not marked virtual, abstract, or override
// record B : A
Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.Equals(A?)", "A.Equals(A)").WithLocation(5, 8));
}
[WorkItem(45026, "https://github.com/dotnet/roslyn/issues/45026")]
[Fact]
public void IEquatableT_15()
{
var source =
@"using System;
record R
{
bool IEquatable<R>.Equals(R other) => false;
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void IEquatableT_16()
{
var source =
@"using System;
class A<T>
{
record B<U> : IEquatable<B<T>>
{
bool IEquatable<B<T>>.Equals(B<T> other) => false;
bool IEquatable<B<U>>.Equals(B<U> other) => false;
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,12): error CS0695: 'A<T>.B<U>' cannot implement both 'IEquatable<A<T>.B<T>>' and 'IEquatable<A<T>.B<U>>' because they may unify for some type parameter substitutions
// record B<U> : IEquatable<B<T>>
Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "B").WithArguments("A<T>.B<U>", "System.IEquatable<A<T>.B<T>>", "System.IEquatable<A<T>.B<U>>").WithLocation(4, 12));
}
[Fact]
public void InterfaceImplementation()
{
var source = @"
interface I
{
int P1 { get; init; }
int P2 { get; init; }
int P3 { get; set; }
}
record R(int P1) : I
{
public int P2 { get; init; }
int I.P3 { get; set; }
public static void Main()
{
I r = new R(42) { P2 = 43 };
r.P3 = 44;
System.Console.Write((r.P1, r.P2, r.P3));
}
}
";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "(42, 43, 44)", verify: Verification.Skipped /* init-only */);
}
[Fact]
public void Initializers_01()
{
var src = @"
using System;
record C(int X)
{
int Z = X + 1;
public static void Main()
{
var c = new C(1);
Console.WriteLine(c.Z);
}
}";
var verifier = CompileAndVerify(src, expectedOutput: @"2").VerifyDiagnostics();
var comp = CreateCompilation(src);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First();
Assert.Equal("= X + 1", x.Parent!.Parent!.ToString());
var symbol = model.GetSymbolInfo(x).Symbol;
Assert.Equal(SymbolKind.Parameter, symbol!.Kind);
Assert.Equal("System.Int32 X", symbol.ToTestDisplayString());
Assert.Equal("C..ctor(System.Int32 X)", symbol.ContainingSymbol.ToTestDisplayString());
Assert.Equal("System.Int32 C.Z", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString());
Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X"));
Assert.Contains("X", model.LookupNames(x.SpanStart));
var recordDeclaration = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Single();
Assert.Equal("C", recordDeclaration.Identifier.ValueText);
Assert.Null(model.GetOperation(recordDeclaration));
}
[Fact]
public void Initializers_02()
{
var src = @"
record C(int X)
{
static int Z = X + 1;
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (4,20): error CS0236: A field initializer cannot reference the non-static field, method, or property 'C.X'
// static int Z = X + 1;
Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "X").WithArguments("C.X").WithLocation(4, 20)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First();
Assert.Equal("= X + 1", x.Parent!.Parent!.ToString());
var symbol = model.GetSymbolInfo(x).Symbol;
Assert.Equal(SymbolKind.Property, symbol!.Kind);
Assert.Equal("System.Int32 C.X { get; init; }", symbol.ToTestDisplayString());
Assert.Equal("C", symbol.ContainingSymbol.ToTestDisplayString());
Assert.Equal("System.Int32 C.Z", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString());
Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X"));
Assert.Contains("X", model.LookupNames(x.SpanStart));
}
[Fact]
public void Initializers_03()
{
var src = @"
record C(int X)
{
const int Z = X + 1;
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (4,19): error CS0236: A field initializer cannot reference the non-static field, method, or property 'C.X'
// const int Z = X + 1;
Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "X").WithArguments("C.X").WithLocation(4, 19)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First();
Assert.Equal("= X + 1", x.Parent!.Parent!.ToString());
var symbol = model.GetSymbolInfo(x).Symbol;
Assert.Equal(SymbolKind.Property, symbol!.Kind);
Assert.Equal("System.Int32 C.X { get; init; }", symbol.ToTestDisplayString());
Assert.Equal("C", symbol.ContainingSymbol.ToTestDisplayString());
Assert.Equal("System.Int32 C.Z", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString());
Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X"));
Assert.Contains("X", model.LookupNames(x.SpanStart));
}
[Fact]
public void Initializers_04()
{
var src = @"
using System;
record C(int X)
{
Func<int> Z = () => X + 1;
public static void Main()
{
var c = new C(1);
Console.WriteLine(c.Z());
}
}";
var verifier = CompileAndVerify(src, expectedOutput: @"2").VerifyDiagnostics();
var comp = CreateCompilation(src);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First();
Assert.Equal("() => X + 1", x.Parent!.Parent!.ToString());
var symbol = model.GetSymbolInfo(x).Symbol;
Assert.Equal(SymbolKind.Parameter, symbol!.Kind);
Assert.Equal("System.Int32 X", symbol.ToTestDisplayString());
Assert.Equal("C..ctor(System.Int32 X)", symbol.ContainingSymbol.ToTestDisplayString());
Assert.Equal("lambda expression", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString());
Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X"));
Assert.Contains("X", model.LookupNames(x.SpanStart));
}
[Fact]
public void Initializers_05()
{
var src = @"
using System;
record Base
{
public Base(Func<int> X)
{
Console.WriteLine(X());
}
public Base() {}
}
record C(int X) : Base(() => 100 + X++)
{
Func<int> Y = () => 200 + X++;
Func<int> Z = () => 300 + X++;
public static void Main()
{
var c = new C(1);
Console.WriteLine(c.Y());
Console.WriteLine(c.Z());
}
}";
var verifier = CompileAndVerify(src, expectedOutput: @"
101
202
303
").VerifyDiagnostics();
}
[Fact]
public void SynthesizedRecordPointerProperty()
{
var src = @"
record R(int P1, int* P2, delegate*<int> P3);";
var comp = CreateCompilation(src);
var p = comp.GlobalNamespace.GetTypeMember("R").GetMember<SourcePropertySymbolBase>("P1");
Assert.False(p.HasPointerType);
p = comp.GlobalNamespace.GetTypeMember("R").GetMember<SourcePropertySymbolBase>("P2");
Assert.True(p.HasPointerType);
p = comp.GlobalNamespace.GetTypeMember("R").GetMember<SourcePropertySymbolBase>("P3");
Assert.True(p.HasPointerType);
}
[Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")]
public void PositionalMemberModifiers_RefOrOut()
{
var src = @"
record R(ref int P1, out int P2);
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (2,8): error CS0177: The out parameter 'P2' must be assigned to before control leaves the current method
// record R(ref int P1, out int P2);
Diagnostic(ErrorCode.ERR_ParamUnassigned, "R").WithArguments("P2").WithLocation(2, 8),
// (2,10): error CS0631: ref and out are not valid in this context
// record R(ref int P1, out int P2);
Diagnostic(ErrorCode.ERR_IllegalRefParam, "ref").WithLocation(2, 10),
// (2,22): error CS0631: ref and out are not valid in this context
// record R(ref int P1, out int P2);
Diagnostic(ErrorCode.ERR_IllegalRefParam, "out").WithLocation(2, 22)
);
}
[Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")]
public void PositionalMemberModifiers_RefOrOut_WithBase()
{
var src = @"
record Base(int I);
record R(ref int P1, out int P2) : Base(P2 = 1);
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (3,10): error CS0631: ref and out are not valid in this context
// record R(ref int P1, out int P2) : Base(P2 = 1);
Diagnostic(ErrorCode.ERR_IllegalRefParam, "ref").WithLocation(3, 10),
// (3,22): error CS0631: ref and out are not valid in this context
// record R(ref int P1, out int P2) : Base(P2 = 1);
Diagnostic(ErrorCode.ERR_IllegalRefParam, "out").WithLocation(3, 22)
);
}
[Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")]
public void PositionalMemberModifiers_In()
{
var src = @"
record R(in int P1);
public class C
{
public static void Main()
{
var r = new R(42);
int i = 43;
var r2 = new R(in i);
System.Console.Write((r.P1, r2.P1));
}
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "(42, 43)", verify: Verification.Skipped /* init-only */);
var actualMembers = comp.GetMember<NamedTypeSymbol>("R").Constructors.ToTestDisplayStrings();
var expectedMembers = new[]
{
"R..ctor(in System.Int32 P1)",
"R..ctor(R original)"
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")]
public void PositionalMemberModifiers_This()
{
var src = @"
record R(this int i);
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (2,10): error CS0027: Keyword 'this' is not available in the current context
// record R(this int i);
Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(2, 10)
);
}
[Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")]
public void PositionalMemberModifiers_Params()
{
var src = @"
record R(params int[] Array);
public class C
{
public static void Main()
{
var r = new R(42, 43);
var r2 = new R(new[] { 44, 45 });
System.Console.Write((r.Array[0], r.Array[1], r2.Array[0], r2.Array[1]));
}
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "(42, 43, 44, 45)", verify: Verification.Skipped /* init-only */);
var actualMembers = comp.GetMember<NamedTypeSymbol>("R").Constructors.ToTestDisplayStrings();
var expectedMembers = new[]
{
"R..ctor(params System.Int32[] Array)",
"R..ctor(R original)"
};
AssertEx.Equal(expectedMembers, actualMembers);
}
[Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")]
public void PositionalMemberDefaultValue()
{
var src = @"
record R(int P = 42)
{
public static void Main()
{
var r = new R();
System.Console.Write(r.P);
}
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */);
}
[Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")]
public void PositionalMemberDefaultValue_AndPropertyWithInitializer()
{
var src = @"
record R(int P = 1)
{
public int P { get; init; } = 42;
public static void Main()
{
var r = new R();
System.Console.Write(r.P);
}
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (2,14): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name?
// record R(int P = 1)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 14)
);
var verifier = CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */);
verifier.VerifyIL("R..ctor(int)", @"
{
// Code size 16 (0x10)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 42
IL_0003: stfld ""int R.<P>k__BackingField""
IL_0008: ldarg.0
IL_0009: call ""object..ctor()""
IL_000e: nop
IL_000f: ret
}");
}
[Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")]
public void PositionalMemberDefaultValue_AndPropertyWithoutInitializer()
{
var src = @"
record R(int P = 42)
{
public int P { get; init; }
public static void Main()
{
var r = new R();
System.Console.Write(r.P);
}
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (2,14): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name?
// record R(int P = 42)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 14)
);
var verifier = CompileAndVerify(comp, expectedOutput: "0", verify: Verification.Skipped /* init-only */);
verifier.VerifyIL("R..ctor(int)", @"
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: nop
IL_0007: ret
}");
}
[Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")]
public void PositionalMemberDefaultValue_AndPropertyWithInitializer_CopyingParameter()
{
var src = @"
record R(int P = 42)
{
public int P { get; init; } = P;
public static void Main()
{
var r = new R();
System.Console.Write(r.P);
}
}
";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */);
verifier.VerifyIL("R..ctor(int)", @"
{
// Code size 15 (0xf)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld ""int R.<P>k__BackingField""
IL_0007: ldarg.0
IL_0008: call ""object..ctor()""
IL_000d: nop
IL_000e: ret
}");
}
[Fact]
public void AttributesOnPrimaryConstructorParameters_01()
{
string source = @"
[System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ]
public class A : System.Attribute
{
}
[System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = true) ]
public class B : System.Attribute
{
}
[System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ]
public class C : System.Attribute
{
}
[System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ]
public class D : System.Attribute
{
}
public record Test(
[field: A]
[property: B]
[param: C]
[D]
int P1)
{
}
";
Action<ModuleSymbol> symbolValidator = moduleSymbol =>
{
var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test");
var prop1 = @class.GetMember<PropertySymbol>("P1");
AssertEx.SetEqual(new[] { "B" }, getAttributeStrings(prop1));
var field1 = @class.GetMember<FieldSymbol>("<P1>k__BackingField");
AssertEx.SetEqual(new[] { "A" }, getAttributeStrings(field1));
var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0];
AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1));
};
var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator,
parseOptions: TestOptions.Regular9,
// init-only is unverifiable
verify: Verification.Skipped,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
comp.VerifyDiagnostics();
IEnumerable<string> getAttributeStrings(Symbol symbol)
{
return GetAttributeStrings(symbol.GetAttributes().Where(a => a.AttributeClass!.Name is "A" or "B" or "C" or "D"));
}
}
[Fact]
public void AttributesOnPrimaryConstructorParameters_02()
{
string source = @"
[System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true) ]
public class A : System.Attribute
{
}
[System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true) ]
public class B : System.Attribute
{
}
[System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true) ]
public class C : System.Attribute
{
}
[System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true) ]
public class D : System.Attribute
{
}
public record Test(
[field: A]
[property: B]
[param: C]
[D]
int P1)
{
}
";
Action<ModuleSymbol> symbolValidator = moduleSymbol =>
{
var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test");
var prop1 = @class.GetMember<PropertySymbol>("P1");
AssertEx.SetEqual(new[] { "B" }, getAttributeStrings(prop1));
var field1 = @class.GetMember<FieldSymbol>("<P1>k__BackingField");
AssertEx.SetEqual(new[] { "A" }, getAttributeStrings(field1));
var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0];
AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1));
};
var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator,
parseOptions: TestOptions.Regular9,
// init-only is unverifiable
verify: Verification.Skipped,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
comp.VerifyDiagnostics();
IEnumerable<string> getAttributeStrings(Symbol symbol)
{
return GetAttributeStrings(symbol.GetAttributes().Where(a =>
{
switch (a.AttributeClass!.Name)
{
case "A":
case "B":
case "C":
case "D":
return true;
}
return false;
}));
}
}
[Fact]
public void AttributesOnPrimaryConstructorParameters_03()
{
string source = @"
[System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ]
public class A : System.Attribute
{
}
[System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = true) ]
public class B : System.Attribute
{
}
[System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ]
public class C : System.Attribute
{
}
[System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ]
public class D : System.Attribute
{
}
public abstract record Base
{
public abstract int P1 { get; init; }
}
public record Test(
[field: A]
[property: B]
[param: C]
[D]
int P1) : Base
{
}
";
Action<ModuleSymbol> symbolValidator = moduleSymbol =>
{
var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test");
var prop1 = @class.GetMember<PropertySymbol>("P1");
AssertEx.SetEqual(new[] { "B" }, getAttributeStrings(prop1));
var field1 = @class.GetMember<FieldSymbol>("<P1>k__BackingField");
AssertEx.SetEqual(new[] { "A" }, getAttributeStrings(field1));
var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0];
AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1));
};
var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator,
parseOptions: TestOptions.Regular9,
// init-only is unverifiable
verify: Verification.Skipped,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
comp.VerifyDiagnostics();
IEnumerable<string> getAttributeStrings(Symbol symbol)
{
return GetAttributeStrings(symbol.GetAttributes().Where(a =>
{
switch (a.AttributeClass!.Name)
{
case "A":
case "B":
case "C":
case "D":
return true;
}
return false;
}));
}
}
[Fact]
public void AttributesOnPrimaryConstructorParameters_04()
{
string source = @"
[System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple = true) ]
public class A : System.Attribute
{
}
public record Test(
[method: A]
int P1)
{
[method: A]
void M1() {}
}
";
Action<ModuleSymbol> symbolValidator = moduleSymbol =>
{
var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test");
var prop1 = @class.GetMember<PropertySymbol>("P1");
AssertEx.SetEqual(new string[] { }, getAttributeStrings(prop1));
var field1 = @class.GetMember<FieldSymbol>("<P1>k__BackingField");
AssertEx.SetEqual(new string[] { }, getAttributeStrings(field1));
var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0];
AssertEx.SetEqual(new string[] { }, getAttributeStrings(param1));
};
var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator,
parseOptions: TestOptions.Regular9,
// init-only is unverifiable
verify: Verification.Skipped,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
comp.VerifyDiagnostics(
// (8,6): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property, param'. All attributes in this block will be ignored.
// [method: A]
Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "field, property, param").WithLocation(8, 6)
);
IEnumerable<string> getAttributeStrings(Symbol symbol)
{
return GetAttributeStrings(symbol.GetAttributes().Where(a =>
{
switch (a.AttributeClass!.Name)
{
case "A":
return true;
}
return false;
}));
}
}
[Fact]
public void AttributesOnPrimaryConstructorParameters_05()
{
string source = @"
[System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ]
public class A : System.Attribute
{
}
[System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = true) ]
public class B : System.Attribute
{
}
[System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ]
public class C : System.Attribute
{
}
[System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ]
public class D : System.Attribute
{
}
public abstract record Base
{
public virtual int P1 { get; init; }
}
public record Test(
[field: A]
[property: B]
[param: C]
[D]
int P1) : Base
{
}
";
Action<ModuleSymbol> symbolValidator = moduleSymbol =>
{
var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test");
Assert.Null(@class.GetMember<PropertySymbol>("P1"));
Assert.Null(@class.GetMember<FieldSymbol>("<P1>k__BackingField"));
var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0];
AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1));
};
var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator,
parseOptions: TestOptions.Regular9,
// init-only is unverifiable
verify: Verification.Skipped,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
comp.VerifyDiagnostics(
// (27,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored.
// [field: A]
Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "param").WithLocation(27, 6),
// (28,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored.
// [property: B]
Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "param").WithLocation(28, 6),
// (31,9): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// int P1) : Base
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(31, 9)
);
IEnumerable<string> getAttributeStrings(Symbol symbol)
{
return GetAttributeStrings(symbol.GetAttributes().Where(a =>
{
switch (a.AttributeClass!.Name)
{
case "A":
case "B":
case "C":
case "D":
return true;
}
return false;
}));
}
}
[Fact]
public void AttributesOnPrimaryConstructorParameters_06()
{
string source = @"
[System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ]
public class A : System.Attribute
{
}
[System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = true) ]
public class B : System.Attribute
{
}
[System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ]
public class C : System.Attribute
{
}
[System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ]
public class D : System.Attribute
{
}
public abstract record Base
{
public int P1 { get; init; }
}
public record Test(
[field: A]
[property: B]
[param: C]
[D]
int P1) : Base
{
}
";
Action<ModuleSymbol> symbolValidator = moduleSymbol =>
{
var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test");
Assert.Null(@class.GetMember<PropertySymbol>("P1"));
Assert.Null(@class.GetMember<FieldSymbol>("<P1>k__BackingField"));
var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0];
AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1));
};
var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator,
parseOptions: TestOptions.Regular9,
// init-only is unverifiable
verify: Verification.Skipped,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
comp.VerifyDiagnostics(
// (27,6): warning CS0657: 'field' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored.
// [field: A]
Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "param").WithLocation(27, 6),
// (28,6): warning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored.
// [property: B]
Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "param").WithLocation(28, 6),
// (31,9): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// int P1) : Base
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(31, 9)
);
IEnumerable<string> getAttributeStrings(Symbol symbol)
{
return GetAttributeStrings(symbol.GetAttributes().Where(a =>
{
switch (a.AttributeClass!.Name)
{
case "A":
case "B":
case "C":
case "D":
return true;
}
return false;
}));
}
}
[Fact]
public void AttributesOnPrimaryConstructorParameters_07()
{
string source = @"
[System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ]
public class C : System.Attribute
{
}
[System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ]
public class D : System.Attribute
{
}
public abstract record Base
{
public int P1 { get; init; }
}
public record Test(
[param: C]
[D]
int P1) : Base
{
}
";
Action<ModuleSymbol> symbolValidator = moduleSymbol =>
{
var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test");
var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0];
AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1));
};
var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator,
parseOptions: TestOptions.Regular9,
// init-only is unverifiable
verify: Verification.Skipped,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
comp.VerifyDiagnostics(
// (20,9): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name?
// int P1) : Base
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(20, 9)
);
IEnumerable<string> getAttributeStrings(Symbol symbol)
{
return GetAttributeStrings(symbol.GetAttributes().Where(a =>
{
switch (a.AttributeClass!.Name)
{
case "C":
case "D":
return true;
}
return false;
}));
}
}
[Fact]
public void AttributesOnPrimaryConstructorParameters_08()
{
string source = @"
#nullable enable
using System.Diagnostics.CodeAnalysis;
record C<T>([property: NotNull] T? P1, T? P2) where T : class
{
protected C(C<T> other)
{
T x = P1;
T y = P2;
}
}
";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition, NotNullAttributeDefinition }, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (10,15): warning CS8600: Converting null literal or possible null value to non-nullable type.
// T y = P2;
Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "P2").WithLocation(10, 15)
);
}
[Fact]
public void AttributesOnPrimaryConstructorParameters_09_CallerMemberName()
{
string source = @"
using System.Runtime.CompilerServices;
record R([CallerMemberName] string S = """");
class C
{
public static void Main()
{
var r = new R();
System.Console.Write(r.S);
}
}
";
var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, expectedOutput: "Main",
parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe, verify: Verification.Skipped /* init-only */);
comp.VerifyDiagnostics();
}
[Fact]
public void RecordWithConstraints_NullableWarning()
{
var src = @"
#nullable enable
record R<T>(T P) where T : class;
record R2<T>(T P) where T : class { }
public class C
{
public static void Main()
{
var r = new R<string?>(""R"");
var r2 = new R2<string?>(""R2"");
System.Console.Write((r.P, r2.P));
}
}";
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (10,23): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'R<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint.
// var r = new R<string?>("R");
Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("R<T>", "T", "string?").WithLocation(10, 23),
// (11,25): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'R2<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint.
// var r2 = new R2<string?>("R2");
Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("R2<T>", "T", "string?").WithLocation(11, 25)
);
CompileAndVerify(comp, expectedOutput: "(R, R2)", verify: Verification.Skipped /* init-only */);
}
[Fact]
public void RecordWithConstraints_ConstraintError()
{
var src = @"
record R<T>(T P) where T : class;
record R2<T>(T P) where T : class { }
public class C
{
public static void Main()
{
_ = new R<int>(1);
_ = new R2<int>(2);
}
}";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (9,19): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'R<T>'
// _ = new R<int>(1);
Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("R<T>", "T", "int").WithLocation(9, 19),
// (10,20): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'R2<T>'
// _ = new R2<int>(2);
Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("R2<T>", "T", "int").WithLocation(10, 20)
);
}
[Fact]
public void AccessCheckProtected03()
{
CSharpCompilation c = CreateCompilation(@"
record X<T> { }
record A { }
record B
{
record C : X<C.D.E>
{
protected record D : A
{
public record E { }
}
}
}
", targetFramework: TargetFramework.StandardLatest);
Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, c.Assembly.RuntimeSupportsCovariantReturnsOfClasses);
if (c.Assembly.RuntimeSupportsCovariantReturnsOfClasses)
{
c.VerifyDiagnostics(
// (8,12): error CS0060: Inconsistent accessibility: base type 'X<B.C.D.E>' is less accessible than class 'B.C'
// record C : X<C.D.E>
Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C").WithArguments("B.C", "X<B.C.D.E>").WithLocation(8, 12),
// (8,12): error CS0051: Inconsistent accessibility: parameter type 'X<B.C.D.E>' is less accessible than method 'B.C.Equals(X<B.C.D.E>?)'
// record C : X<C.D.E>
Diagnostic(ErrorCode.ERR_BadVisParamType, "C").WithArguments("B.C.Equals(X<B.C.D.E>?)", "X<B.C.D.E>").WithLocation(8, 12)
);
}
else
{
c.VerifyDiagnostics(
// (8,12): error CS0060: Inconsistent accessibility: base type 'X<B.C.D.E>' is less accessible than class 'B.C'
// record C : X<C.D.E>
Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C").WithArguments("B.C", "X<B.C.D.E>").WithLocation(8, 12),
// (8,12): error CS0050: Inconsistent accessibility: return type 'X<B.C.D.E>' is less accessible than method 'B.C.<Clone>$()'
// record C : X<C.D.E>
Diagnostic(ErrorCode.ERR_BadVisReturnType, "C").WithArguments("B.C.<Clone>$()", "X<B.C.D.E>").WithLocation(8, 12),
// (8,12): error CS0051: Inconsistent accessibility: parameter type 'X<B.C.D.E>' is less accessible than method 'B.C.Equals(X<B.C.D.E>?)'
// record C : X<C.D.E>
Diagnostic(ErrorCode.ERR_BadVisParamType, "C").WithArguments("B.C.Equals(X<B.C.D.E>?)", "X<B.C.D.E>").WithLocation(8, 12)
);
}
}
[Fact]
public void TestTargetType_Abstract()
{
var source = @"
abstract record C
{
void M()
{
C x0 = new();
var x1 = (C)new();
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,16): error CS0144: Cannot create an instance of the abstract type or interface 'C'
// C x0 = new();
Diagnostic(ErrorCode.ERR_NoNewAbstract, "new()").WithArguments("C").WithLocation(6, 16),
// (7,21): error CS0144: Cannot create an instance of the abstract type or interface 'C'
// var x1 = (C)new();
Diagnostic(ErrorCode.ERR_NoNewAbstract, "new()").WithArguments("C").WithLocation(7, 21)
);
}
[Fact]
public void CyclicBases4()
{
var text =
@"
record A<T> : B<A<T>> { }
record B<T> : A<B<T>> {
A<T> F() { return null; }
}
";
var comp = CreateCompilation(text);
comp.GetDeclarationDiagnostics().Verify(
// (2,8): error CS0146: Circular base type dependency involving 'B<A<T>>' and 'A<T>'
// record A<T> : B<A<T>> { }
Diagnostic(ErrorCode.ERR_CircularBase, "A").WithArguments("B<A<T>>", "A<T>").WithLocation(2, 8),
// (3,8): error CS0146: Circular base type dependency involving 'A<B<T>>' and 'B<T>'
// record B<T> : A<B<T>> {
Diagnostic(ErrorCode.ERR_CircularBase, "B").WithArguments("A<B<T>>", "B<T>").WithLocation(3, 8),
// (2,8): error CS0115: 'A<T>.ToString()': no suitable method found to override
// record A<T> : B<A<T>> { }
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.ToString()").WithLocation(2, 8),
// (2,8): error CS0115: 'A<T>.EqualityContract': no suitable method found to override
// record A<T> : B<A<T>> { }
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.EqualityContract").WithLocation(2, 8),
// (2,8): error CS0115: 'A<T>.Equals(object?)': no suitable method found to override
// record A<T> : B<A<T>> { }
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.Equals(object?)").WithLocation(2, 8),
// (2,8): error CS0115: 'A<T>.GetHashCode()': no suitable method found to override
// record A<T> : B<A<T>> { }
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.GetHashCode()").WithLocation(2, 8),
// (2,8): error CS0115: 'A<T>.PrintMembers(StringBuilder)': no suitable method found to override
// record A<T> : B<A<T>> { }
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8),
// (3,8): error CS0115: 'B<T>.EqualityContract': no suitable method found to override
// record B<T> : A<B<T>> {
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B<T>.EqualityContract").WithLocation(3, 8),
// (3,8): error CS0115: 'B<T>.Equals(object?)': no suitable method found to override
// record B<T> : A<B<T>> {
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B<T>.Equals(object?)").WithLocation(3, 8),
// (3,8): error CS0115: 'B<T>.GetHashCode()': no suitable method found to override
// record B<T> : A<B<T>> {
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B<T>.GetHashCode()").WithLocation(3, 8),
// (3,8): error CS0115: 'B<T>.PrintMembers(StringBuilder)': no suitable method found to override
// record B<T> : A<B<T>> {
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B<T>.PrintMembers(System.Text.StringBuilder)").WithLocation(3, 8),
// (3,8): error CS0115: 'B<T>.ToString()': no suitable method found to override
// record B<T> : A<B<T>> {
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B<T>.ToString()").WithLocation(3, 8)
);
}
[Fact]
public void CS0250ERR_CallingBaseFinalizeDeprecated()
{
var text = @"
record B
{
}
record C : B
{
~C()
{
base.Finalize(); // CS0250
}
public static void Main()
{
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (10,7): error CS0250: Do not directly call your base type Finalize method. It is called automatically from your destructor.
Diagnostic(ErrorCode.ERR_CallingBaseFinalizeDeprecated, "base.Finalize()")
);
}
[Fact]
public void PartialClassWithDifferentTupleNamesInBaseTypes()
{
var source = @"
public record Base<T> { }
public partial record C1 : Base<(int a, int b)> { }
public partial record C1 : Base<(int notA, int notB)> { }
public partial record C2 : Base<(int a, int b)> { }
public partial record C2 : Base<(int, int)> { }
public partial record C3 : Base<(int a, int b)> { }
public partial record C3 : Base<(int a, int b)> { }
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (5,23): error CS0263: Partial declarations of 'C2' must not specify different base classes
// public partial record C2 : Base<(int a, int b)> { }
Diagnostic(ErrorCode.ERR_PartialMultipleBases, "C2").WithArguments("C2").WithLocation(5, 23),
// (3,23): error CS0263: Partial declarations of 'C1' must not specify different base classes
// public partial record C1 : Base<(int a, int b)> { }
Diagnostic(ErrorCode.ERR_PartialMultipleBases, "C1").WithArguments("C1").WithLocation(3, 23),
// (5,23): error CS0115: 'C2.ToString()': no suitable method found to override
// public partial record C2 : Base<(int a, int b)> { }
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.ToString()").WithLocation(5, 23),
// (5,23): error CS0115: 'C2.EqualityContract': no suitable method found to override
// public partial record C2 : Base<(int a, int b)> { }
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.EqualityContract").WithLocation(5, 23),
// (5,23): error CS0115: 'C2.Equals(object?)': no suitable method found to override
// public partial record C2 : Base<(int a, int b)> { }
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.Equals(object?)").WithLocation(5, 23),
// (5,23): error CS0115: 'C2.GetHashCode()': no suitable method found to override
// public partial record C2 : Base<(int a, int b)> { }
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.GetHashCode()").WithLocation(5, 23),
// (5,23): error CS0115: 'C2.PrintMembers(StringBuilder)': no suitable method found to override
// public partial record C2 : Base<(int a, int b)> { }
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.PrintMembers(System.Text.StringBuilder)").WithLocation(5, 23),
// (3,23): error CS0115: 'C1.ToString()': no suitable method found to override
// public partial record C1 : Base<(int a, int b)> { }
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C1").WithArguments("C1.ToString()").WithLocation(3, 23),
// (3,23): error CS0115: 'C1.EqualityContract': no suitable method found to override
// public partial record C1 : Base<(int a, int b)> { }
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C1").WithArguments("C1.EqualityContract").WithLocation(3, 23),
// (3,23): error CS0115: 'C1.Equals(object?)': no suitable method found to override
// public partial record C1 : Base<(int a, int b)> { }
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C1").WithArguments("C1.Equals(object?)").WithLocation(3, 23),
// (3,23): error CS0115: 'C1.GetHashCode()': no suitable method found to override
// public partial record C1 : Base<(int a, int b)> { }
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C1").WithArguments("C1.GetHashCode()").WithLocation(3, 23),
// (3,23): error CS0115: 'C1.PrintMembers(StringBuilder)': no suitable method found to override
// public partial record C1 : Base<(int a, int b)> { }
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C1").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(3, 23)
);
}
[Fact]
public void CS0267ERR_PartialMisplaced()
{
var test = @"
partial public record C // CS0267
{
}
";
CreateCompilation(test).VerifyDiagnostics(
// (2,1): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type.
// partial public class C // CS0267
Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(2, 1));
}
[Fact]
public void AttributeContainsGeneric()
{
string source = @"
[Goo<int>]
class G
{
}
record Goo<T>
{
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (2,2): error CS0404: Cannot apply attribute class 'Goo<T>' because it is generic
// [Goo<int>]
Diagnostic(ErrorCode.ERR_AttributeCantBeGeneric, "Goo<int>").WithArguments("Goo<T>").WithLocation(2, 2)
);
}
[Fact]
public void CS0406ERR_ClassBoundNotFirst()
{
var source =
@"interface I { }
record A { }
record B { }
class C<T, U>
where T : I, A
where U : A, B
{
void M<V>() where V : U, A, B { }
}";
CreateCompilation(source).VerifyDiagnostics(
// (5,18): error CS0406: The class type constraint 'A' must come before any other constraints
Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "A").WithArguments("A").WithLocation(5, 18),
// (6,18): error CS0406: The class type constraint 'B' must come before any other constraints
Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "B").WithArguments("B").WithLocation(6, 18),
// (8,30): error CS0406: The class type constraint 'A' must come before any other constraints
Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "A").WithArguments("A").WithLocation(8, 30),
// (8,33): error CS0406: The class type constraint 'B' must come before any other constraints
Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "B").WithArguments("B").WithLocation(8, 33));
}
[Fact]
public void SealedStaticRecord()
{
var source = @"
sealed static record R;
";
CreateCompilation(source).VerifyDiagnostics(
// (2,22): error CS0106: The modifier 'static' is not valid for this item
// sealed static record R;
Diagnostic(ErrorCode.ERR_BadMemberFlag, "R").WithArguments("static").WithLocation(2, 22)
);
}
[Fact]
public void CS0513ERR_AbstractInConcreteClass02()
{
var text = @"
record C
{
public abstract event System.Action E;
public abstract int this[int x] { get; set; }
}
";
CreateCompilation(text).VerifyDiagnostics(
// (4,41): error CS0513: 'C.E' is abstract but it is contained in non-abstract type 'C'
// public abstract event System.Action E;
Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "E").WithArguments("C.E", "C"),
// (5,39): error CS0513: 'C.this[int].get' is abstract but it is contained in non-abstract type 'C'
// public abstract int this[int x] { get; set; }
Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "get").WithArguments("C.this[int].get", "C"),
// (5,44): error CS0513: 'C.this[int].set' is abstract but it is contained in non-abstract type 'C'
// public abstract int this[int x] { get; set; }
Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "set").WithArguments("C.this[int].set", "C"));
}
[Fact]
public void ConversionToBase()
{
var source = @"
public record Base<T> { }
public record Derived : Base<(int a, int b)>
{
public static explicit operator Base<(int, int)>(Derived x)
{
return null;
}
public static explicit operator Derived(Base<(int, int)> x)
{
return null;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (9,37): error CS0553: 'Derived.explicit operator Derived(Base<(int, int)>)': user-defined conversions to or from a base type are not allowed
// public static explicit operator Derived(Base<(int, int)> x)
Diagnostic(ErrorCode.ERR_ConversionWithBase, "Derived").WithArguments("Derived.explicit operator Derived(Base<(int, int)>)").WithLocation(9, 37),
// (5,37): error CS0553: 'Derived.explicit operator Base<(int, int)>(Derived)': user-defined conversions to or from a base type are not allowed
// public static explicit operator Base<(int, int)>(Derived x)
Diagnostic(ErrorCode.ERR_ConversionWithBase, "Base<(int, int)>").WithArguments("Derived.explicit operator Base<(int, int)>(Derived)").WithLocation(5, 37)
);
}
[Fact]
public void CS0554ERR_ConversionWithDerived()
{
var text = @"
public record B
{
public static implicit operator B(D d) // CS0554
{
return null;
}
}
public record D : B {}
";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (4,37): error CS0554: 'B.implicit operator B(D)': user-defined conversions to or from a derived type are not allowed
// public static implicit operator B(D d) // CS0554
Diagnostic(ErrorCode.ERR_ConversionWithDerived, "B").WithArguments("B.implicit operator B(D)")
);
}
[Fact]
public void CS0574ERR_BadDestructorName()
{
var test = @"
namespace x
{
public record iii
{
~iiii(){}
public static void Main()
{
}
}
}
";
CreateCompilation(test).VerifyDiagnostics(
// (6,10): error CS0574: Name of destructor must match name of type
// ~iiii(){}
Diagnostic(ErrorCode.ERR_BadDestructorName, "iiii").WithLocation(6, 10));
}
[Fact]
public void StaticBasePartial()
{
var text = @"
static record NV
{
}
public partial record C1
{
}
partial record C1 : NV
{
}
public partial record C1
{
}
";
var comp = CreateCompilation(text, targetFramework: TargetFramework.StandardLatest);
Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses);
if (comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses)
{
comp.VerifyDiagnostics(
// (2,15): error CS0106: The modifier 'static' is not valid for this item
// static record NV
Diagnostic(ErrorCode.ERR_BadMemberFlag, "NV").WithArguments("static").WithLocation(2, 15),
// (6,23): error CS0051: Inconsistent accessibility: parameter type 'NV' is less accessible than method 'C1.Equals(NV?)'
// public partial record C1
Diagnostic(ErrorCode.ERR_BadVisParamType, "C1").WithArguments("C1.Equals(NV?)", "NV").WithLocation(6, 23),
// (10,16): error CS0060: Inconsistent accessibility: base class 'NV' is less accessible than class 'C1'
// partial record C1 : NV
Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C1").WithArguments("C1", "NV").WithLocation(10, 16)
);
}
else
{
comp.VerifyDiagnostics(
// (2,15): error CS0106: The modifier 'static' is not valid for this item
// static record NV
Diagnostic(ErrorCode.ERR_BadMemberFlag, "NV").WithArguments("static").WithLocation(2, 15),
// (6,23): error CS0050: Inconsistent accessibility: return type 'NV' is less accessible than method 'C1.<Clone>$()'
// public partial record C1
Diagnostic(ErrorCode.ERR_BadVisReturnType, "C1").WithArguments("C1.<Clone>$()", "NV").WithLocation(6, 23),
// (6,23): error CS0051: Inconsistent accessibility: parameter type 'NV' is less accessible than method 'C1.Equals(NV?)'
// public partial record C1
Diagnostic(ErrorCode.ERR_BadVisParamType, "C1").WithArguments("C1.Equals(NV?)", "NV").WithLocation(6, 23),
// (10,16): error CS0060: Inconsistent accessibility: base class 'NV' is less accessible than class 'C1'
// partial record C1 : NV
Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C1").WithArguments("C1", "NV").WithLocation(10, 16)
);
}
}
[Fact]
public void StaticRecordWithConstructorAndDestructor()
{
var text = @"
static record R(int I)
{
R() : this(0) { }
~R() { }
}
";
var comp = CreateCompilation(text);
comp.VerifyDiagnostics(
// (2,15): error CS0106: The modifier 'static' is not valid for this item
// static record R(int I)
Diagnostic(ErrorCode.ERR_BadMemberFlag, "R").WithArguments("static").WithLocation(2, 15)
);
}
[Fact]
public void RecordWithPartialMethodExplicitImplementation()
{
var source =
@"record R
{
partial void M();
}";
CreateCompilation(source).VerifyDiagnostics(
// (3,18): error CS0751: A partial method must be declared within a partial type
// partial void M();
Diagnostic(ErrorCode.ERR_PartialMethodOnlyInPartialClass, "M").WithLocation(3, 18)
);
}
[Fact]
public void RecordWithMultipleBaseTypes()
{
var source = @"
record Base1;
record Base2;
record R : Base1, Base2
{
}";
CreateCompilation(source).VerifyDiagnostics(
// (4,19): error CS1721: Class 'R' cannot have multiple base classes: 'Base1' and 'Base2'
// record R : Base1, Base2
Diagnostic(ErrorCode.ERR_NoMultipleInheritance, "Base2").WithArguments("R", "Base1", "Base2").WithLocation(4, 19)
);
}
[Fact]
public void RecordWithInterfaceBeforeBase()
{
var source = @"
record Base;
interface I { }
record R : I, Base;
";
CreateCompilation(source).VerifyDiagnostics(
// (4,15): error CS1722: Base class 'Base' must come before any interfaces
// record R : I, Base;
Diagnostic(ErrorCode.ERR_BaseClassMustBeFirst, "Base").WithArguments("Base").WithLocation(4, 15)
);
}
[Fact]
public void RecordLoadedInVisualBasicDisplaysAsClass()
{
var src = @"
public record A;
";
var compRef = CreateCompilation(src).EmitToImageReference();
var vbComp = CreateVisualBasicCompilation("", referencedAssemblies: new[] { compRef });
var symbol = vbComp.GlobalNamespace.GetTypeMember("A");
Assert.False(symbol.IsRecord);
Assert.Equal("class A",
SymbolDisplay.ToDisplayString(symbol, SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword)));
}
[Fact]
public void AnalyzerActions_01()
{
var text1 = @"
record A([Attr1]int X = 0) : I1
{}
record B([Attr2]int Y = 1) : A(2), I1
{
int M() => 3;
}
record C : A, I1
{
C([Attr3]int Z = 4) : base(5)
{}
}
interface I1 {}
class Attr1 : System.Attribute {}
class Attr2 : System.Attribute {}
class Attr3 : System.Attribute {}
";
var analyzer = new AnalyzerActions_01_Analyzer();
var comp = CreateCompilation(text1);
comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify();
Assert.Equal(1, analyzer.FireCount0);
Assert.Equal(1, analyzer.FireCount1);
Assert.Equal(1, analyzer.FireCount2);
Assert.Equal(1, analyzer.FireCount3);
Assert.Equal(1, analyzer.FireCount4);
Assert.Equal(1, analyzer.FireCount5);
Assert.Equal(1, analyzer.FireCount6);
Assert.Equal(1, analyzer.FireCount7);
Assert.Equal(1, analyzer.FireCount8);
Assert.Equal(1, analyzer.FireCount9);
Assert.Equal(1, analyzer.FireCount10);
Assert.Equal(1, analyzer.FireCount11);
Assert.Equal(1, analyzer.FireCount12);
Assert.Equal(1, analyzer.FireCount13);
Assert.Equal(1, analyzer.FireCount14);
Assert.Equal(1, analyzer.FireCount15);
Assert.Equal(1, analyzer.FireCount16);
Assert.Equal(1, analyzer.FireCount17);
Assert.Equal(1, analyzer.FireCount18);
Assert.Equal(1, analyzer.FireCount19);
Assert.Equal(1, analyzer.FireCount20);
Assert.Equal(1, analyzer.FireCount21);
Assert.Equal(1, analyzer.FireCount22);
Assert.Equal(1, analyzer.FireCount23);
Assert.Equal(1, analyzer.FireCount24);
Assert.Equal(1, analyzer.FireCount25);
Assert.Equal(1, analyzer.FireCount26);
Assert.Equal(1, analyzer.FireCount27);
Assert.Equal(1, analyzer.FireCount28);
Assert.Equal(1, analyzer.FireCount29);
Assert.Equal(1, analyzer.FireCount30);
Assert.Equal(1, analyzer.FireCount31);
}
private class AnalyzerActions_01_Analyzer : DiagnosticAnalyzer
{
public int FireCount0;
public int FireCount1;
public int FireCount2;
public int FireCount3;
public int FireCount4;
public int FireCount5;
public int FireCount6;
public int FireCount7;
public int FireCount8;
public int FireCount9;
public int FireCount10;
public int FireCount11;
public int FireCount12;
public int FireCount13;
public int FireCount14;
public int FireCount15;
public int FireCount16;
public int FireCount17;
public int FireCount18;
public int FireCount19;
public int FireCount20;
public int FireCount21;
public int FireCount22;
public int FireCount23;
public int FireCount24;
public int FireCount25;
public int FireCount26;
public int FireCount27;
public int FireCount28;
public int FireCount29;
public int FireCount30;
public int FireCount31;
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.NumericLiteralExpression);
context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.EqualsValueClause);
context.RegisterSyntaxNodeAction(Handle3, SyntaxKind.BaseConstructorInitializer);
context.RegisterSyntaxNodeAction(Handle4, SyntaxKind.ConstructorDeclaration);
context.RegisterSyntaxNodeAction(Handle5, SyntaxKind.PrimaryConstructorBaseType);
context.RegisterSyntaxNodeAction(Handle6, SyntaxKind.RecordDeclaration);
context.RegisterSyntaxNodeAction(Handle7, SyntaxKind.IdentifierName);
context.RegisterSyntaxNodeAction(Handle8, SyntaxKind.SimpleBaseType);
context.RegisterSyntaxNodeAction(Handle9, SyntaxKind.ParameterList);
context.RegisterSyntaxNodeAction(Handle10, SyntaxKind.ArgumentList);
}
protected void Handle1(SyntaxNodeAnalysisContext context)
{
var literal = (LiteralExpressionSyntax)context.Node;
switch (literal.ToString())
{
case "0":
Interlocked.Increment(ref FireCount0);
Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString());
break;
case "1":
Interlocked.Increment(ref FireCount1);
Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString());
break;
case "2":
Interlocked.Increment(ref FireCount2);
Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString());
break;
case "3":
Interlocked.Increment(ref FireCount3);
Assert.Equal("System.Int32 B.M()", context.ContainingSymbol.ToTestDisplayString());
break;
case "4":
Interlocked.Increment(ref FireCount4);
Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString());
break;
case "5":
Interlocked.Increment(ref FireCount5);
Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString());
break;
default:
Assert.True(false);
break;
}
Assert.Same(literal.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree);
}
protected void Handle2(SyntaxNodeAnalysisContext context)
{
var equalsValue = (EqualsValueClauseSyntax)context.Node;
switch (equalsValue.ToString())
{
case "= 0":
Interlocked.Increment(ref FireCount15);
Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString());
break;
case "= 1":
Interlocked.Increment(ref FireCount16);
Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString());
break;
case "= 4":
Interlocked.Increment(ref FireCount6);
Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString());
break;
default:
Assert.True(false);
break;
}
Assert.Same(equalsValue.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree);
}
protected void Handle3(SyntaxNodeAnalysisContext context)
{
var initializer = (ConstructorInitializerSyntax)context.Node;
switch (initializer.ToString())
{
case ": base(5)":
Interlocked.Increment(ref FireCount7);
Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString());
break;
default:
Assert.True(false);
break;
}
Assert.Same(initializer.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree);
}
protected void Handle4(SyntaxNodeAnalysisContext context)
{
Interlocked.Increment(ref FireCount8);
Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString());
}
protected void Handle5(SyntaxNodeAnalysisContext context)
{
var baseType = (PrimaryConstructorBaseTypeSyntax)context.Node;
switch (baseType.ToString())
{
case "A(2)":
switch (context.ContainingSymbol.ToTestDisplayString())
{
case "B..ctor([System.Int32 Y = 1])":
Interlocked.Increment(ref FireCount9);
break;
case "B":
Interlocked.Increment(ref FireCount17);
break;
default:
Assert.True(false);
break;
}
break;
default:
Assert.True(false);
break;
}
Assert.Same(baseType.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree);
}
protected void Handle6(SyntaxNodeAnalysisContext context)
{
var record = (RecordDeclarationSyntax)context.Node;
switch (context.ContainingSymbol.ToTestDisplayString())
{
case "B..ctor([System.Int32 Y = 1])":
Interlocked.Increment(ref FireCount10);
break;
case "B":
Interlocked.Increment(ref FireCount11);
break;
case "A":
Interlocked.Increment(ref FireCount12);
break;
case "C":
Interlocked.Increment(ref FireCount13);
break;
case "A..ctor([System.Int32 X = 0])":
Interlocked.Increment(ref FireCount14);
break;
default:
Assert.True(false);
break;
}
Assert.Same(record.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree);
}
protected void Handle7(SyntaxNodeAnalysisContext context)
{
var identifier = (IdentifierNameSyntax)context.Node;
switch (identifier.Identifier.ValueText)
{
case "A":
switch (identifier.Parent!.ToString())
{
case "A(2)":
Interlocked.Increment(ref FireCount18);
Assert.Equal("B", context.ContainingSymbol.ToTestDisplayString());
break;
case "A":
Interlocked.Increment(ref FireCount19);
Assert.Equal(SyntaxKind.SimpleBaseType, identifier.Parent.Kind());
Assert.Equal("C", context.ContainingSymbol.ToTestDisplayString());
break;
default:
Assert.True(false);
break;
}
break;
case "Attr1":
Interlocked.Increment(ref FireCount24);
Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString());
break;
case "Attr2":
Interlocked.Increment(ref FireCount25);
Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString());
break;
case "Attr3":
Interlocked.Increment(ref FireCount26);
Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString());
break;
}
}
protected void Handle8(SyntaxNodeAnalysisContext context)
{
var baseType = (SimpleBaseTypeSyntax)context.Node;
switch (baseType.ToString())
{
case "I1":
switch (context.ContainingSymbol.ToTestDisplayString())
{
case "A":
Interlocked.Increment(ref FireCount20);
break;
case "B":
Interlocked.Increment(ref FireCount21);
break;
case "C":
Interlocked.Increment(ref FireCount22);
break;
default:
Assert.True(false);
break;
}
break;
case "A":
switch (context.ContainingSymbol.ToTestDisplayString())
{
case "C":
Interlocked.Increment(ref FireCount23);
break;
default:
Assert.True(false);
break;
}
break;
case "System.Attribute":
break;
default:
Assert.True(false);
break;
}
}
protected void Handle9(SyntaxNodeAnalysisContext context)
{
var parameterList = (ParameterListSyntax)context.Node;
switch (parameterList.ToString())
{
case "([Attr1]int X = 0)":
Interlocked.Increment(ref FireCount27);
Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString());
break;
case "([Attr2]int Y = 1)":
Interlocked.Increment(ref FireCount28);
Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString());
break;
case "([Attr3]int Z = 4)":
Interlocked.Increment(ref FireCount29);
Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString());
break;
case "()":
break;
default:
Assert.True(false);
break;
}
}
protected void Handle10(SyntaxNodeAnalysisContext context)
{
var argumentList = (ArgumentListSyntax)context.Node;
switch (argumentList.ToString())
{
case "(2)":
Interlocked.Increment(ref FireCount30);
Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString());
break;
case "(5)":
Interlocked.Increment(ref FireCount31);
Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString());
break;
default:
Assert.True(false);
break;
}
}
}
[Fact]
public void AnalyzerActions_02()
{
var text1 = @"
record A(int X = 0)
{}
record C
{
C(int Z = 4)
{}
}
";
var analyzer = new AnalyzerActions_02_Analyzer();
var comp = CreateCompilation(text1);
comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify();
Assert.Equal(1, analyzer.FireCount1);
Assert.Equal(1, analyzer.FireCount2);
Assert.Equal(1, analyzer.FireCount3);
Assert.Equal(1, analyzer.FireCount4);
Assert.Equal(1, analyzer.FireCount5);
Assert.Equal(1, analyzer.FireCount6);
Assert.Equal(1, analyzer.FireCount7);
}
private class AnalyzerActions_02_Analyzer : DiagnosticAnalyzer
{
public int FireCount1;
public int FireCount2;
public int FireCount3;
public int FireCount4;
public int FireCount5;
public int FireCount6;
public int FireCount7;
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterSymbolAction(Handle, SymbolKind.Method);
context.RegisterSymbolAction(Handle, SymbolKind.Property);
context.RegisterSymbolAction(Handle, SymbolKind.Parameter);
context.RegisterSymbolAction(Handle, SymbolKind.NamedType);
}
private void Handle(SymbolAnalysisContext context)
{
switch (context.Symbol.ToTestDisplayString())
{
case "A..ctor([System.Int32 X = 0])":
Interlocked.Increment(ref FireCount1);
break;
case "System.Int32 A.X { get; init; }":
Interlocked.Increment(ref FireCount2);
break;
case "[System.Int32 X = 0]":
Interlocked.Increment(ref FireCount3);
break;
case "C..ctor([System.Int32 Z = 4])":
Interlocked.Increment(ref FireCount4);
break;
case "[System.Int32 Z = 4]":
Interlocked.Increment(ref FireCount5);
break;
case "A":
Interlocked.Increment(ref FireCount6);
break;
case "C":
Interlocked.Increment(ref FireCount7);
break;
case "System.Runtime.CompilerServices.IsExternalInit":
break;
default:
Assert.True(false);
break;
}
}
}
[Fact]
public void AnalyzerActions_03()
{
var text1 = @"
record A(int X = 0)
{}
record C
{
C(int Z = 4)
{}
}
";
var analyzer = new AnalyzerActions_03_Analyzer();
var comp = CreateCompilation(text1);
comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify();
Assert.Equal(1, analyzer.FireCount1);
Assert.Equal(1, analyzer.FireCount2);
Assert.Equal(0, analyzer.FireCount3);
Assert.Equal(1, analyzer.FireCount4);
Assert.Equal(0, analyzer.FireCount5);
Assert.Equal(1, analyzer.FireCount6);
Assert.Equal(1, analyzer.FireCount7);
Assert.Equal(1, analyzer.FireCount8);
Assert.Equal(1, analyzer.FireCount9);
Assert.Equal(1, analyzer.FireCount10);
Assert.Equal(1, analyzer.FireCount11);
Assert.Equal(1, analyzer.FireCount12);
}
private class AnalyzerActions_03_Analyzer : DiagnosticAnalyzer
{
public int FireCount1;
public int FireCount2;
public int FireCount3;
public int FireCount4;
public int FireCount5;
public int FireCount6;
public int FireCount7;
public int FireCount8;
public int FireCount9;
public int FireCount10;
public int FireCount11;
public int FireCount12;
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterSymbolStartAction(Handle1, SymbolKind.Method);
context.RegisterSymbolStartAction(Handle1, SymbolKind.Property);
context.RegisterSymbolStartAction(Handle1, SymbolKind.Parameter);
context.RegisterSymbolStartAction(Handle1, SymbolKind.NamedType);
}
private void Handle1(SymbolStartAnalysisContext context)
{
switch (context.Symbol.ToTestDisplayString())
{
case "A..ctor([System.Int32 X = 0])":
Interlocked.Increment(ref FireCount1);
context.RegisterSymbolEndAction(Handle2);
break;
case "System.Int32 A.X { get; init; }":
Interlocked.Increment(ref FireCount2);
context.RegisterSymbolEndAction(Handle3);
break;
case "[System.Int32 X = 0]":
Interlocked.Increment(ref FireCount3);
break;
case "C..ctor([System.Int32 Z = 4])":
Interlocked.Increment(ref FireCount4);
context.RegisterSymbolEndAction(Handle4);
break;
case "[System.Int32 Z = 4]":
Interlocked.Increment(ref FireCount5);
break;
case "A":
Interlocked.Increment(ref FireCount9);
Assert.Equal(0, FireCount1);
Assert.Equal(0, FireCount2);
Assert.Equal(0, FireCount6);
Assert.Equal(0, FireCount7);
context.RegisterSymbolEndAction(Handle5);
break;
case "C":
Interlocked.Increment(ref FireCount10);
Assert.Equal(0, FireCount4);
Assert.Equal(0, FireCount8);
context.RegisterSymbolEndAction(Handle6);
break;
case "System.Runtime.CompilerServices.IsExternalInit":
break;
default:
Assert.True(false);
break;
}
}
private void Handle2(SymbolAnalysisContext context)
{
Assert.Equal("A..ctor([System.Int32 X = 0])", context.Symbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount6);
}
private void Handle3(SymbolAnalysisContext context)
{
Assert.Equal("System.Int32 A.X { get; init; }", context.Symbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount7);
}
private void Handle4(SymbolAnalysisContext context)
{
Assert.Equal("C..ctor([System.Int32 Z = 4])", context.Symbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount8);
}
private void Handle5(SymbolAnalysisContext context)
{
Assert.Equal("A", context.Symbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount11);
Assert.Equal(1, FireCount1);
Assert.Equal(1, FireCount2);
Assert.Equal(1, FireCount6);
Assert.Equal(1, FireCount7);
}
private void Handle6(SymbolAnalysisContext context)
{
Assert.Equal("C", context.Symbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount12);
Assert.Equal(1, FireCount4);
Assert.Equal(1, FireCount8);
}
}
[Fact]
public void AnalyzerActions_04()
{
var text1 = @"
record A([Attr1(100)]int X = 0) : I1
{}
record B([Attr2(200)]int Y = 1) : A(2), I1
{
int M() => 3;
}
record C : A, I1
{
C([Attr3(300)]int Z = 4) : base(5)
{}
}
interface I1 {}
";
var analyzer = new AnalyzerActions_04_Analyzer();
var comp = CreateCompilation(text1);
comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify();
Assert.Equal(0, analyzer.FireCount1);
Assert.Equal(1, analyzer.FireCount2);
Assert.Equal(1, analyzer.FireCount3);
Assert.Equal(1, analyzer.FireCount4);
Assert.Equal(1, analyzer.FireCount5);
Assert.Equal(1, analyzer.FireCount6);
Assert.Equal(1, analyzer.FireCount7);
Assert.Equal(1, analyzer.FireCount8);
Assert.Equal(1, analyzer.FireCount9);
Assert.Equal(1, analyzer.FireCount10);
Assert.Equal(1, analyzer.FireCount11);
Assert.Equal(1, analyzer.FireCount12);
Assert.Equal(1, analyzer.FireCount13);
Assert.Equal(1, analyzer.FireCount14);
Assert.Equal(1, analyzer.FireCount15);
Assert.Equal(1, analyzer.FireCount16);
Assert.Equal(1, analyzer.FireCount17);
}
private class AnalyzerActions_04_Analyzer : DiagnosticAnalyzer
{
public int FireCount1;
public int FireCount2;
public int FireCount3;
public int FireCount4;
public int FireCount5;
public int FireCount6;
public int FireCount7;
public int FireCount8;
public int FireCount9;
public int FireCount10;
public int FireCount11;
public int FireCount12;
public int FireCount13;
public int FireCount14;
public int FireCount15;
public int FireCount16;
public int FireCount17;
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterOperationAction(Handle1, OperationKind.ConstructorBody);
context.RegisterOperationAction(Handle2, OperationKind.Invocation);
context.RegisterOperationAction(Handle3, OperationKind.Literal);
context.RegisterOperationAction(Handle4, OperationKind.ParameterInitializer);
context.RegisterOperationAction(Handle5, OperationKind.PropertyInitializer);
context.RegisterOperationAction(Handle5, OperationKind.FieldInitializer);
}
protected void Handle1(OperationAnalysisContext context)
{
switch (context.ContainingSymbol.ToTestDisplayString())
{
case "A..ctor([System.Int32 X = 0])":
Interlocked.Increment(ref FireCount1);
Assert.Equal(SyntaxKind.RecordDeclaration, context.Operation.Syntax.Kind());
break;
case "B..ctor([System.Int32 Y = 1])":
Interlocked.Increment(ref FireCount2);
Assert.Equal(SyntaxKind.RecordDeclaration, context.Operation.Syntax.Kind());
break;
case "C..ctor([System.Int32 Z = 4])":
Interlocked.Increment(ref FireCount3);
Assert.Equal(SyntaxKind.ConstructorDeclaration, context.Operation.Syntax.Kind());
break;
default:
Assert.True(false);
break;
}
}
protected void Handle2(OperationAnalysisContext context)
{
switch (context.ContainingSymbol.ToTestDisplayString())
{
case "B..ctor([System.Int32 Y = 1])":
Interlocked.Increment(ref FireCount4);
Assert.Equal(SyntaxKind.PrimaryConstructorBaseType, context.Operation.Syntax.Kind());
VerifyOperationTree((CSharpCompilation)context.Compilation, context.Operation,
@"
IInvocationOperation ( A..ctor([System.Int32 X = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'A(2)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'A(2)')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
break;
case "C..ctor([System.Int32 Z = 4])":
Interlocked.Increment(ref FireCount5);
Assert.Equal(SyntaxKind.BaseConstructorInitializer, context.Operation.Syntax.Kind());
VerifyOperationTree((CSharpCompilation)context.Compilation, context.Operation,
@"
IInvocationOperation ( A..ctor([System.Int32 X = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: ': base(5)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: ': base(5)')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: '5')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
");
break;
default:
Assert.True(false);
break;
}
}
protected void Handle3(OperationAnalysisContext context)
{
switch (context.Operation.Syntax.ToString())
{
case "100":
Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount6);
break;
case "0":
Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount7);
break;
case "200":
Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount8);
break;
case "1":
Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount9);
break;
case "2":
Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount10);
break;
case "300":
Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount11);
break;
case "4":
Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount12);
break;
case "5":
Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount13);
break;
case "3":
Assert.Equal("System.Int32 B.M()", context.ContainingSymbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount17);
break;
default:
Assert.True(false);
break;
}
}
protected void Handle4(OperationAnalysisContext context)
{
switch (context.Operation.Syntax.ToString())
{
case "= 0":
Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount14);
break;
case "= 1":
Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount15);
break;
case "= 4":
Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString());
Interlocked.Increment(ref FireCount16);
break;
default:
Assert.True(false);
break;
}
}
protected void Handle5(OperationAnalysisContext context)
{
Assert.True(false);
}
}
[Fact]
public void AnalyzerActions_05()
{
var text1 = @"
record A([Attr1(100)]int X = 0) : I1
{}
record B([Attr2(200)]int Y = 1) : A(2), I1
{
int M() => 3;
}
record C : A, I1
{
C([Attr3(300)]int Z = 4) : base(5)
{}
}
interface I1 {}
";
var analyzer = new AnalyzerActions_05_Analyzer();
var comp = CreateCompilation(text1);
comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify();
Assert.Equal(1, analyzer.FireCount1);
Assert.Equal(1, analyzer.FireCount2);
Assert.Equal(1, analyzer.FireCount3);
Assert.Equal(1, analyzer.FireCount4);
}
private class AnalyzerActions_05_Analyzer : DiagnosticAnalyzer
{
public int FireCount1;
public int FireCount2;
public int FireCount3;
public int FireCount4;
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterOperationBlockAction(Handle);
}
private void Handle(OperationBlockAnalysisContext context)
{
switch (context.OwningSymbol.ToTestDisplayString())
{
case "A..ctor([System.Int32 X = 0])":
Interlocked.Increment(ref FireCount1);
Assert.Equal(2, context.OperationBlocks.Length);
Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind);
Assert.Equal("= 0", context.OperationBlocks[0].Syntax.ToString());
Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind);
Assert.Equal("Attr1(100)", context.OperationBlocks[1].Syntax.ToString());
break;
case "B..ctor([System.Int32 Y = 1])":
Interlocked.Increment(ref FireCount2);
Assert.Equal(3, context.OperationBlocks.Length);
Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind);
Assert.Equal("= 1", context.OperationBlocks[0].Syntax.ToString());
Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind);
Assert.Equal("Attr2(200)", context.OperationBlocks[1].Syntax.ToString());
Assert.Equal(OperationKind.Invocation, context.OperationBlocks[2].Kind);
Assert.Equal("A(2)", context.OperationBlocks[2].Syntax.ToString());
break;
case "C..ctor([System.Int32 Z = 4])":
Interlocked.Increment(ref FireCount3);
Assert.Equal(4, context.OperationBlocks.Length);
Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind);
Assert.Equal("= 4", context.OperationBlocks[0].Syntax.ToString());
Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind);
Assert.Equal("Attr3(300)", context.OperationBlocks[1].Syntax.ToString());
Assert.Equal(OperationKind.Block, context.OperationBlocks[2].Kind);
Assert.Equal(OperationKind.Invocation, context.OperationBlocks[3].Kind);
Assert.Equal(": base(5)", context.OperationBlocks[3].Syntax.ToString());
break;
case "System.Int32 B.M()":
Interlocked.Increment(ref FireCount4);
Assert.Equal(1, context.OperationBlocks.Length);
Assert.Equal(OperationKind.Block, context.OperationBlocks[0].Kind);
break;
default:
Assert.True(false);
break;
}
}
}
[Fact]
public void AnalyzerActions_06()
{
var text1 = @"
record A([Attr1(100)]int X = 0) : I1
{}
record B([Attr2(200)]int Y = 1) : A(2), I1
{
int M() => 3;
}
record C : A, I1
{
C([Attr3(300)]int Z = 4) : base(5)
{}
}
interface I1 {}
";
var analyzer = new AnalyzerActions_06_Analyzer();
var comp = CreateCompilation(text1);
comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify();
Assert.Equal(1, analyzer.FireCount100);
Assert.Equal(1, analyzer.FireCount200);
Assert.Equal(1, analyzer.FireCount300);
Assert.Equal(1, analyzer.FireCount400);
Assert.Equal(0, analyzer.FireCount1);
Assert.Equal(1, analyzer.FireCount2);
Assert.Equal(1, analyzer.FireCount3);
Assert.Equal(1, analyzer.FireCount4);
Assert.Equal(1, analyzer.FireCount5);
Assert.Equal(1, analyzer.FireCount6);
Assert.Equal(1, analyzer.FireCount7);
Assert.Equal(1, analyzer.FireCount8);
Assert.Equal(1, analyzer.FireCount9);
Assert.Equal(1, analyzer.FireCount10);
Assert.Equal(1, analyzer.FireCount11);
Assert.Equal(1, analyzer.FireCount12);
Assert.Equal(1, analyzer.FireCount13);
Assert.Equal(1, analyzer.FireCount14);
Assert.Equal(1, analyzer.FireCount15);
Assert.Equal(1, analyzer.FireCount16);
Assert.Equal(1, analyzer.FireCount17);
Assert.Equal(1, analyzer.FireCount1000);
Assert.Equal(1, analyzer.FireCount2000);
Assert.Equal(1, analyzer.FireCount3000);
Assert.Equal(1, analyzer.FireCount4000);
}
private class AnalyzerActions_06_Analyzer : AnalyzerActions_04_Analyzer
{
public int FireCount100;
public int FireCount200;
public int FireCount300;
public int FireCount400;
public int FireCount1000;
public int FireCount2000;
public int FireCount3000;
public int FireCount4000;
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterOperationBlockStartAction(Handle);
}
private void Handle(OperationBlockStartAnalysisContext context)
{
switch (context.OwningSymbol.ToTestDisplayString())
{
case "A..ctor([System.Int32 X = 0])":
Interlocked.Increment(ref FireCount100);
Assert.Equal(2, context.OperationBlocks.Length);
Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind);
Assert.Equal("= 0", context.OperationBlocks[0].Syntax.ToString());
Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind);
Assert.Equal("Attr1(100)", context.OperationBlocks[1].Syntax.ToString());
RegisterOperationAction(context);
context.RegisterOperationBlockEndAction(Handle6);
break;
case "B..ctor([System.Int32 Y = 1])":
Interlocked.Increment(ref FireCount200);
Assert.Equal(3, context.OperationBlocks.Length);
Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind);
Assert.Equal("= 1", context.OperationBlocks[0].Syntax.ToString());
Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind);
Assert.Equal("Attr2(200)", context.OperationBlocks[1].Syntax.ToString());
Assert.Equal(OperationKind.Invocation, context.OperationBlocks[2].Kind);
Assert.Equal("A(2)", context.OperationBlocks[2].Syntax.ToString());
RegisterOperationAction(context);
context.RegisterOperationBlockEndAction(Handle6);
break;
case "C..ctor([System.Int32 Z = 4])":
Interlocked.Increment(ref FireCount300);
Assert.Equal(4, context.OperationBlocks.Length);
Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind);
Assert.Equal("= 4", context.OperationBlocks[0].Syntax.ToString());
Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind);
Assert.Equal("Attr3(300)", context.OperationBlocks[1].Syntax.ToString());
Assert.Equal(OperationKind.Block, context.OperationBlocks[2].Kind);
Assert.Equal(OperationKind.Invocation, context.OperationBlocks[3].Kind);
Assert.Equal(": base(5)", context.OperationBlocks[3].Syntax.ToString());
RegisterOperationAction(context);
context.RegisterOperationBlockEndAction(Handle6);
break;
case "System.Int32 B.M()":
Interlocked.Increment(ref FireCount400);
Assert.Equal(1, context.OperationBlocks.Length);
Assert.Equal(OperationKind.Block, context.OperationBlocks[0].Kind);
RegisterOperationAction(context);
context.RegisterOperationBlockEndAction(Handle6);
break;
default:
Assert.True(false);
break;
}
}
private void RegisterOperationAction(OperationBlockStartAnalysisContext context)
{
context.RegisterOperationAction(Handle1, OperationKind.ConstructorBody);
context.RegisterOperationAction(Handle2, OperationKind.Invocation);
context.RegisterOperationAction(Handle3, OperationKind.Literal);
context.RegisterOperationAction(Handle4, OperationKind.ParameterInitializer);
context.RegisterOperationAction(Handle5, OperationKind.PropertyInitializer);
context.RegisterOperationAction(Handle5, OperationKind.FieldInitializer);
}
private void Handle6(OperationBlockAnalysisContext context)
{
switch (context.OwningSymbol.ToTestDisplayString())
{
case "A..ctor([System.Int32 X = 0])":
Interlocked.Increment(ref FireCount1000);
Assert.Equal(2, context.OperationBlocks.Length);
Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind);
Assert.Equal("= 0", context.OperationBlocks[0].Syntax.ToString());
Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind);
Assert.Equal("Attr1(100)", context.OperationBlocks[1].Syntax.ToString());
break;
case "B..ctor([System.Int32 Y = 1])":
Interlocked.Increment(ref FireCount2000);
Assert.Equal(3, context.OperationBlocks.Length);
Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind);
Assert.Equal("= 1", context.OperationBlocks[0].Syntax.ToString());
Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind);
Assert.Equal("Attr2(200)", context.OperationBlocks[1].Syntax.ToString());
Assert.Equal(OperationKind.Invocation, context.OperationBlocks[2].Kind);
Assert.Equal("A(2)", context.OperationBlocks[2].Syntax.ToString());
break;
case "C..ctor([System.Int32 Z = 4])":
Interlocked.Increment(ref FireCount3000);
Assert.Equal(4, context.OperationBlocks.Length);
Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind);
Assert.Equal("= 4", context.OperationBlocks[0].Syntax.ToString());
Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind);
Assert.Equal("Attr3(300)", context.OperationBlocks[1].Syntax.ToString());
Assert.Equal(OperationKind.Block, context.OperationBlocks[2].Kind);
Assert.Equal(OperationKind.Invocation, context.OperationBlocks[3].Kind);
Assert.Equal(": base(5)", context.OperationBlocks[3].Syntax.ToString());
break;
case "System.Int32 B.M()":
Interlocked.Increment(ref FireCount4000);
Assert.Equal(1, context.OperationBlocks.Length);
Assert.Equal(OperationKind.Block, context.OperationBlocks[0].Kind);
break;
default:
Assert.True(false);
break;
}
}
}
[Fact]
public void AnalyzerActions_07()
{
var text1 = @"
record A([Attr1(100)]int X = 0) : I1
{}
record B([Attr2(200)]int Y = 1) : A(2), I1
{
int M() => 3;
}
record C : A, I1
{
C([Attr3(300)]int Z = 4) : base(5)
{}
}
interface I1 {}
";
var analyzer = new AnalyzerActions_07_Analyzer();
var comp = CreateCompilation(text1);
comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify();
Assert.Equal(1, analyzer.FireCount1);
Assert.Equal(1, analyzer.FireCount2);
Assert.Equal(1, analyzer.FireCount3);
Assert.Equal(1, analyzer.FireCount4);
}
private class AnalyzerActions_07_Analyzer : DiagnosticAnalyzer
{
public int FireCount1;
public int FireCount2;
public int FireCount3;
public int FireCount4;
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterCodeBlockAction(Handle);
}
private void Handle(CodeBlockAnalysisContext context)
{
switch (context.OwningSymbol.ToTestDisplayString())
{
case "A..ctor([System.Int32 X = 0])":
switch (context.CodeBlock)
{
case RecordDeclarationSyntax { Identifier: { ValueText: "A" } }:
Interlocked.Increment(ref FireCount1);
break;
default:
Assert.True(false);
break;
}
break;
case "B..ctor([System.Int32 Y = 1])":
switch (context.CodeBlock)
{
case RecordDeclarationSyntax { Identifier: { ValueText: "B" } }:
Interlocked.Increment(ref FireCount2);
break;
default:
Assert.True(false);
break;
}
break;
case "C..ctor([System.Int32 Z = 4])":
switch (context.CodeBlock)
{
case ConstructorDeclarationSyntax { Identifier: { ValueText: "C" } }:
Interlocked.Increment(ref FireCount3);
break;
default:
Assert.True(false);
break;
}
break;
case "System.Int32 B.M()":
switch (context.CodeBlock)
{
case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }:
Interlocked.Increment(ref FireCount4);
break;
default:
Assert.True(false);
break;
}
break;
default:
Assert.True(false);
break;
}
}
}
[Fact]
public void AnalyzerActions_08()
{
var text1 = @"
record A([Attr1]int X = 0) : I1
{}
record B([Attr2]int Y = 1) : A(2), I1
{
int M() => 3;
}
record C : A, I1
{
C([Attr3]int Z = 4) : base(5)
{}
}
interface I1 {}
";
var analyzer = new AnalyzerActions_08_Analyzer();
var comp = CreateCompilation(text1);
comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify();
Assert.Equal(1, analyzer.FireCount100);
Assert.Equal(1, analyzer.FireCount200);
Assert.Equal(1, analyzer.FireCount300);
Assert.Equal(1, analyzer.FireCount400);
Assert.Equal(1, analyzer.FireCount0);
Assert.Equal(1, analyzer.FireCount1);
Assert.Equal(1, analyzer.FireCount2);
Assert.Equal(1, analyzer.FireCount3);
Assert.Equal(1, analyzer.FireCount4);
Assert.Equal(1, analyzer.FireCount5);
Assert.Equal(1, analyzer.FireCount6);
Assert.Equal(1, analyzer.FireCount7);
Assert.Equal(0, analyzer.FireCount8);
Assert.Equal(1, analyzer.FireCount9);
Assert.Equal(0, analyzer.FireCount10);
Assert.Equal(0, analyzer.FireCount11);
Assert.Equal(0, analyzer.FireCount12);
Assert.Equal(0, analyzer.FireCount13);
Assert.Equal(0, analyzer.FireCount14);
Assert.Equal(1, analyzer.FireCount15);
Assert.Equal(1, analyzer.FireCount16);
Assert.Equal(0, analyzer.FireCount17);
Assert.Equal(0, analyzer.FireCount18);
Assert.Equal(0, analyzer.FireCount19);
Assert.Equal(0, analyzer.FireCount20);
Assert.Equal(0, analyzer.FireCount21);
Assert.Equal(0, analyzer.FireCount22);
Assert.Equal(0, analyzer.FireCount23);
Assert.Equal(1, analyzer.FireCount24);
Assert.Equal(1, analyzer.FireCount25);
Assert.Equal(1, analyzer.FireCount26);
Assert.Equal(0, analyzer.FireCount27);
Assert.Equal(0, analyzer.FireCount28);
Assert.Equal(0, analyzer.FireCount29);
Assert.Equal(1, analyzer.FireCount30);
Assert.Equal(1, analyzer.FireCount31);
Assert.Equal(1, analyzer.FireCount1000);
Assert.Equal(1, analyzer.FireCount2000);
Assert.Equal(1, analyzer.FireCount3000);
Assert.Equal(1, analyzer.FireCount4000);
}
private class AnalyzerActions_08_Analyzer : AnalyzerActions_01_Analyzer
{
public int FireCount100;
public int FireCount200;
public int FireCount300;
public int FireCount400;
public int FireCount1000;
public int FireCount2000;
public int FireCount3000;
public int FireCount4000;
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterCodeBlockStartAction<SyntaxKind>(Handle);
}
private void Handle(CodeBlockStartAnalysisContext<SyntaxKind> context)
{
switch (context.OwningSymbol.ToTestDisplayString())
{
case "A..ctor([System.Int32 X = 0])":
switch (context.CodeBlock)
{
case RecordDeclarationSyntax { Identifier: { ValueText: "A" } }:
Interlocked.Increment(ref FireCount100);
break;
default:
Assert.True(false);
break;
}
break;
case "B..ctor([System.Int32 Y = 1])":
switch (context.CodeBlock)
{
case RecordDeclarationSyntax { Identifier: { ValueText: "B" } }:
Interlocked.Increment(ref FireCount200);
break;
default:
Assert.True(false);
break;
}
break;
case "C..ctor([System.Int32 Z = 4])":
switch (context.CodeBlock)
{
case ConstructorDeclarationSyntax { Identifier: { ValueText: "C" } }:
Interlocked.Increment(ref FireCount300);
break;
default:
Assert.True(false);
break;
}
break;
case "System.Int32 B.M()":
switch (context.CodeBlock)
{
case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }:
Interlocked.Increment(ref FireCount400);
break;
default:
Assert.True(false);
break;
}
break;
default:
Assert.True(false);
break;
}
context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.NumericLiteralExpression);
context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.EqualsValueClause);
context.RegisterSyntaxNodeAction(Handle3, SyntaxKind.BaseConstructorInitializer);
context.RegisterSyntaxNodeAction(Handle4, SyntaxKind.ConstructorDeclaration);
context.RegisterSyntaxNodeAction(Handle5, SyntaxKind.PrimaryConstructorBaseType);
context.RegisterSyntaxNodeAction(Handle6, SyntaxKind.RecordDeclaration);
context.RegisterSyntaxNodeAction(Handle7, SyntaxKind.IdentifierName);
context.RegisterSyntaxNodeAction(Handle8, SyntaxKind.SimpleBaseType);
context.RegisterSyntaxNodeAction(Handle9, SyntaxKind.ParameterList);
context.RegisterSyntaxNodeAction(Handle10, SyntaxKind.ArgumentList);
context.RegisterCodeBlockEndAction(Handle11);
}
private void Handle11(CodeBlockAnalysisContext context)
{
switch (context.OwningSymbol.ToTestDisplayString())
{
case "A..ctor([System.Int32 X = 0])":
switch (context.CodeBlock)
{
case RecordDeclarationSyntax { Identifier: { ValueText: "A" } }:
Interlocked.Increment(ref FireCount1000);
break;
default:
Assert.True(false);
break;
}
break;
case "B..ctor([System.Int32 Y = 1])":
switch (context.CodeBlock)
{
case RecordDeclarationSyntax { Identifier: { ValueText: "B" } }:
Interlocked.Increment(ref FireCount2000);
break;
default:
Assert.True(false);
break;
}
break;
case "C..ctor([System.Int32 Z = 4])":
switch (context.CodeBlock)
{
case ConstructorDeclarationSyntax { Identifier: { ValueText: "C" } }:
Interlocked.Increment(ref FireCount3000);
break;
default:
Assert.True(false);
break;
}
break;
case "System.Int32 B.M()":
switch (context.CodeBlock)
{
case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }:
Interlocked.Increment(ref FireCount4000);
break;
default:
Assert.True(false);
break;
}
break;
default:
Assert.True(false);
break;
}
}
}
[Fact]
public void AnalyzerActions_09()
{
var text1 = @"
record A([Attr1(100)]int X = 0) : I1
{}
record B([Attr2(200)]int Y = 1) : A(2), I1
{
int M() => 3;
}
record C : A, I1
{
C([Attr3(300)]int Z = 4) : base(5)
{}
}
interface I1 {}
";
var analyzer = new AnalyzerActions_09_Analyzer();
var comp = CreateCompilation(text1);
comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify();
Assert.Equal(1, analyzer.FireCount1);
Assert.Equal(1, analyzer.FireCount2);
Assert.Equal(1, analyzer.FireCount3);
Assert.Equal(1, analyzer.FireCount4);
Assert.Equal(1, analyzer.FireCount5);
Assert.Equal(1, analyzer.FireCount6);
Assert.Equal(1, analyzer.FireCount7);
Assert.Equal(1, analyzer.FireCount8);
Assert.Equal(1, analyzer.FireCount9);
}
private class AnalyzerActions_09_Analyzer : DiagnosticAnalyzer
{
public int FireCount1;
public int FireCount2;
public int FireCount3;
public int FireCount4;
public int FireCount5;
public int FireCount6;
public int FireCount7;
public int FireCount8;
public int FireCount9;
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterSymbolAction(Handle1, SymbolKind.Method);
context.RegisterSymbolAction(Handle2, SymbolKind.Property);
context.RegisterSymbolAction(Handle3, SymbolKind.Parameter);
}
private void Handle1(SymbolAnalysisContext context)
{
switch (context.Symbol.ToTestDisplayString())
{
case "A..ctor([System.Int32 X = 0])":
Interlocked.Increment(ref FireCount1);
break;
case "B..ctor([System.Int32 Y = 1])":
Interlocked.Increment(ref FireCount2);
break;
case "C..ctor([System.Int32 Z = 4])":
Interlocked.Increment(ref FireCount3);
break;
case "System.Int32 B.M()":
Interlocked.Increment(ref FireCount4);
break;
default:
Assert.True(false);
break;
}
}
private void Handle2(SymbolAnalysisContext context)
{
switch (context.Symbol.ToTestDisplayString())
{
case "System.Int32 A.X { get; init; }":
Interlocked.Increment(ref FireCount5);
break;
case "System.Int32 B.Y { get; init; }":
Interlocked.Increment(ref FireCount6);
break;
default:
Assert.True(false);
break;
}
}
private void Handle3(SymbolAnalysisContext context)
{
switch (context.Symbol.ToTestDisplayString())
{
case "[System.Int32 X = 0]":
Interlocked.Increment(ref FireCount7);
break;
case "[System.Int32 Y = 1]":
Interlocked.Increment(ref FireCount8);
break;
case "[System.Int32 Z = 4]":
Interlocked.Increment(ref FireCount9);
break;
default:
Assert.True(false);
break;
}
}
}
[Fact]
[WorkItem(46657, "https://github.com/dotnet/roslyn/issues/46657")]
public void CanDeclareIteratorInRecord()
{
var source = @"
using System.Collections.Generic;
public record X(int a)
{
public static void Main()
{
foreach(var i in new X(42).GetItems())
{
System.Console.Write(i);
}
}
public IEnumerable<int> GetItems() { yield return a; yield return a + 1; }
}";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9)
.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "4243", verify: Verification.Skipped /* init-only */);
}
[Fact]
public void DefaultCtor_01()
{
var src = @"
record C
{
}
class Program
{
static void Main()
{
var x = new C();
var y = new C();
System.Console.WriteLine(x == y);
}
}
";
var verifier = CompileAndVerify(src, expectedOutput: "True");
verifier.VerifyDiagnostics();
verifier.VerifyIL("C..ctor()", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ret
}
");
}
[Fact]
public void DefaultCtor_02()
{
var src = @"
record B(int x);
record C : B
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (4,8): error CS1729: 'B' does not contain a constructor that takes 0 arguments
// record C : B
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("B", "0").WithLocation(4, 8)
);
}
[Fact]
public void DefaultCtor_03()
{
var src = @"
record C
{
public C(C c){}
}
class Program
{
static void Main()
{
var x = new C();
var y = new C();
System.Console.WriteLine(x == y);
}
}
";
var verifier = CompileAndVerify(src, expectedOutput: "True");
verifier.VerifyDiagnostics();
verifier.VerifyIL("C..ctor()", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ret
}
");
}
[Fact]
public void DefaultCtor_04()
{
var src = @"
record B(int x);
record C : B
{
public C(C c) : base(c) {}
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (4,8): error CS1729: 'B' does not contain a constructor that takes 0 arguments
// record C : B
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("B", "0").WithLocation(4, 8)
);
}
[Fact]
public void DefaultCtor_05()
{
var src = @"
record C(int x);
class Program
{
static void Main()
{
_ = new C();
}
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (8,17): error CS7036: There is no argument given that corresponds to the required formal parameter 'x' of 'C.C(int)'
// _ = new C();
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("x", "C.C(int)").WithLocation(8, 17)
);
}
[Fact]
public void DefaultCtor_06()
{
var src = @"
record C
{
C(int x) {}
}
class Program
{
static void Main()
{
_ = new C();
}
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (11,17): error CS1729: 'C' does not contain a constructor that takes 0 arguments
// _ = new C();
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("C", "0").WithLocation(11, 17)
);
}
[Fact]
public void DefaultCtor_07()
{
var src = @"
class C
{
C(C x) {}
}
class Program
{
static void Main()
{
_ = new C();
}
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (11,17): error CS1729: 'C' does not contain a constructor that takes 0 arguments
// _ = new C();
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("C", "0").WithLocation(11, 17)
);
}
[Fact]
[WorkItem(47867, "https://github.com/dotnet/roslyn/issues/47867")]
public void ToString_RecordWithStaticMembers()
{
var src = @"
var c1 = new C1(42);
System.Console.Write(c1.ToString());
record C1(int I1)
{
public static int field1 = 44;
public const int field2 = 44;
public static int P1 { set { } }
public static int P2 { get { return 1; } set { } }
public static int P3 { get { return 1; } }
}
";
var compDebug = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe);
var compRelease = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.ReleaseExe);
CompileAndVerify(compDebug, expectedOutput: "C1 { I1 = 42 }", verify: Verification.Skipped /* init-only */);
compDebug.VerifyEmitDiagnostics();
CompileAndVerify(compRelease, expectedOutput: "C1 { I1 = 42 }", verify: Verification.Skipped /* init-only */);
compRelease.VerifyEmitDiagnostics();
}
[Fact]
[WorkItem(47867, "https://github.com/dotnet/roslyn/issues/47867")]
public void ToString_NestedRecord()
{
var src = @"
var c1 = new Outer.C1(42);
System.Console.Write(c1.ToString());
public class Outer
{
public record C1(int I1);
}
";
var compDebug = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe);
var compRelease = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.ReleaseExe);
CompileAndVerify(compDebug, expectedOutput: "C1 { I1 = 42 }", verify: Verification.Skipped /* init-only */);
compDebug.VerifyEmitDiagnostics();
CompileAndVerify(compRelease, expectedOutput: "C1 { I1 = 42 }", verify: Verification.Skipped /* init-only */);
compRelease.VerifyEmitDiagnostics();
}
[Fact]
[WorkItem(50040, "https://github.com/dotnet/roslyn/issues/50040")]
public void RaceConditionInAddMembers()
{
var src = @"
#nullable enable
using System;
using System.Linq.Expressions;
using System.Threading.Tasks;
var collection = new Collection<Hamster>();
Hamster h = null!;
await collection.MethodAsync(entity => entity.Name! == ""bar"", h);
public record Collection<T> where T : Document
{
public Task MethodAsync<TDerived>(Expression<Func<TDerived, bool>> filter, TDerived td) where TDerived : T
=> throw new NotImplementedException();
public Task MethodAsync<TDerived2>(Task<TDerived2> filterDefinition, TDerived2 td) where TDerived2 : T
=> throw new NotImplementedException();
}
public sealed record HamsterCollection : Collection<Hamster>
{
}
public abstract class Document
{
}
public sealed class Hamster : Document
{
public string? Name { get; private set; }
}
";
for (int i = 0; i < 100; i++)
{
var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
}
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc()
{
var src = @"
/// <summary>Summary</summary>
/// <param name=""I1"">Description for I1</param>
public record C(int I1);
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics();
var cMember = comp.GetMember<NamedTypeSymbol>("C");
Assert.Equal(
@"<member name=""T:C"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", cMember.GetDocumentationCommentXml());
var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single();
Assert.Equal(
@"<member name=""M:C.#ctor(System.Int32)"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", constructor.GetDocumentationCommentXml());
Assert.Equal("", constructor.GetParameters()[0].GetDocumentationCommentXml());
var property = cMember.GetMembers("I1").Single();
Assert.Equal("", property.GetDocumentationCommentXml());
}
[Fact]
public void XmlDoc_RecordClass()
{
var src = @"
/// <summary>Summary</summary>
/// <param name=""I1"">Description for I1</param>
public record class C(int I1);
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics();
var cMember = comp.GetMember<NamedTypeSymbol>("C");
Assert.Equal(
@"<member name=""T:C"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", cMember.GetDocumentationCommentXml());
var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single();
Assert.Equal(
@"<member name=""M:C.#ctor(System.Int32)"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", constructor.GetDocumentationCommentXml());
Assert.Equal("", constructor.GetParameters()[0].GetDocumentationCommentXml());
var property = cMember.GetMembers("I1").Single();
Assert.Equal("", property.GetDocumentationCommentXml());
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_Cref()
{
var src = @"
/// <summary>Summary</summary>
/// <param name=""I1"">Description for <see cref=""I1""/></param>
public record C(int I1)
{
/// <summary>Summary</summary>
/// <param name=""x"">Description for <see cref=""x""/></param>
public void M(int x) { }
}
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics(
// (7,52): warning CS1574: XML comment has cref attribute 'x' that could not be resolved
// /// <param name="x">Description for <see cref="x"/></param>
Diagnostic(ErrorCode.WRN_BadXMLRef, "x").WithArguments("x").WithLocation(7, 52)
);
var tree = comp.SyntaxTrees.Single();
var docComments = tree.GetCompilationUnitRoot().DescendantTrivia().Select(trivia => trivia.GetStructure()).OfType<DocumentationCommentTriviaSyntax>();
var cref = docComments.First().DescendantNodes().OfType<XmlCrefAttributeSyntax>().First().Cref;
Assert.Equal("I1", cref.ToString());
var model = comp.GetSemanticModel(tree, ignoreAccessibility: false);
Assert.Equal(SymbolKind.Property, model.GetSymbolInfo(cref).Symbol!.Kind);
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_Error()
{
var src = @"
/// <summary>Summary</summary>
/// <param name=""Error""></param>
/// <param name=""I1""></param>
public record C(int I1);
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics(
// (3,18): warning CS1572: XML comment has a param tag for 'Error', but there is no parameter by that name
// /// <param name="Error"></param>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "Error").WithArguments("Error").WithLocation(3, 18),
// (3,18): warning CS1572: XML comment has a param tag for 'Error', but there is no parameter by that name
// /// <param name="Error"></param>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "Error").WithArguments("Error").WithLocation(3, 18)
);
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_Duplicate()
{
var src = @"
/// <summary>Summary</summary>
/// <param name=""I1""></param>
/// <param name=""I1""></param>
public record C(int I1);
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics(
// (4,12): warning CS1571: XML comment has a duplicate param tag for 'I1'
// /// <param name="I1"></param>
Diagnostic(ErrorCode.WRN_DuplicateParamTag, @"name=""I1""").WithArguments("I1").WithLocation(4, 12),
// (4,12): warning CS1571: XML comment has a duplicate param tag for 'I1'
// /// <param name="I1"></param>
Diagnostic(ErrorCode.WRN_DuplicateParamTag, @"name=""I1""").WithArguments("I1").WithLocation(4, 12)
);
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_ParamRef()
{
var src = @"
/// <summary>Summary <paramref name=""I1""/></summary>
/// <param name=""I1"">Description for I1</param>
public record C(int I1);
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics();
var cMember = comp.GetMember<NamedTypeSymbol>("C");
var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single();
Assert.Equal(
@"<member name=""M:C.#ctor(System.Int32)"">
<summary>Summary <paramref name=""I1""/></summary>
<param name=""I1"">Description for I1</param>
</member>
", constructor.GetDocumentationCommentXml());
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_ParamRef_Error()
{
var src = @"
/// <summary>Summary <paramref name=""Error""/></summary>
/// <param name=""I1"">Description for I1</param>
public record C(int I1);
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics(
// (2,38): warning CS1734: XML comment on 'C' has a paramref tag for 'Error', but there is no parameter by that name
// /// <summary>Summary <paramref name="Error"/></summary>
Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "Error").WithArguments("Error", "C").WithLocation(2, 38),
// (2,38): warning CS1734: XML comment on 'C.C(int)' has a paramref tag for 'Error', but there is no parameter by that name
// /// <summary>Summary <paramref name="Error"/></summary>
Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "Error").WithArguments("Error", "C.C(int)").WithLocation(2, 38)
);
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_WithExplicitProperty()
{
var src = @"
/// <summary>Summary</summary>
/// <param name=""I1"">Description for I1</param>
public record C(int I1)
{
/// <summary>Property summary</summary>
public int I1 { get; init; } = I1;
}
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics();
var cMember = comp.GetMember<NamedTypeSymbol>("C");
Assert.Equal(
@"<member name=""T:C"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", cMember.GetDocumentationCommentXml());
var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single();
Assert.Equal(
@"<member name=""M:C.#ctor(System.Int32)"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", constructor.GetDocumentationCommentXml());
Assert.Equal("", constructor.GetParameters()[0].GetDocumentationCommentXml());
var property = cMember.GetMembers("I1").Single();
Assert.Equal(
@"<member name=""P:C.I1"">
<summary>Property summary</summary>
</member>
", property.GetDocumentationCommentXml());
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_EmptyParameterList()
{
var src = @"
/// <summary>Summary</summary>
public record C();
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics();
var cMember = comp.GetMember<NamedTypeSymbol>("C");
Assert.Equal(
@"<member name=""T:C"">
<summary>Summary</summary>
</member>
", cMember.GetDocumentationCommentXml());
var constructor = cMember.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.IsEmpty).Single();
Assert.Equal(
@"<member name=""M:C.#ctor"">
<summary>Summary</summary>
</member>
", constructor.GetDocumentationCommentXml());
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_Partial_ParamListSecond()
{
var src = @"
public partial record C;
/// <summary>Summary</summary>
/// <param name=""I1"">Description for I1</param>
public partial record C(int I1);
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics();
var c = comp.GetMember<NamedTypeSymbol>("C");
Assert.Equal(
@"<member name=""T:C"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", c.GetDocumentationCommentXml());
var cConstructor = c.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single();
Assert.Equal(
@"<member name=""M:C.#ctor(System.Int32)"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", cConstructor.GetDocumentationCommentXml());
Assert.Equal("", cConstructor.GetParameters()[0].GetDocumentationCommentXml());
Assert.Equal("", c.GetMembers("I1").Single().GetDocumentationCommentXml());
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_Partial_ParamListFirst()
{
var src = @"
/// <summary>Summary</summary>
/// <param name=""I1"">Description for I1</param>
public partial record D(int I1);
public partial record D;
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics();
var d = comp.GetMember<NamedTypeSymbol>("D");
Assert.Equal(
@"<member name=""T:D"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", d.GetDocumentationCommentXml());
var dConstructor = d.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single();
Assert.Equal(
@"<member name=""M:D.#ctor(System.Int32)"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", dConstructor.GetDocumentationCommentXml());
Assert.Equal("", dConstructor.GetParameters()[0].GetDocumentationCommentXml());
Assert.Equal("", d.GetMembers("I1").Single().GetDocumentationCommentXml());
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_Partial_ParamListFirst_XmlDocSecond()
{
var src = @"
public partial record E(int I1);
/// <summary>Summary</summary>
/// <param name=""I1"">Description for I1</param>
public partial record E;
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics(
// (2,23): warning CS1591: Missing XML comment for publicly visible type or member 'E.E(int)'
// public partial record E(int I1);
Diagnostic(ErrorCode.WRN_MissingXMLComment, "E").WithArguments("E.E(int)").WithLocation(2, 23),
// (5,18): warning CS1572: XML comment has a param tag for 'I1', but there is no parameter by that name
// /// <param name="I1">Description for I1</param>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "I1").WithArguments("I1").WithLocation(5, 18)
);
var e = comp.GetMember<NamedTypeSymbol>("E");
Assert.Equal(
@"<member name=""T:E"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", e.GetDocumentationCommentXml());
var eConstructor = e.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single();
Assert.Equal("", eConstructor.GetDocumentationCommentXml());
Assert.Equal("", eConstructor.GetParameters()[0].GetDocumentationCommentXml());
Assert.Equal("", e.GetMembers("I1").Single().GetDocumentationCommentXml());
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_Partial_ParamListSecond_XmlDocFirst()
{
var src = @"
/// <summary>Summary</summary>
/// <param name=""I1"">Description for I1</param>
public partial record E;
public partial record E(int I1);
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics(
// (3,18): warning CS1572: XML comment has a param tag for 'I1', but there is no parameter by that name
// /// <param name="I1">Description for I1</param>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "I1").WithArguments("I1").WithLocation(3, 18),
// (6,23): warning CS1591: Missing XML comment for publicly visible type or member 'E.E(int)'
// public partial record E(int I1);
Diagnostic(ErrorCode.WRN_MissingXMLComment, "E").WithArguments("E.E(int)").WithLocation(6, 23)
);
var e = comp.GetMember<NamedTypeSymbol>("E");
Assert.Equal(
@"<member name=""T:E"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", e.GetDocumentationCommentXml());
var eConstructor = e.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single();
Assert.Equal("", eConstructor.GetDocumentationCommentXml());
Assert.Equal("", eConstructor.GetParameters()[0].GetDocumentationCommentXml());
Assert.Equal("", e.GetMembers("I1").Single().GetDocumentationCommentXml());
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_Partial_DuplicateParameterList_XmlDocSecond()
{
var src = @"
public partial record C(int I1);
/// <summary>Summary</summary>
/// <param name=""I1"">Description for I1</param>
public partial record C(int I1);
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics(
// (2,23): warning CS1591: Missing XML comment for publicly visible type or member 'C.C(int)'
// public partial record C(int I1);
Diagnostic(ErrorCode.WRN_MissingXMLComment, "C").WithArguments("C.C(int)").WithLocation(2, 23),
// (5,18): warning CS1572: XML comment has a param tag for 'I1', but there is no parameter by that name
// /// <param name="I1">Description for I1</param>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "I1").WithArguments("I1").WithLocation(5, 18),
// (6,24): error CS8863: Only a single record partial declaration may have a parameter list
// public partial record C(int I1);
Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(int I1)").WithLocation(6, 24)
);
var c = comp.GetMember<NamedTypeSymbol>("C");
Assert.Equal(
@"<member name=""T:C"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", c.GetDocumentationCommentXml());
var cConstructor = c.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single();
Assert.Equal(1, cConstructor.DeclaringSyntaxReferences.Count());
Assert.Equal("", cConstructor.GetDocumentationCommentXml());
Assert.Equal("", cConstructor.GetParameters()[0].GetDocumentationCommentXml());
Assert.Equal("", c.GetMembers("I1").Single().GetDocumentationCommentXml());
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_Partial_DuplicateParameterList_XmlDocFirst()
{
var src = @"
/// <summary>Summary</summary>
/// <param name=""I1"">Description for I1</param>
public partial record D(int I1);
public partial record D(int I1);
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics(
// (6,24): error CS8863: Only a single record partial declaration may have a parameter list
// public partial record D(int I1);
Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(int I1)").WithLocation(6, 24)
);
var d = comp.GetMember<NamedTypeSymbol>("D");
Assert.Equal(
@"<member name=""T:D"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", d.GetDocumentationCommentXml());
var dConstructor = d.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single();
Assert.Equal(
@"<member name=""M:D.#ctor(System.Int32)"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", dConstructor.GetDocumentationCommentXml());
Assert.Equal("", dConstructor.GetParameters()[0].GetDocumentationCommentXml());
Assert.Equal("", d.GetMembers("I1").Single().GetDocumentationCommentXml());
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_Partial_DuplicateParameterList_XmlDocOnBoth()
{
var src = @"
/// <summary>Summary1</summary>
/// <param name=""I1"">Description1 for I1</param>
public partial record E(int I1);
/// <summary>Summary2</summary>
/// <param name=""I1"">Description2 for I1</param>
public partial record E(int I1);
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics(
// (7,18): warning CS1572: XML comment has a param tag for 'I1', but there is no parameter by that name
// /// <param name="I1">Description2 for I1</param>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "I1").WithArguments("I1").WithLocation(7, 18),
// (8,24): error CS8863: Only a single record partial declaration may have a parameter list
// public partial record E(int I1);
Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(int I1)").WithLocation(8, 24)
);
var e = comp.GetMember<NamedTypeSymbol>("E");
Assert.Equal(
@"<member name=""T:E"">
<summary>Summary1</summary>
<param name=""I1"">Description1 for I1</param>
<summary>Summary2</summary>
<param name=""I1"">Description2 for I1</param>
</member>
", e.GetDocumentationCommentXml());
var eConstructor = e.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single();
Assert.Equal(1, eConstructor.DeclaringSyntaxReferences.Count());
Assert.Equal(
@"<member name=""M:E.#ctor(System.Int32)"">
<summary>Summary1</summary>
<param name=""I1"">Description1 for I1</param>
</member>
", eConstructor.GetDocumentationCommentXml());
Assert.Equal("", eConstructor.GetParameters()[0].GetDocumentationCommentXml());
Assert.Equal("", e.GetMembers("I1").Single().GetDocumentationCommentXml());
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_Partial_DifferentParameterLists_XmlDocSecond()
{
var src = @"
public partial record E(int I1);
/// <summary>Summary2</summary>
/// <param name=""S1"">Description2 for S1</param>
public partial record E(string S1);
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics(
// (2,23): warning CS1591: Missing XML comment for publicly visible type or member 'E.E(int)'
// public partial record E(int I1);
Diagnostic(ErrorCode.WRN_MissingXMLComment, "E").WithArguments("E.E(int)").WithLocation(2, 23),
// (5,18): warning CS1572: XML comment has a param tag for 'S1', but there is no parameter by that name
// /// <param name="S1">Description2 for S1</param>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "S1").WithArguments("S1").WithLocation(5, 18),
// (6,24): error CS8863: Only a single record partial declaration may have a parameter list
// public partial record E(string S1);
Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(string S1)").WithLocation(6, 24)
);
var e = comp.GetMember<NamedTypeSymbol>("E");
Assert.Equal(
@"<member name=""T:E"">
<summary>Summary2</summary>
<param name=""S1"">Description2 for S1</param>
</member>
", e.GetDocumentationCommentXml());
var eConstructor = e.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single();
Assert.Equal(1, eConstructor.DeclaringSyntaxReferences.Count());
Assert.Equal("", eConstructor.GetDocumentationCommentXml());
Assert.Equal("", eConstructor.GetParameters()[0].GetDocumentationCommentXml());
Assert.Equal("", e.GetMembers("I1").Single().GetDocumentationCommentXml());
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_Partial_DifferentParameterLists_XmlDocOnBoth()
{
var src = @"
/// <summary>Summary1</summary>
/// <param name=""I1"">Description1 for I1</param>
public partial record E(int I1);
/// <summary>Summary2</summary>
/// <param name=""S1"">Description2 for S1</param>
public partial record E(string S1);
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics(
// (7,18): warning CS1572: XML comment has a param tag for 'S1', but there is no parameter by that name
// /// <param name="S1">Description2 for S1</param>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "S1").WithArguments("S1").WithLocation(7, 18),
// (8,24): error CS8863: Only a single record partial declaration may have a parameter list
// public partial record E(string S1);
Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(string S1)").WithLocation(8, 24)
);
var e = comp.GetMember<NamedTypeSymbol>("E");
Assert.Equal(
@"<member name=""T:E"">
<summary>Summary1</summary>
<param name=""I1"">Description1 for I1</param>
<summary>Summary2</summary>
<param name=""S1"">Description2 for S1</param>
</member>
", e.GetDocumentationCommentXml());
var eConstructor = e.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single();
Assert.Equal(1, eConstructor.DeclaringSyntaxReferences.Count());
Assert.Equal(
@"<member name=""M:E.#ctor(System.Int32)"">
<summary>Summary1</summary>
<param name=""I1"">Description1 for I1</param>
</member>
", eConstructor.GetDocumentationCommentXml());
Assert.Equal("", eConstructor.GetParameters()[0].GetDocumentationCommentXml());
Assert.Equal("", e.GetMembers("I1").Single().GetDocumentationCommentXml());
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_Nested()
{
var src = @"
/// <summary>Summary</summary>
public class Outer
{
/// <summary>Summary</summary>
/// <param name=""I1"">Description for I1</param>
public record C(int I1);
}
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics();
var cMember = comp.GetMember<NamedTypeSymbol>("Outer.C");
Assert.Equal(
@"<member name=""T:Outer.C"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", cMember.GetDocumentationCommentXml());
var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single();
Assert.Equal(
@"<member name=""M:Outer.C.#ctor(System.Int32)"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
</member>
", constructor.GetDocumentationCommentXml());
Assert.Equal("", constructor.GetParameters()[0].GetDocumentationCommentXml());
var property = cMember.GetMembers("I1").Single();
Assert.Equal("", property.GetDocumentationCommentXml());
}
[Fact]
[WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")]
public void XmlDoc_Nested_ReferencingOuterParam()
{
var src = @"
/// <summary>Summary</summary>
/// <param name=""O1"">Description for O1</param>
public record Outer(object O1)
{
/// <summary>Summary</summary>
public int P1 { get; set; }
/// <summary>Summary</summary>
/// <param name=""I1"">Description for I1</param>
/// <param name=""O1"">Error O1</param>
/// <param name=""P1"">Error P1</param>
/// <param name=""C"">Error C</param>
public record C(int I1);
}
namespace System.Runtime.CompilerServices
{
/// <summary>Ignored</summary>
public static class IsExternalInit
{
}
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments);
comp.VerifyDiagnostics(
// (11,22): warning CS1572: XML comment has a param tag for 'O1', but there is no parameter by that name
// /// <param name="O1">Error</param>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "O1").WithArguments("O1").WithLocation(11, 22),
// (11,22): warning CS1572: XML comment has a param tag for 'O1', but there is no parameter by that name
// /// <param name="O1">Error</param>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "O1").WithArguments("O1").WithLocation(11, 22),
// (12,22): warning CS1572: XML comment has a param tag for 'P1', but there is no parameter by that name
// /// <param name="P1">Error</param>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "P1").WithArguments("P1").WithLocation(12, 22),
// (12,22): warning CS1572: XML comment has a param tag for 'P1', but there is no parameter by that name
// /// <param name="P1">Error</param>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "P1").WithArguments("P1").WithLocation(12, 22),
// (13,22): warning CS1572: XML comment has a param tag for 'C', but there is no parameter by that name
// /// <param name="C">Error</param>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "C").WithArguments("C").WithLocation(13, 22),
// (13,22): warning CS1572: XML comment has a param tag for 'C', but there is no parameter by that name
// /// <param name="C">Error</param>
Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "C").WithArguments("C").WithLocation(13, 22)
);
var cMember = comp.GetMember<NamedTypeSymbol>("Outer.C");
var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single();
Assert.Equal(
@"<member name=""M:Outer.C.#ctor(System.Int32)"">
<summary>Summary</summary>
<param name=""I1"">Description for I1</param>
<param name=""O1"">Error O1</param>
<param name=""P1"">Error P1</param>
<param name=""C"">Error C</param>
</member>
", constructor.GetDocumentationCommentXml());
}
[Fact, WorkItem(51590, "https://github.com/dotnet/roslyn/issues/51590")]
public void SealedIncomplete()
{
var source = @"
public sealed record(";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (2,21): error CS1001: Identifier expected
// public sealed record(
Diagnostic(ErrorCode.ERR_IdentifierExpected, "(").WithLocation(2, 21),
// (2,22): error CS1026: ) expected
// public sealed record(
Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(2, 22),
// (2,22): error CS1514: { expected
// public sealed record(
Diagnostic(ErrorCode.ERR_LbraceExpected, "").WithLocation(2, 22),
// (2,22): error CS1513: } expected
// public sealed record(
Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(2, 22)
);
}
[Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")]
public void HiddenPositionalMember_Property()
{
var source = @"
public record Base
{
public int I { get; set; } = 42;
public Base(int ignored) { }
}
public record C(int I) : Base(I)
{
public void I() { } // hiding
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics(
// (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden.
// public record C(int I) : Base(I)
Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21),
// (9,17): warning CS0108: 'C.I()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended.
// public void I() { } // hiding
Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I()", "Base.I").WithLocation(9, 17)
);
}
[Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")]
public void HiddenPositionalMember_Field()
{
var source = @"
public record Base
{
public int I = 42;
public Base(int ignored) { }
}
public record C(int I) : Base(I)
{
public void I() { } // hiding
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics(
// (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden.
// public record C(int I) : Base(I)
Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21),
// (9,17): warning CS0108: 'C.I()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended.
// public void I() { } // hiding
Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I()", "Base.I").WithLocation(9, 17)
);
}
[Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")]
public void HiddenPositionalMember_Field_HiddenWithConstant()
{
var source = @"
public record Base
{
public int I = 0;
public Base(int ignored) { }
}
public record C(int I) : Base(I)
{
public const int I = 0;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics(
// (7,21): error CS8866: Record member 'C.I' must be a readable instance property or field of type 'int' to match positional parameter 'I'.
// public record C(int I) : Base(I)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "I").WithArguments("C.I", "int", "I").WithLocation(7, 21),
// (9,22): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended.
// public const int I = 0;
Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 22)
);
}
[Fact]
public void FieldAsPositionalMember()
{
var source = @"
var a = new A(42);
System.Console.Write(a.X);
System.Console.Write("" - "");
a.Deconstruct(out int x);
System.Console.Write(x);
record A(int X)
{
public int X = X;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (8,10): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater.
// record A(int X)
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int X").WithArguments("positional fields in records", "10.0").WithLocation(8, 10)
);
comp = CreateCompilation(source, parseOptions: TestOptions.Regular10);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "42 - 42");
verifier.VerifyIL("A.Deconstruct", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: ldfld ""int A.X""
IL_0007: stind.i4
IL_0008: ret
}
");
}
[Fact]
public void FieldAsPositionalMember_TwoParameters()
{
var source = @"
var a = new A(42, 43);
System.Console.Write(a.Y);
System.Console.Write("" - "");
a.Deconstruct(out int x, out int y);
System.Console.Write(y);
record A(int X, int Y)
{
public int X = X;
public int Y = Y;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "43 - 43");
verifier.VerifyIL("A.Deconstruct", @"
{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: ldfld ""int A.X""
IL_0007: stind.i4
IL_0008: ldarg.2
IL_0009: ldarg.0
IL_000a: ldfld ""int A.Y""
IL_000f: stind.i4
IL_0010: ret
}
");
}
[Fact]
public void FieldAsPositionalMember_Readonly()
{
var source = @"
var a = new A(42);
System.Console.Write(a.X);
System.Console.Write("" - "");
a.Deconstruct(out int x);
System.Console.Write(x);
record A(int X)
{
public readonly int X = X;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "42 - 42", verify: Verification.Skipped /* init-only */);
verifier.VerifyIL("A.Deconstruct", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: ldfld ""int A.X""
IL_0007: stind.i4
IL_0008: ret
}
");
}
[Fact]
public void FieldAsPositionalMember_UnusedParameter()
{
var source = @"
record A(int X)
{
public int X;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics(
// (2,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name?
// record A(int X)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 14),
// (4,16): warning CS0649: Field 'A.X' is never assigned to, and will always have its default value 0
// public int X;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "X").WithArguments("A.X", "0").WithLocation(4, 16)
);
}
[Fact]
public void FieldAsPositionalMember_CurrentTypeComesFirst()
{
var source = @"
var c = new C(42);
c.Deconstruct(out int i);
System.Console.Write(i);
public record Base
{
public int I { get; set; } = 0;
}
public record C(int I) : Base
{
public int I = I;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (12,16): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended.
// public int I = I;
Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(12, 16)
);
var verifier = CompileAndVerify(comp, expectedOutput: "42");
verifier.VerifyIL("C.Deconstruct", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: ldfld ""int C.I""
IL_0007: stind.i4
IL_0008: ret
}
");
}
[Fact]
public void FieldAsPositionalMember_CurrentTypeComesFirst_FieldInBase()
{
var source = @"
var c = new C(42);
c.Deconstruct(out int i);
System.Console.Write(i);
public record Base
{
public int I = 0;
}
public record C(int I) : Base
{
public int I { get; set; } = I;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (12,16): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended.
// public int I { get; set; } = I;
Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(12, 16)
);
var verifier = CompileAndVerify(comp, expectedOutput: "42");
verifier.VerifyIL("C.Deconstruct", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: call ""int C.I.get""
IL_0007: stind.i4
IL_0008: ret
}
");
}
[Fact]
public void FieldAsPositionalMember_FieldFromBase()
{
var source = @"
var c = new C(0);
c.Deconstruct(out int i);
System.Console.Write(i);
public record Base
{
public int I = 42;
public Base(int ignored) { }
}
public record C(int I) : Base(I)
{
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "42");
verifier.VerifyIL("C.Deconstruct", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: ldfld ""int Base.I""
IL_0007: stind.i4
IL_0008: ret
}
");
}
[Fact]
public void FieldAsPositionalMember_FieldFromBase_StaticFieldInDerivedType()
{
var source = @"
public record Base
{
public int I = 42;
public Base(int ignored) { }
}
public record C(int I) : Base(I)
{
public static int I = 42;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (7,21): error CS8866: Record member 'C.I' must be a readable instance property or field of type 'int' to match positional parameter 'I'.
// public record C(int I) : Base(I)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "I").WithArguments("C.I", "int", "I").WithLocation(7, 21),
// (9,23): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended.
// public static int I = 42;
Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 23)
);
comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (7,21): error CS8866: Record member 'C.I' must be a readable instance property or field of type 'int' to match positional parameter 'I'.
// public record C(int I) : Base(I)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "I").WithArguments("C.I", "int", "I").WithLocation(7, 21),
// (9,23): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended.
// public static int I = 42;
Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 23)
);
source = @"
public record Base
{
public int I { get; set; } = 42;
public Base(int ignored) { }
}
public record C(int I) : Base(I)
{
public static int I { get; set; } = 42;
}
";
comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (7,21): error CS8866: Record member 'C.I' must be a readable instance property or field of type 'int' to match positional parameter 'I'.
// public record C(int I) : Base(I)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "I").WithArguments("C.I", "int", "I").WithLocation(7, 21),
// (9,23): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended.
// public static int I { get; set; } = 42;
Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 23)
);
}
[Fact]
public void FieldAsPositionalMember_Static()
{
var source = @"
record A(int X)
{
public static int X = 0;
public int Y = X;
}
";
var comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics(
// (2,14): error CS8866: Record member 'A.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'.
// record A(int X)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("A.X", "int", "X").WithLocation(2, 14)
);
}
[Fact]
public void FieldAsPositionalMember_Const()
{
var src = @"
record C(int P)
{
const int P = 4;
}
record C2(int P)
{
const int P = P;
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (2,14): error CS8866: Record member 'C.P' must be a readable instance property or field of type 'int' to match positional parameter 'P'.
// record C(int P)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("C.P", "int", "P").WithLocation(2, 14),
// (2,14): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name?
// record C(int P)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 14),
// (6,15): error CS8866: Record member 'C2.P' must be a readable instance property or field of type 'int' to match positional parameter 'P'.
// record C2(int P)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("C2.P", "int", "P").WithLocation(6, 15),
// (6,15): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name?
// record C2(int P)
Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(6, 15),
// (8,15): error CS0110: The evaluation of the constant value for 'C2.P' involves a circular definition
// const int P = P;
Diagnostic(ErrorCode.ERR_CircConstValue, "P").WithArguments("C2.P").WithLocation(8, 15)
);
}
[Fact]
public void FieldAsPositionalMember_Volatile()
{
var src = @"
record C(int P)
{
public volatile int P = P;
}";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics();
}
[Fact]
public void FieldAsPositionalMember_DifferentAccessibility()
{
var src = @"
record C(int P)
{
private int P = P;
}
record C2(int P)
{
protected int P = P;
}
record C3(int P)
{
internal int P = P;
}
";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics();
}
[Fact]
public void FieldAsPositionalMember_WrongType()
{
var src = @"
record C(int P)
{
public string P = null;
public int Q = P;
}";
var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics(
// (2,14): error CS8866: Record member 'C.P' must be a readable instance property or field of type 'int' to match positional parameter 'P'.
// record C(int P)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("C.P", "int", "P").WithLocation(2, 14)
);
}
[Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")]
public void HiddenPositionalMember_Property_HiddenWithZeroArityMethod()
{
var source = @"
public record Base
{
public int I { get; set; } = 42;
public Base(int ignored) { }
}
public record C(int I) : Base(I)
{
public void I() { }
}
";
var expected = new[]
{
// (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden.
// public record C(int I) : Base(I)
Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21),
// (9,17): warning CS0108: 'C.I()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended.
// public void I() { }
Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I()", "Base.I").WithLocation(9, 17)
};
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(expected);
comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics(expected);
}
[Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")]
public void HiddenPositionalMember_Property_HiddenWithZeroArityMethod_DeconstructInSource()
{
var source = @"
public record Base
{
public int I { get; set; } = 42;
public Base(int ignored) { }
}
public record C(int I) : Base(I)
{
public void I() { }
public void Deconstruct(out int i) { i = 0; }
}
";
var expected = new[]
{
// (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden.
// public record C(int I) : Base(I)
Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21),
// (9,17): warning CS0108: 'C.I()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended.
// public void I() { }
Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I()", "Base.I").WithLocation(9, 17)
};
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(expected);
comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics(expected);
}
[Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")]
public void HiddenPositionalMember_Property_HiddenWithZeroArityMethod_WithNew()
{
var source = @"
public record Base
{
public int I { get; set; } = 42;
public Base(int ignored) { }
}
public record C(int I) : Base(I) // 1
{
public new void I() { }
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics(
// (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden.
// public record C(int I) : Base(I) // 1
Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21)
);
}
[Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")]
public void HiddenPositionalMember_Property_HiddenWithGenericMethod()
{
var source = @"
var c = new C(0);
c.Deconstruct(out int i);
System.Console.Write(i);
public record Base
{
public int I { get; set; } = 42;
public Base(int ignored) { }
}
public record C(int I) : Base(I)
{
public void I<T>() { }
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics(
// (11,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden.
// public record C(int I) : Base(I)
Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(11, 21),
// (13,17): warning CS0108: 'C.I<T>()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended.
// public void I<T>() { }
Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I<T>()", "Base.I").WithLocation(13, 17)
);
}
[Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")]
public void HiddenPositionalMember_Property_FromGrandBase()
{
var source = @"
public record GrandBase
{
public int I { get; set; } = 42;
}
public record Base : GrandBase
{
public Base(int ignored) { }
}
public record C(int I) : Base(I)
{
public void I() { }
}
";
var expected = new[]
{
// (10,21): error CS8913: The positional member 'GrandBase.I' found corresponding to this parameter is hidden.
// public record C(int I) : Base(I)
Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("GrandBase.I").WithLocation(10, 21),
// (12,17): warning CS0108: 'C.I()' hides inherited member 'GrandBase.I'. Use the new keyword if hiding was intended.
// public void I() { }
Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I()", "GrandBase.I").WithLocation(12, 17)
};
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics(expected);
}
[Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")]
public void HiddenPositionalMember_Property_NotHiddenByIndexer()
{
var source = @"
var c = new C(0);
c.Deconstruct(out int i);
System.Console.Write(i);
public record Base
{
public int Item { get; set; } = 42;
public Base(int ignored) { }
}
public record C(int Item) : Base(Item)
{
public int this[int x] { get => throw null; }
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "42");
verifier.VerifyIL("C.Deconstruct", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: call ""int Base.Item.get""
IL_0007: stind.i4
IL_0008: ret
}
");
}
[Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")]
public void HiddenPositionalMember_Property_NotHiddenByIndexer_WithIndexerName()
{
var source = @"
var c = new C(0);
c.Deconstruct(out int i);
System.Console.Write(i);
public record Base
{
public int I { get; set; } = 42;
public Base(int ignored) { }
}
public record C(int I) : Base(I)
{
[System.Runtime.CompilerServices.IndexerName(""I"")]
public int this[int x] { get => throw null; }
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "42");
verifier.VerifyIL("C.Deconstruct", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldarg.0
IL_0002: call ""int Base.I.get""
IL_0007: stind.i4
IL_0008: ret
}
");
}
[Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")]
public void HiddenPositionalMember_Property_HiddenWithType()
{
var source = @"
public record Base
{
public int I { get; set; } = 42;
public Base(int ignored) { }
}
public record C(int I) : Base(I)
{
public class I { }
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics(
// (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden.
// public record C(int I) : Base(I)
Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21),
// (9,18): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended.
// public class I { }
Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 18)
);
}
[Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")]
public void HiddenPositionalMember_Property_HiddenWithEvent()
{
var source = @"
public record Base
{
public int I { get; set; } = 42;
public Base(int ignored) { }
}
public record C(int I) : Base(I)
{
public event System.Action I;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics(
// (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden.
// public record C(int I) : Base(I)
Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21),
// (9,32): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended.
// public event System.Action I;
Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 32),
// (9,32): warning CS0067: The event 'C.I' is never used
// public event System.Action I;
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "I").WithArguments("C.I").WithLocation(9, 32)
);
}
[Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")]
public void HiddenPositionalMember_Property_HiddenWithConstant()
{
var source = @"
public record Base
{
public int I { get; set; } = 42;
public Base(int ignored) { }
}
public record C(int I) : Base(I)
{
public const string I = null;
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics(
// (7,21): error CS8866: Record member 'C.I' must be a readable instance property or field of type 'int' to match positional parameter 'I'.
// public record C(int I) : Base(I)
Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "I").WithArguments("C.I", "int", "I").WithLocation(7, 21),
// (9,25): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended.
// public const string I = null;
Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 25)
);
}
[Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")]
public void HiddenPositionalMember_Property_AbstractInBase()
{
var source = @"
abstract record Base
{
public abstract int I { get; init; }
}
record Derived(int I) : Base
{
public int I() { return 0; }
}
";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics(
// (8,16): warning CS0108: 'Derived.I()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended.
// public int I() { return 0; }
Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("Derived.I()", "Base.I").WithLocation(8, 16),
// (8,16): error CS0102: The type 'Derived' already contains a definition for 'I'
// public int I() { return 0; }
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "I").WithArguments("Derived", "I").WithLocation(8, 16)
);
}
[Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")]
public void HiddenPositionalMember_Property_AbstractInBase_AbstractInDerived()
{
var source = @"
abstract record Base
{
public abstract int I { get; init; }
}
abstract record Derived(int I) : Base
{
public int I() { return 0; }
}
";
var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview);
comp.VerifyEmitDiagnostics(
// (8,16): error CS0533: 'Derived.I()' hides inherited abstract member 'Base.I'
// public int I() { return 0; }
Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "I").WithArguments("Derived.I()", "Base.I").WithLocation(8, 16),
// (8,16): error CS0102: The type 'Derived' already contains a definition for 'I'
// public int I() { return 0; }
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "I").WithArguments("Derived", "I").WithLocation(8, 16)
);
}
[Fact]
public void InterfaceWithParameters()
{
var src = @"
public interface I
{
}
record R(int X) : I()
{
}
record R2(int X) : I(X)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (6,20): error CS8861: Unexpected argument list.
// record R(int X) : I()
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 20),
// (10,21): error CS8861: Unexpected argument list.
// record R2(int X) : I(X)
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(10, 21),
// (10,21): error CS1729: 'object' does not contain a constructor that takes 1 arguments
// record R2(int X) : I(X)
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(10, 21)
);
}
[Fact]
public void InterfaceWithParameters_RecordClass()
{
var src = @"
public interface I
{
}
record class R(int X) : I()
{
}
record class R2(int X) : I(X)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (6,26): error CS8861: Unexpected argument list.
// record class R(int X) : I()
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 26),
// (10,27): error CS8861: Unexpected argument list.
// record class R2(int X) : I(X)
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(10, 27),
// (10,27): error CS1729: 'object' does not contain a constructor that takes 1 arguments
// record class R2(int X) : I(X)
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(10, 27)
);
}
[Fact]
public void BaseErrorTypeWithParameters()
{
var src = @"
record R2(int X) : Error(X)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (2,8): error CS0115: 'R2.ToString()': no suitable method found to override
// record R2(int X) : Error(X)
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R2").WithArguments("R2.ToString()").WithLocation(2, 8),
// (2,8): error CS0115: 'R2.EqualityContract': no suitable method found to override
// record R2(int X) : Error(X)
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R2").WithArguments("R2.EqualityContract").WithLocation(2, 8),
// (2,8): error CS0115: 'R2.Equals(object?)': no suitable method found to override
// record R2(int X) : Error(X)
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R2").WithArguments("R2.Equals(object?)").WithLocation(2, 8),
// (2,8): error CS0115: 'R2.GetHashCode()': no suitable method found to override
// record R2(int X) : Error(X)
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R2").WithArguments("R2.GetHashCode()").WithLocation(2, 8),
// (2,8): error CS0115: 'R2.PrintMembers(StringBuilder)': no suitable method found to override
// record R2(int X) : Error(X)
Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R2").WithArguments("R2.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8),
// (2,20): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?)
// record R2(int X) : Error(X)
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(2, 20),
// (2,25): error CS1729: 'Error' does not contain a constructor that takes 1 arguments
// record R2(int X) : Error(X)
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("Error", "1").WithLocation(2, 25)
);
}
[Fact]
public void BaseDynamicTypeWithParameters()
{
var src = @"
record R(int X) : dynamic(X)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (2,19): error CS1965: 'R': cannot derive from the dynamic type
// record R(int X) : dynamic(X)
Diagnostic(ErrorCode.ERR_DeriveFromDynamic, "dynamic").WithArguments("R").WithLocation(2, 19),
// (2,26): error CS1729: 'object' does not contain a constructor that takes 1 arguments
// record R(int X) : dynamic(X)
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(2, 26)
);
}
[Fact]
public void BaseTypeParameterTypeWithParameters()
{
var src = @"
class C<T>
{
record R(int X) : T(X)
{
}
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (4,23): error CS0689: Cannot derive from 'T' because it is a type parameter
// record R(int X) : T(X)
Diagnostic(ErrorCode.ERR_DerivingFromATyVar, "T").WithArguments("T").WithLocation(4, 23),
// (4,24): error CS1729: 'object' does not contain a constructor that takes 1 arguments
// record R(int X) : T(X)
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(4, 24)
);
}
[Fact]
public void BaseObjectTypeWithParameters()
{
var src = @"
record R(int X) : object(X)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (2,25): error CS1729: 'object' does not contain a constructor that takes 1 arguments
// record R(int X) : object(X)
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(2, 25)
);
}
[Fact]
public void BaseValueTypeTypeWithParameters()
{
var src = @"
record R(int X) : System.ValueType(X)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (2,19): error CS0644: 'R' cannot derive from special class 'ValueType'
// record R(int X) : System.ValueType(X)
Diagnostic(ErrorCode.ERR_DeriveFromEnumOrValueType, "System.ValueType").WithArguments("R", "System.ValueType").WithLocation(2, 19),
// (2,35): error CS1729: 'object' does not contain a constructor that takes 1 arguments
// record R(int X) : System.ValueType(X)
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(2, 35)
);
}
[Fact]
public void InterfaceWithParameters_NoPrimaryConstructor()
{
var src = @"
public interface I
{
}
record R : I()
{
}
record R2 : I(0)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (6,13): error CS8861: Unexpected argument list.
// record R : I()
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 13),
// (10,14): error CS8861: Unexpected argument list.
// record R2 : I(0)
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(0)").WithLocation(10, 14)
);
}
[Fact]
public void InterfaceWithParameters_Class()
{
var src = @"
public interface I
{
}
class C : I()
{
}
class C2 : I(0)
{
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics(
// (6,12): error CS8861: Unexpected argument list.
// class C : I()
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 12),
// (10,13): error CS8861: Unexpected argument list.
// class C2 : I(0)
Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(0)").WithLocation(10, 13)
);
}
[Theory, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")]
[CombinatorialData]
public void CrossAssemblySupportingAndNotSupportingCovariantReturns(bool useCompilationReference)
{
var sourceA =
@"public record B(int I)
{
}
public record C(int I) : B(I);";
var compA = CreateEmptyCompilation(new[] { sourceA, IsExternalInitTypeDefinition }, references: TargetFrameworkUtil.GetReferences(TargetFramework.NetStandard20));
compA.VerifyDiagnostics();
Assert.False(compA.Assembly.RuntimeSupportsCovariantReturnsOfClasses);
var actualMembers = compA.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings();
var expectedMembers = new[]
{
"C..ctor(System.Int32 I)",
"System.Type C.EqualityContract.get",
"System.Type C.EqualityContract { get; }",
"System.String C.ToString()",
"System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)",
"System.Boolean C.op_Inequality(C? left, C? right)",
"System.Boolean C.op_Equality(C? left, C? right)",
"System.Int32 C.GetHashCode()",
"System.Boolean C.Equals(System.Object? obj)",
"System.Boolean C.Equals(B? other)",
"System.Boolean C.Equals(C? other)",
"B C." + WellKnownMemberNames.CloneMethodName + "()",
"C..ctor(C original)",
"void C.Deconstruct(out System.Int32 I)",
};
AssertEx.Equal(expectedMembers, actualMembers);
var refA = useCompilationReference ? compA.ToMetadataReference() : compA.EmitToImageReference();
var sourceB = "record D(int I) : C(I);";
// CS1701: Assuming assembly reference '{0}' used by '{1}' matches identity '{2}' of '{3}', you may need to supply runtime policy
var compB = CreateCompilation(sourceB, references: new[] { refA }, options: TestOptions.ReleaseDll.WithSpecificDiagnosticOptions("CS1701", ReportDiagnostic.Suppress), parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp);
compB.VerifyDiagnostics();
Assert.True(compB.Assembly.RuntimeSupportsCovariantReturnsOfClasses);
actualMembers = compB.GetMember<NamedTypeSymbol>("D").GetMembers().ToTestDisplayStrings();
expectedMembers = new[]
{
"D..ctor(System.Int32 I)",
"System.Type D.EqualityContract.get",
"System.Type D.EqualityContract { get; }",
"System.String D.ToString()",
"System.Boolean D." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)",
"System.Boolean D.op_Inequality(D? left, D? right)",
"System.Boolean D.op_Equality(D? left, D? right)",
"System.Int32 D.GetHashCode()",
"System.Boolean D.Equals(System.Object? obj)",
"System.Boolean D.Equals(C? other)",
"System.Boolean D.Equals(D? other)",
"D D." + WellKnownMemberNames.CloneMethodName + "()",
"D..ctor(D original)",
"void D.Deconstruct(out System.Int32 I)"
};
AssertEx.Equal(expectedMembers, actualMembers);
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Analyzers/CSharp/CodeFixes/UseConditionalExpression/CSharpUseConditionalExpressionForReturnCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.UseConditionalExpression;
#if CODE_STYLE
using Microsoft.CodeAnalysis.CSharp.Formatting;
#endif
namespace Microsoft.CodeAnalysis.CSharp.UseConditionalExpression
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseConditionalExpressionForReturn), Shared]
internal partial class CSharpUseConditionalExpressionForReturnCodeFixProvider
: AbstractUseConditionalExpressionForReturnCodeFixProvider<StatementSyntax, IfStatementSyntax, ExpressionSyntax, ConditionalExpressionSyntax>
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpUseConditionalExpressionForReturnCodeFixProvider()
{
}
protected override AbstractFormattingRule GetMultiLineFormattingRule()
=> MultiLineConditionalExpressionFormattingRule.Instance;
protected override StatementSyntax WrapWithBlockIfAppropriate(
IfStatementSyntax ifStatement, StatementSyntax statement)
{
if (ifStatement.Parent is ElseClauseSyntax &&
ifStatement.Statement is BlockSyntax block)
{
return block.WithStatements(SyntaxFactory.SingletonList(statement))
.WithAdditionalAnnotations(Formatter.Annotation);
}
return statement;
}
protected override ExpressionSyntax ConvertToExpression(IThrowOperation throwOperation)
=> CSharpUseConditionalExpressionHelpers.ConvertToExpression(throwOperation);
#if CODE_STYLE
protected override ISyntaxFormattingService GetSyntaxFormattingService()
=> CSharpSyntaxFormattingService.Instance;
#endif
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.UseConditionalExpression;
#if CODE_STYLE
using Microsoft.CodeAnalysis.CSharp.Formatting;
#endif
namespace Microsoft.CodeAnalysis.CSharp.UseConditionalExpression
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseConditionalExpressionForReturn), Shared]
internal partial class CSharpUseConditionalExpressionForReturnCodeFixProvider
: AbstractUseConditionalExpressionForReturnCodeFixProvider<StatementSyntax, IfStatementSyntax, ExpressionSyntax, ConditionalExpressionSyntax>
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpUseConditionalExpressionForReturnCodeFixProvider()
{
}
protected override AbstractFormattingRule GetMultiLineFormattingRule()
=> MultiLineConditionalExpressionFormattingRule.Instance;
protected override StatementSyntax WrapWithBlockIfAppropriate(
IfStatementSyntax ifStatement, StatementSyntax statement)
{
if (ifStatement.Parent is ElseClauseSyntax &&
ifStatement.Statement is BlockSyntax block)
{
return block.WithStatements(SyntaxFactory.SingletonList(statement))
.WithAdditionalAnnotations(Formatter.Annotation);
}
return statement;
}
protected override ExpressionSyntax ConvertToExpression(IThrowOperation throwOperation)
=> CSharpUseConditionalExpressionHelpers.ConvertToExpression(throwOperation);
#if CODE_STYLE
protected override ISyntaxFormattingService GetSyntaxFormattingService()
=> CSharpSyntaxFormattingService.Instance;
#endif
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/VisualStudioDiagnosticsToolWindow/OptionPages/PerformanceFunctionIdPage.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Runtime.InteropServices;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.VisualStudio.LanguageServices;
using Microsoft.VisualStudio.LanguageServices.Implementation.Options;
namespace Roslyn.VisualStudio.DiagnosticsWindow.OptionsPages
{
[Guid(Guids.RoslynOptionPagePerformanceFunctionIdIdString)]
internal class PerformanceFunctionIdPage : AbstractOptionPage
{
protected override AbstractOptionPageControl CreateOptionPage(IServiceProvider serviceProvider, OptionStore optionStore)
{
return new InternalOptionsControl(nameof(FunctionIdOptions), optionStore);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Runtime.InteropServices;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.VisualStudio.LanguageServices;
using Microsoft.VisualStudio.LanguageServices.Implementation.Options;
namespace Roslyn.VisualStudio.DiagnosticsWindow.OptionsPages
{
[Guid(Guids.RoslynOptionPagePerformanceFunctionIdIdString)]
internal class PerformanceFunctionIdPage : AbstractOptionPage
{
protected override AbstractOptionPageControl CreateOptionPage(IServiceProvider serviceProvider, OptionStore optionStore)
{
return new InternalOptionsControl(nameof(FunctionIdOptions), optionStore);
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/IntegrationTest/TestUtilities/ScreenshotService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Forms;
using System.Windows.Media.Imaging;
using PixelFormats = System.Windows.Media.PixelFormats;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities
{
internal static class ScreenshotService
{
private static readonly object s_gate = new object();
/// <summary>
/// Takes a picture of the screen and saves it to the location specified by
/// <paramref name="fullPath"/>. Files are always saved in PNG format, regardless of the
/// file extension.
/// </summary>
public static void TakeScreenshot(string fullPath)
{
// This gate prevents concurrency for two reasons:
//
// 1. Only one screenshot is held in memory at a time to prevent running out of memory for large displays
// 2. Only one screenshot is written to disk at a time to avoid exceptions if concurrent calls are writing
// to the same file
lock (s_gate)
{
var bitmap = TryCaptureFullScreen();
if (bitmap == null)
{
return;
}
var directory = Path.GetDirectoryName(fullPath);
Directory.CreateDirectory(directory);
using (var fileStream = new FileStream(fullPath, FileMode.Create, FileAccess.Write))
{
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmap));
encoder.Save(fileStream);
}
}
}
/// <summary>
/// Captures the full screen to a <see cref="Bitmap"/>.
/// </summary>
/// <returns>
/// A <see cref="Bitmap"/> containing the screen capture of the desktop, or null if a screen
/// capture can't be created.
/// </returns>
private static BitmapSource? TryCaptureFullScreen()
{
var width = Screen.PrimaryScreen.Bounds.Width;
var height = Screen.PrimaryScreen.Bounds.Height;
if (width <= 0 || height <= 0)
{
// Don't try to take a screenshot if there is no screen.
// This may not be an interactive session.
return null;
}
using (var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb))
using (var graphics = Graphics.FromImage(bitmap))
{
graphics.CopyFromScreen(
sourceX: Screen.PrimaryScreen.Bounds.X,
sourceY: Screen.PrimaryScreen.Bounds.Y,
destinationX: 0,
destinationY: 0,
blockRegionSize: bitmap.Size,
copyPixelOperation: CopyPixelOperation.SourceCopy);
var bitmapData = bitmap.LockBits(
new Rectangle(0, 0, bitmap.Width, bitmap.Height),
ImageLockMode.ReadOnly,
PixelFormat.Format32bppArgb);
try
{
return BitmapSource.Create(
bitmapData.Width,
bitmapData.Height,
bitmap.HorizontalResolution,
bitmap.VerticalResolution,
PixelFormats.Bgra32,
null,
bitmapData.Scan0,
bitmapData.Stride * bitmapData.Height,
bitmapData.Stride);
}
finally
{
bitmap.UnlockBits(bitmapData);
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Forms;
using System.Windows.Media.Imaging;
using PixelFormats = System.Windows.Media.PixelFormats;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities
{
internal static class ScreenshotService
{
private static readonly object s_gate = new object();
/// <summary>
/// Takes a picture of the screen and saves it to the location specified by
/// <paramref name="fullPath"/>. Files are always saved in PNG format, regardless of the
/// file extension.
/// </summary>
public static void TakeScreenshot(string fullPath)
{
// This gate prevents concurrency for two reasons:
//
// 1. Only one screenshot is held in memory at a time to prevent running out of memory for large displays
// 2. Only one screenshot is written to disk at a time to avoid exceptions if concurrent calls are writing
// to the same file
lock (s_gate)
{
var bitmap = TryCaptureFullScreen();
if (bitmap == null)
{
return;
}
var directory = Path.GetDirectoryName(fullPath);
Directory.CreateDirectory(directory);
using (var fileStream = new FileStream(fullPath, FileMode.Create, FileAccess.Write))
{
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmap));
encoder.Save(fileStream);
}
}
}
/// <summary>
/// Captures the full screen to a <see cref="Bitmap"/>.
/// </summary>
/// <returns>
/// A <see cref="Bitmap"/> containing the screen capture of the desktop, or null if a screen
/// capture can't be created.
/// </returns>
private static BitmapSource? TryCaptureFullScreen()
{
var width = Screen.PrimaryScreen.Bounds.Width;
var height = Screen.PrimaryScreen.Bounds.Height;
if (width <= 0 || height <= 0)
{
// Don't try to take a screenshot if there is no screen.
// This may not be an interactive session.
return null;
}
using (var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb))
using (var graphics = Graphics.FromImage(bitmap))
{
graphics.CopyFromScreen(
sourceX: Screen.PrimaryScreen.Bounds.X,
sourceY: Screen.PrimaryScreen.Bounds.Y,
destinationX: 0,
destinationY: 0,
blockRegionSize: bitmap.Size,
copyPixelOperation: CopyPixelOperation.SourceCopy);
var bitmapData = bitmap.LockBits(
new Rectangle(0, 0, bitmap.Width, bitmap.Height),
ImageLockMode.ReadOnly,
PixelFormat.Format32bppArgb);
try
{
return BitmapSource.Create(
bitmapData.Width,
bitmapData.Height,
bitmap.HorizontalResolution,
bitmap.VerticalResolution,
PixelFormats.Bgra32,
null,
bitmapData.Scan0,
bitmapData.Stride * bitmapData.Height,
bitmapData.Stride);
}
finally
{
bitmap.UnlockBits(bitmapData);
}
}
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/Portable/CodeGen/SwitchIntegralJumpTableEmitter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Reflection.Metadata;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeGen
{
/// <summary>
/// Class for emitting the switch jump table for switch statements with integral governing type
/// </summary>
internal partial struct SwitchIntegralJumpTableEmitter
{
private readonly ILBuilder _builder;
/// <summary>
/// Switch key for the jump table
/// </summary>
private readonly LocalOrParameter _key;
/// <summary>
/// Primitive type of the switch key
/// </summary>
private readonly Cci.PrimitiveTypeCode _keyTypeCode;
/// <summary>
/// Fall through label for the jump table
/// </summary>
private readonly object _fallThroughLabel;
/// <summary>
/// Integral case labels sorted and indexed by their ConstantValue
/// </summary>
private readonly ImmutableArray<KeyValuePair<ConstantValue, object>> _sortedCaseLabels;
// threshold at which binary search stops partitioning.
// if a search leaf has less than LinearSearchThreshold buckets
// we just go through buckets linearly.
// We chose 3 here because it is where number of branches to reach fall-through
// is the same for linear and binary search.
private const int LinearSearchThreshold = 3;
internal SwitchIntegralJumpTableEmitter(
ILBuilder builder,
KeyValuePair<ConstantValue, object>[] caseLabels,
object fallThroughLabel,
Cci.PrimitiveTypeCode keyTypeCode,
LocalOrParameter key)
{
_builder = builder;
_key = key;
_keyTypeCode = keyTypeCode;
_fallThroughLabel = fallThroughLabel;
// Sort the switch case labels, see comments below for more details.
Debug.Assert(caseLabels.Length > 0);
Array.Sort(caseLabels, CompareIntegralSwitchLabels);
_sortedCaseLabels = ImmutableArray.Create(caseLabels);
}
internal void EmitJumpTable()
{
// For emitting the switch statement (integral governing type) jump table with a non-constant
// switch expression, we can use a naive approach and generate a single big MSIL switch instruction
// with all the case labels and fall through label. However, this approach can be optimized
// to improve both the code size and speed using the following optimization steps:
// a) Sort the switch case labels based on their constant values.
// b) Divide the sorted switch labels into buckets with good enough density (>50%). For example:
// switch(..)
// {
// case 1:
// case 100:
// break;
// case 2:
// case 4:
// break;
// case 200:
// case 201:
// case 202:
// break;
// }
// can be divided into 3 buckets: (1, 2, 4) (100) (200, 201, 202).
// We do this bucketing so that we have reasonable size jump tables for generated switch instructions.
// c) After bucketing, generate code to perform a binary search on these buckets array,
// emitting conditional jumps if current bucket sub-array has more than one bucket and
// emitting the switch instruction when we are down to a single bucket in the sub-array.
// (a) Sort switch labels: This was done in the constructor
Debug.Assert(!_sortedCaseLabels.IsEmpty);
var sortedCaseLabels = _sortedCaseLabels;
int endLabelIndex = sortedCaseLabels.Length - 1;
int startLabelIndex;
// Check for a label with ConstantValue.Null.
// Sorting ensures that if we do have one, it will be
// the first label in the sorted list.
if (sortedCaseLabels[0].Key != ConstantValue.Null)
{
startLabelIndex = 0;
}
else
{
// Skip null label for emitting switch table header.
// We should have inserted a conditional branch to 'null' label during rewriting.
// See LocalRewriter.MakeSwitchStatementWithNullableExpression
startLabelIndex = 1;
}
if (startLabelIndex <= endLabelIndex)
{
// We have at least one non-null case label, emit jump table
// (b) Generate switch buckets
ImmutableArray<SwitchBucket> switchBuckets = this.GenerateSwitchBuckets(startLabelIndex, endLabelIndex);
// (c) Emit switch buckets
this.EmitSwitchBuckets(switchBuckets, 0, switchBuckets.Length - 1);
}
else
{
_builder.EmitBranch(ILOpCode.Br, _fallThroughLabel);
}
}
#region "Sorting switch labels"
private static int CompareIntegralSwitchLabels(KeyValuePair<ConstantValue, object> first, KeyValuePair<ConstantValue, object> second)
{
ConstantValue firstConstant = first.Key;
ConstantValue secondConstant = second.Key;
RoslynDebug.Assert(firstConstant != null);
Debug.Assert(SwitchConstantValueHelper.IsValidSwitchCaseLabelConstant(firstConstant)
&& !firstConstant.IsString);
RoslynDebug.Assert(secondConstant != null);
Debug.Assert(SwitchConstantValueHelper.IsValidSwitchCaseLabelConstant(secondConstant)
&& !secondConstant.IsString);
return SwitchConstantValueHelper.CompareSwitchCaseLabelConstants(firstConstant, secondConstant);
}
#endregion
#region "Switch bucketing methods"
// Bucketing algorithm:
// Start with empty stack of buckets.
// While there are still labels
// If bucket from remaining labels is dense
// Create a newBucket from remaining labels
// Else
// Create a singleton newBucket from the next label
// While the top bucket on stack can be merged with newBucket into a dense bucket
// merge top bucket on stack into newBucket, and pop bucket from stack
// End While
// Push newBucket on stack
// End While
private ImmutableArray<SwitchBucket> GenerateSwitchBuckets(int startLabelIndex, int endLabelIndex)
{
Debug.Assert(startLabelIndex >= 0 && startLabelIndex <= endLabelIndex);
Debug.Assert(_sortedCaseLabels.Length > endLabelIndex);
// Start with empty stack of buckets.
var switchBucketsStack = ArrayBuilder<SwitchBucket>.GetInstance();
int curStartLabelIndex = startLabelIndex;
// While there are still labels
while (curStartLabelIndex <= endLabelIndex)
{
SwitchBucket newBucket = CreateNextBucket(curStartLabelIndex, endLabelIndex);
// While the top bucket on stack can be merged with newBucket into a dense bucket
// merge top bucket on stack into newBucket, and pop bucket from stack
// End While
while (!switchBucketsStack.IsEmpty())
{
// get the bucket at top of the stack
SwitchBucket prevBucket = switchBucketsStack.Peek();
if (newBucket.TryMergeWith(prevBucket))
{
// pop the previous bucket from the stack
switchBucketsStack.Pop();
}
else
{
// merge failed
break;
}
}
// Push newBucket on stack
switchBucketsStack.Push(newBucket);
// update curStartLabelIndex
curStartLabelIndex++;
}
Debug.Assert(!switchBucketsStack.IsEmpty());
// crumble leaf buckets into degenerate buckets where possible
var crumbled = ArrayBuilder<SwitchBucket>.GetInstance();
foreach (var uncrumbled in switchBucketsStack)
{
var degenerateSplit = uncrumbled.DegenerateBucketSplit;
switch (degenerateSplit)
{
case -1:
// cannot be split
crumbled.Add(uncrumbled);
break;
case 0:
// already degenerate
crumbled.Add(new SwitchBucket(_sortedCaseLabels, uncrumbled.StartLabelIndex, uncrumbled.EndLabelIndex, isDegenerate: true));
break;
default:
// can split
crumbled.Add(new SwitchBucket(_sortedCaseLabels, uncrumbled.StartLabelIndex, degenerateSplit - 1, isDegenerate: true));
crumbled.Add(new SwitchBucket(_sortedCaseLabels, degenerateSplit, uncrumbled.EndLabelIndex, isDegenerate: true));
break;
}
}
switchBucketsStack.Free();
return crumbled.ToImmutableAndFree();
}
private SwitchBucket CreateNextBucket(int startLabelIndex, int endLabelIndex)
{
Debug.Assert(startLabelIndex >= 0 && startLabelIndex <= endLabelIndex);
return new SwitchBucket(_sortedCaseLabels, startLabelIndex);
}
#endregion
#region "Switch bucket emit methods"
private void EmitSwitchBucketsLinearLeaf(ImmutableArray<SwitchBucket> switchBuckets, int low, int high)
{
for (int i = low; i < high; i++)
{
var nextBucketLabel = new object();
this.EmitSwitchBucket(switchBuckets[i], nextBucketLabel);
// nextBucketLabel:
_builder.MarkLabel(nextBucketLabel);
}
this.EmitSwitchBucket(switchBuckets[high], _fallThroughLabel);
}
private void EmitSwitchBuckets(ImmutableArray<SwitchBucket> switchBuckets, int low, int high)
{
// if (high - low + 1 <= LinearSearchThreshold)
if (high - low < LinearSearchThreshold)
{
this.EmitSwitchBucketsLinearLeaf(switchBuckets, low, high);
return;
}
// This way (0 1 2 3) will produce a mid of 2 while
// (0 1 2) will produce a mid of 1
// Now, the first half is first to mid-1
// and the second half is mid to last.
int mid = (low + high + 1) / 2;
object secondHalfLabel = new object();
// Emit a conditional branch to the second half
// before emitting the first half buckets.
ConstantValue pivotConstant = switchBuckets[mid - 1].EndConstant;
// if(key > midLabelConstant)
// goto secondHalfLabel;
this.EmitCondBranchForSwitch(
_keyTypeCode.IsUnsigned() ? ILOpCode.Bgt_un : ILOpCode.Bgt,
pivotConstant,
secondHalfLabel);
// Emit first half
this.EmitSwitchBuckets(switchBuckets, low, mid - 1);
// NOTE: Typically marking a synthetic label needs a hidden sequence point.
// NOTE: Otherwise if you step (F11) to this label debugger may highlight previous (lexically) statement.
// NOTE: We do not need a hidden point in this implementation since we do not interleave jump table
// NOTE: and cases so the "previous" statement will always be "switch".
// secondHalfLabel:
_builder.MarkLabel(secondHalfLabel);
// Emit second half
this.EmitSwitchBuckets(switchBuckets, mid, high);
}
private void EmitSwitchBucket(SwitchBucket switchBucket, object bucketFallThroughLabel)
{
if (switchBucket.LabelsCount == 1)
{
var c = switchBucket[0];
// if(key == constant)
// goto caseLabel;
ConstantValue constant = c.Key;
object caseLabel = c.Value;
this.EmitEqBranchForSwitch(constant, caseLabel);
}
else
{
if (switchBucket.IsDegenerate)
{
EmitRangeCheckedBranch(switchBucket.StartConstant, switchBucket.EndConstant, switchBucket[0].Value);
}
else
{
// Emit key normalized to startConstant (i.e. key - startConstant)
this.EmitNormalizedSwitchKey(switchBucket.StartConstant, switchBucket.EndConstant, bucketFallThroughLabel);
// Create the labels array for emitting a switch instruction for the bucket
object[] labels = this.CreateBucketLabels(switchBucket);
// switch (N, label1, label2... labelN)
// Emit the switch instruction
_builder.EmitSwitch(labels);
}
}
// goto fallThroughLabel;
_builder.EmitBranch(ILOpCode.Br, bucketFallThroughLabel);
}
private object[] CreateBucketLabels(SwitchBucket switchBucket)
{
// switch (N, t1, t2... tN)
// IL ==> ILOpCode.Switch < unsigned int32 > < int32 >... < int32 >
// For example: given a switch bucket [1, 3, 5] and FallThrough Label,
// we create the following labels array:
// { CaseLabel1, FallThrough, CaseLabel3, FallThrough, CaseLabel5 }
ConstantValue startConstant = switchBucket.StartConstant;
bool hasNegativeCaseLabels = startConstant.IsNegativeNumeric;
int nextCaseIndex = 0;
ulong nextCaseLabelNormalizedValue = 0;
ulong bucketSize = switchBucket.BucketSize;
object[] labels = new object[bucketSize];
for (ulong i = 0; i < bucketSize; ++i)
{
if (i == nextCaseLabelNormalizedValue)
{
labels[i] = switchBucket[nextCaseIndex].Value;
nextCaseIndex++;
if (nextCaseIndex >= switchBucket.LabelsCount)
{
Debug.Assert(i == bucketSize - 1);
break;
}
ConstantValue caseLabelConstant = switchBucket[nextCaseIndex].Key;
if (hasNegativeCaseLabels)
{
var nextCaseLabelValue = caseLabelConstant.Int64Value;
Debug.Assert(nextCaseLabelValue > startConstant.Int64Value);
nextCaseLabelNormalizedValue = (ulong)(nextCaseLabelValue - startConstant.Int64Value);
}
else
{
var nextCaseLabelValue = caseLabelConstant.UInt64Value;
Debug.Assert(nextCaseLabelValue > startConstant.UInt64Value);
nextCaseLabelNormalizedValue = nextCaseLabelValue - startConstant.UInt64Value;
}
continue;
}
labels[i] = _fallThroughLabel;
}
Debug.Assert(nextCaseIndex >= switchBucket.LabelsCount);
return labels;
}
#endregion
#region "Helper emit methods"
private void EmitCondBranchForSwitch(ILOpCode branchCode, ConstantValue constant, object targetLabel)
{
Debug.Assert(branchCode.IsBranch());
RoslynDebug.Assert(constant != null &&
SwitchConstantValueHelper.IsValidSwitchCaseLabelConstant(constant));
RoslynDebug.Assert(targetLabel != null);
// ldloc key
// ldc constant
// branch branchCode targetLabel
_builder.EmitLoad(_key);
_builder.EmitConstantValue(constant);
_builder.EmitBranch(branchCode, targetLabel, GetReverseBranchCode(branchCode));
}
private void EmitEqBranchForSwitch(ConstantValue constant, object targetLabel)
{
RoslynDebug.Assert(constant != null &&
SwitchConstantValueHelper.IsValidSwitchCaseLabelConstant(constant));
RoslynDebug.Assert(targetLabel != null);
_builder.EmitLoad(_key);
if (constant.IsDefaultValue)
{
// ldloc key
// brfalse targetLabel
_builder.EmitBranch(ILOpCode.Brfalse, targetLabel);
}
else
{
_builder.EmitConstantValue(constant);
_builder.EmitBranch(ILOpCode.Beq, targetLabel);
}
}
private void EmitRangeCheckedBranch(ConstantValue startConstant, ConstantValue endConstant, object targetLabel)
{
_builder.EmitLoad(_key);
// Normalize the key to 0 if needed
// Emit: ldc constant
// sub
if (!startConstant.IsDefaultValue)
{
_builder.EmitConstantValue(startConstant);
_builder.EmitOpCode(ILOpCode.Sub);
}
if (_keyTypeCode.Is64BitIntegral())
{
_builder.EmitLongConstant(endConstant.Int64Value - startConstant.Int64Value);
}
else
{
int Int32Value(ConstantValue value)
{
// ConstantValue does not correctly convert byte and ushort values to int.
// It sign extends them rather than padding them. We compensate for that here.
// See also https://github.com/dotnet/roslyn/issues/18579
switch (value.Discriminator)
{
case ConstantValueTypeDiscriminator.Byte: return value.ByteValue;
case ConstantValueTypeDiscriminator.UInt16: return value.UInt16Value;
default: return value.Int32Value;
}
}
_builder.EmitIntConstant(Int32Value(endConstant) - Int32Value(startConstant));
}
_builder.EmitBranch(ILOpCode.Ble_un, targetLabel, ILOpCode.Bgt_un);
}
private static ILOpCode GetReverseBranchCode(ILOpCode branchCode)
{
switch (branchCode)
{
case ILOpCode.Beq:
return ILOpCode.Bne_un;
case ILOpCode.Blt:
return ILOpCode.Bge;
case ILOpCode.Blt_un:
return ILOpCode.Bge_un;
case ILOpCode.Bgt:
return ILOpCode.Ble;
case ILOpCode.Bgt_un:
return ILOpCode.Ble_un;
default:
throw ExceptionUtilities.UnexpectedValue(branchCode);
}
}
private void EmitNormalizedSwitchKey(ConstantValue startConstant, ConstantValue endConstant, object bucketFallThroughLabel)
{
_builder.EmitLoad(_key);
// Normalize the key to 0 if needed
// Emit: ldc constant
// sub
if (!startConstant.IsDefaultValue)
{
_builder.EmitConstantValue(startConstant);
_builder.EmitOpCode(ILOpCode.Sub);
}
// range-check normalized value if needed
EmitRangeCheckIfNeeded(startConstant, endConstant, bucketFallThroughLabel);
// truncate key to 32bit
_builder.EmitNumericConversion(_keyTypeCode, Microsoft.Cci.PrimitiveTypeCode.UInt32, false);
}
private void EmitRangeCheckIfNeeded(ConstantValue startConstant, ConstantValue endConstant, object bucketFallThroughLabel)
{
// switch treats key as an unsigned int.
// this ensures that normalization does not introduce [over|under]flows issues with 32bit or shorter keys.
// 64bit values, however must be checked before 32bit truncation happens.
if (_keyTypeCode.Is64BitIntegral())
{
// Dup(normalized);
// if ((ulong)(normalized) > (ulong)(endConstant - startConstant))
// {
// // not going to use it in the switch
// Pop(normalized);
// goto bucketFallThroughLabel;
// }
var inRangeLabel = new object();
_builder.EmitOpCode(ILOpCode.Dup);
_builder.EmitLongConstant(endConstant.Int64Value - startConstant.Int64Value);
_builder.EmitBranch(ILOpCode.Ble_un, inRangeLabel, ILOpCode.Bgt_un);
_builder.EmitOpCode(ILOpCode.Pop);
_builder.EmitBranch(ILOpCode.Br, bucketFallThroughLabel);
// If we get to inRangeLabel, we should have key on stack, adjust for that.
// builder cannot infer this since it has not seen all branches,
// but it will verify that our Adjustment is valid when more branches are known.
_builder.AdjustStack(+1);
_builder.MarkLabel(inRangeLabel);
}
}
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection.Metadata;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeGen
{
/// <summary>
/// Class for emitting the switch jump table for switch statements with integral governing type
/// </summary>
internal partial struct SwitchIntegralJumpTableEmitter
{
private readonly ILBuilder _builder;
/// <summary>
/// Switch key for the jump table
/// </summary>
private readonly LocalOrParameter _key;
/// <summary>
/// Primitive type of the switch key
/// </summary>
private readonly Cci.PrimitiveTypeCode _keyTypeCode;
/// <summary>
/// Fall through label for the jump table
/// </summary>
private readonly object _fallThroughLabel;
/// <summary>
/// Integral case labels sorted and indexed by their ConstantValue
/// </summary>
private readonly ImmutableArray<KeyValuePair<ConstantValue, object>> _sortedCaseLabels;
// threshold at which binary search stops partitioning.
// if a search leaf has less than LinearSearchThreshold buckets
// we just go through buckets linearly.
// We chose 3 here because it is where number of branches to reach fall-through
// is the same for linear and binary search.
private const int LinearSearchThreshold = 3;
internal SwitchIntegralJumpTableEmitter(
ILBuilder builder,
KeyValuePair<ConstantValue, object>[] caseLabels,
object fallThroughLabel,
Cci.PrimitiveTypeCode keyTypeCode,
LocalOrParameter key)
{
_builder = builder;
_key = key;
_keyTypeCode = keyTypeCode;
_fallThroughLabel = fallThroughLabel;
// Sort the switch case labels, see comments below for more details.
Debug.Assert(caseLabels.Length > 0);
Array.Sort(caseLabels, CompareIntegralSwitchLabels);
_sortedCaseLabels = ImmutableArray.Create(caseLabels);
}
internal void EmitJumpTable()
{
// For emitting the switch statement (integral governing type) jump table with a non-constant
// switch expression, we can use a naive approach and generate a single big MSIL switch instruction
// with all the case labels and fall through label. However, this approach can be optimized
// to improve both the code size and speed using the following optimization steps:
// a) Sort the switch case labels based on their constant values.
// b) Divide the sorted switch labels into buckets with good enough density (>50%). For example:
// switch(..)
// {
// case 1:
// case 100:
// break;
// case 2:
// case 4:
// break;
// case 200:
// case 201:
// case 202:
// break;
// }
// can be divided into 3 buckets: (1, 2, 4) (100) (200, 201, 202).
// We do this bucketing so that we have reasonable size jump tables for generated switch instructions.
// c) After bucketing, generate code to perform a binary search on these buckets array,
// emitting conditional jumps if current bucket sub-array has more than one bucket and
// emitting the switch instruction when we are down to a single bucket in the sub-array.
// (a) Sort switch labels: This was done in the constructor
Debug.Assert(!_sortedCaseLabels.IsEmpty);
var sortedCaseLabels = _sortedCaseLabels;
int endLabelIndex = sortedCaseLabels.Length - 1;
int startLabelIndex;
// Check for a label with ConstantValue.Null.
// Sorting ensures that if we do have one, it will be
// the first label in the sorted list.
if (sortedCaseLabels[0].Key != ConstantValue.Null)
{
startLabelIndex = 0;
}
else
{
// Skip null label for emitting switch table header.
// We should have inserted a conditional branch to 'null' label during rewriting.
// See LocalRewriter.MakeSwitchStatementWithNullableExpression
startLabelIndex = 1;
}
if (startLabelIndex <= endLabelIndex)
{
// We have at least one non-null case label, emit jump table
// (b) Generate switch buckets
ImmutableArray<SwitchBucket> switchBuckets = this.GenerateSwitchBuckets(startLabelIndex, endLabelIndex);
// (c) Emit switch buckets
this.EmitSwitchBuckets(switchBuckets, 0, switchBuckets.Length - 1);
}
else
{
_builder.EmitBranch(ILOpCode.Br, _fallThroughLabel);
}
}
#region "Sorting switch labels"
private static int CompareIntegralSwitchLabels(KeyValuePair<ConstantValue, object> first, KeyValuePair<ConstantValue, object> second)
{
ConstantValue firstConstant = first.Key;
ConstantValue secondConstant = second.Key;
RoslynDebug.Assert(firstConstant != null);
Debug.Assert(SwitchConstantValueHelper.IsValidSwitchCaseLabelConstant(firstConstant)
&& !firstConstant.IsString);
RoslynDebug.Assert(secondConstant != null);
Debug.Assert(SwitchConstantValueHelper.IsValidSwitchCaseLabelConstant(secondConstant)
&& !secondConstant.IsString);
return SwitchConstantValueHelper.CompareSwitchCaseLabelConstants(firstConstant, secondConstant);
}
#endregion
#region "Switch bucketing methods"
// Bucketing algorithm:
// Start with empty stack of buckets.
// While there are still labels
// If bucket from remaining labels is dense
// Create a newBucket from remaining labels
// Else
// Create a singleton newBucket from the next label
// While the top bucket on stack can be merged with newBucket into a dense bucket
// merge top bucket on stack into newBucket, and pop bucket from stack
// End While
// Push newBucket on stack
// End While
private ImmutableArray<SwitchBucket> GenerateSwitchBuckets(int startLabelIndex, int endLabelIndex)
{
Debug.Assert(startLabelIndex >= 0 && startLabelIndex <= endLabelIndex);
Debug.Assert(_sortedCaseLabels.Length > endLabelIndex);
// Start with empty stack of buckets.
var switchBucketsStack = ArrayBuilder<SwitchBucket>.GetInstance();
int curStartLabelIndex = startLabelIndex;
// While there are still labels
while (curStartLabelIndex <= endLabelIndex)
{
SwitchBucket newBucket = CreateNextBucket(curStartLabelIndex, endLabelIndex);
// While the top bucket on stack can be merged with newBucket into a dense bucket
// merge top bucket on stack into newBucket, and pop bucket from stack
// End While
while (!switchBucketsStack.IsEmpty())
{
// get the bucket at top of the stack
SwitchBucket prevBucket = switchBucketsStack.Peek();
if (newBucket.TryMergeWith(prevBucket))
{
// pop the previous bucket from the stack
switchBucketsStack.Pop();
}
else
{
// merge failed
break;
}
}
// Push newBucket on stack
switchBucketsStack.Push(newBucket);
// update curStartLabelIndex
curStartLabelIndex++;
}
Debug.Assert(!switchBucketsStack.IsEmpty());
// crumble leaf buckets into degenerate buckets where possible
var crumbled = ArrayBuilder<SwitchBucket>.GetInstance();
foreach (var uncrumbled in switchBucketsStack)
{
var degenerateSplit = uncrumbled.DegenerateBucketSplit;
switch (degenerateSplit)
{
case -1:
// cannot be split
crumbled.Add(uncrumbled);
break;
case 0:
// already degenerate
crumbled.Add(new SwitchBucket(_sortedCaseLabels, uncrumbled.StartLabelIndex, uncrumbled.EndLabelIndex, isDegenerate: true));
break;
default:
// can split
crumbled.Add(new SwitchBucket(_sortedCaseLabels, uncrumbled.StartLabelIndex, degenerateSplit - 1, isDegenerate: true));
crumbled.Add(new SwitchBucket(_sortedCaseLabels, degenerateSplit, uncrumbled.EndLabelIndex, isDegenerate: true));
break;
}
}
switchBucketsStack.Free();
return crumbled.ToImmutableAndFree();
}
private SwitchBucket CreateNextBucket(int startLabelIndex, int endLabelIndex)
{
Debug.Assert(startLabelIndex >= 0 && startLabelIndex <= endLabelIndex);
return new SwitchBucket(_sortedCaseLabels, startLabelIndex);
}
#endregion
#region "Switch bucket emit methods"
private void EmitSwitchBucketsLinearLeaf(ImmutableArray<SwitchBucket> switchBuckets, int low, int high)
{
for (int i = low; i < high; i++)
{
var nextBucketLabel = new object();
this.EmitSwitchBucket(switchBuckets[i], nextBucketLabel);
// nextBucketLabel:
_builder.MarkLabel(nextBucketLabel);
}
this.EmitSwitchBucket(switchBuckets[high], _fallThroughLabel);
}
private void EmitSwitchBuckets(ImmutableArray<SwitchBucket> switchBuckets, int low, int high)
{
// if (high - low + 1 <= LinearSearchThreshold)
if (high - low < LinearSearchThreshold)
{
this.EmitSwitchBucketsLinearLeaf(switchBuckets, low, high);
return;
}
// This way (0 1 2 3) will produce a mid of 2 while
// (0 1 2) will produce a mid of 1
// Now, the first half is first to mid-1
// and the second half is mid to last.
int mid = (low + high + 1) / 2;
object secondHalfLabel = new object();
// Emit a conditional branch to the second half
// before emitting the first half buckets.
ConstantValue pivotConstant = switchBuckets[mid - 1].EndConstant;
// if(key > midLabelConstant)
// goto secondHalfLabel;
this.EmitCondBranchForSwitch(
_keyTypeCode.IsUnsigned() ? ILOpCode.Bgt_un : ILOpCode.Bgt,
pivotConstant,
secondHalfLabel);
// Emit first half
this.EmitSwitchBuckets(switchBuckets, low, mid - 1);
// NOTE: Typically marking a synthetic label needs a hidden sequence point.
// NOTE: Otherwise if you step (F11) to this label debugger may highlight previous (lexically) statement.
// NOTE: We do not need a hidden point in this implementation since we do not interleave jump table
// NOTE: and cases so the "previous" statement will always be "switch".
// secondHalfLabel:
_builder.MarkLabel(secondHalfLabel);
// Emit second half
this.EmitSwitchBuckets(switchBuckets, mid, high);
}
private void EmitSwitchBucket(SwitchBucket switchBucket, object bucketFallThroughLabel)
{
if (switchBucket.LabelsCount == 1)
{
var c = switchBucket[0];
// if(key == constant)
// goto caseLabel;
ConstantValue constant = c.Key;
object caseLabel = c.Value;
this.EmitEqBranchForSwitch(constant, caseLabel);
}
else
{
if (switchBucket.IsDegenerate)
{
EmitRangeCheckedBranch(switchBucket.StartConstant, switchBucket.EndConstant, switchBucket[0].Value);
}
else
{
// Emit key normalized to startConstant (i.e. key - startConstant)
this.EmitNormalizedSwitchKey(switchBucket.StartConstant, switchBucket.EndConstant, bucketFallThroughLabel);
// Create the labels array for emitting a switch instruction for the bucket
object[] labels = this.CreateBucketLabels(switchBucket);
// switch (N, label1, label2... labelN)
// Emit the switch instruction
_builder.EmitSwitch(labels);
}
}
// goto fallThroughLabel;
_builder.EmitBranch(ILOpCode.Br, bucketFallThroughLabel);
}
private object[] CreateBucketLabels(SwitchBucket switchBucket)
{
// switch (N, t1, t2... tN)
// IL ==> ILOpCode.Switch < unsigned int32 > < int32 >... < int32 >
// For example: given a switch bucket [1, 3, 5] and FallThrough Label,
// we create the following labels array:
// { CaseLabel1, FallThrough, CaseLabel3, FallThrough, CaseLabel5 }
ConstantValue startConstant = switchBucket.StartConstant;
bool hasNegativeCaseLabels = startConstant.IsNegativeNumeric;
int nextCaseIndex = 0;
ulong nextCaseLabelNormalizedValue = 0;
ulong bucketSize = switchBucket.BucketSize;
object[] labels = new object[bucketSize];
for (ulong i = 0; i < bucketSize; ++i)
{
if (i == nextCaseLabelNormalizedValue)
{
labels[i] = switchBucket[nextCaseIndex].Value;
nextCaseIndex++;
if (nextCaseIndex >= switchBucket.LabelsCount)
{
Debug.Assert(i == bucketSize - 1);
break;
}
ConstantValue caseLabelConstant = switchBucket[nextCaseIndex].Key;
if (hasNegativeCaseLabels)
{
var nextCaseLabelValue = caseLabelConstant.Int64Value;
Debug.Assert(nextCaseLabelValue > startConstant.Int64Value);
nextCaseLabelNormalizedValue = (ulong)(nextCaseLabelValue - startConstant.Int64Value);
}
else
{
var nextCaseLabelValue = caseLabelConstant.UInt64Value;
Debug.Assert(nextCaseLabelValue > startConstant.UInt64Value);
nextCaseLabelNormalizedValue = nextCaseLabelValue - startConstant.UInt64Value;
}
continue;
}
labels[i] = _fallThroughLabel;
}
Debug.Assert(nextCaseIndex >= switchBucket.LabelsCount);
return labels;
}
#endregion
#region "Helper emit methods"
private void EmitCondBranchForSwitch(ILOpCode branchCode, ConstantValue constant, object targetLabel)
{
Debug.Assert(branchCode.IsBranch());
RoslynDebug.Assert(constant != null &&
SwitchConstantValueHelper.IsValidSwitchCaseLabelConstant(constant));
RoslynDebug.Assert(targetLabel != null);
// ldloc key
// ldc constant
// branch branchCode targetLabel
_builder.EmitLoad(_key);
_builder.EmitConstantValue(constant);
_builder.EmitBranch(branchCode, targetLabel, GetReverseBranchCode(branchCode));
}
private void EmitEqBranchForSwitch(ConstantValue constant, object targetLabel)
{
RoslynDebug.Assert(constant != null &&
SwitchConstantValueHelper.IsValidSwitchCaseLabelConstant(constant));
RoslynDebug.Assert(targetLabel != null);
_builder.EmitLoad(_key);
if (constant.IsDefaultValue)
{
// ldloc key
// brfalse targetLabel
_builder.EmitBranch(ILOpCode.Brfalse, targetLabel);
}
else
{
_builder.EmitConstantValue(constant);
_builder.EmitBranch(ILOpCode.Beq, targetLabel);
}
}
private void EmitRangeCheckedBranch(ConstantValue startConstant, ConstantValue endConstant, object targetLabel)
{
_builder.EmitLoad(_key);
// Normalize the key to 0 if needed
// Emit: ldc constant
// sub
if (!startConstant.IsDefaultValue)
{
_builder.EmitConstantValue(startConstant);
_builder.EmitOpCode(ILOpCode.Sub);
}
if (_keyTypeCode.Is64BitIntegral())
{
_builder.EmitLongConstant(endConstant.Int64Value - startConstant.Int64Value);
}
else
{
int Int32Value(ConstantValue value)
{
// ConstantValue does not correctly convert byte and ushort values to int.
// It sign extends them rather than padding them. We compensate for that here.
// See also https://github.com/dotnet/roslyn/issues/18579
switch (value.Discriminator)
{
case ConstantValueTypeDiscriminator.Byte: return value.ByteValue;
case ConstantValueTypeDiscriminator.UInt16: return value.UInt16Value;
default: return value.Int32Value;
}
}
_builder.EmitIntConstant(Int32Value(endConstant) - Int32Value(startConstant));
}
_builder.EmitBranch(ILOpCode.Ble_un, targetLabel, ILOpCode.Bgt_un);
}
private static ILOpCode GetReverseBranchCode(ILOpCode branchCode)
{
switch (branchCode)
{
case ILOpCode.Beq:
return ILOpCode.Bne_un;
case ILOpCode.Blt:
return ILOpCode.Bge;
case ILOpCode.Blt_un:
return ILOpCode.Bge_un;
case ILOpCode.Bgt:
return ILOpCode.Ble;
case ILOpCode.Bgt_un:
return ILOpCode.Ble_un;
default:
throw ExceptionUtilities.UnexpectedValue(branchCode);
}
}
private void EmitNormalizedSwitchKey(ConstantValue startConstant, ConstantValue endConstant, object bucketFallThroughLabel)
{
_builder.EmitLoad(_key);
// Normalize the key to 0 if needed
// Emit: ldc constant
// sub
if (!startConstant.IsDefaultValue)
{
_builder.EmitConstantValue(startConstant);
_builder.EmitOpCode(ILOpCode.Sub);
}
// range-check normalized value if needed
EmitRangeCheckIfNeeded(startConstant, endConstant, bucketFallThroughLabel);
// truncate key to 32bit
_builder.EmitNumericConversion(_keyTypeCode, Microsoft.Cci.PrimitiveTypeCode.UInt32, false);
}
private void EmitRangeCheckIfNeeded(ConstantValue startConstant, ConstantValue endConstant, object bucketFallThroughLabel)
{
// switch treats key as an unsigned int.
// this ensures that normalization does not introduce [over|under]flows issues with 32bit or shorter keys.
// 64bit values, however must be checked before 32bit truncation happens.
if (_keyTypeCode.Is64BitIntegral())
{
// Dup(normalized);
// if ((ulong)(normalized) > (ulong)(endConstant - startConstant))
// {
// // not going to use it in the switch
// Pop(normalized);
// goto bucketFallThroughLabel;
// }
var inRangeLabel = new object();
_builder.EmitOpCode(ILOpCode.Dup);
_builder.EmitLongConstant(endConstant.Int64Value - startConstant.Int64Value);
_builder.EmitBranch(ILOpCode.Ble_un, inRangeLabel, ILOpCode.Bgt_un);
_builder.EmitOpCode(ILOpCode.Pop);
_builder.EmitBranch(ILOpCode.Br, bucketFallThroughLabel);
// If we get to inRangeLabel, we should have key on stack, adjust for that.
// builder cannot infer this since it has not seen all branches,
// but it will verify that our Adjustment is valid when more branches are known.
_builder.AdjustStack(+1);
_builder.MarkLabel(inRangeLabel);
}
}
#endregion
}
}
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/CSharpTest/AddUsing/AddUsingTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Remote.Testing;
using Microsoft.CodeAnalysis.Tags;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
using static Roslyn.Test.Utilities.TestMetadata;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddUsing
{
[Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public partial class AddUsingTests : AbstractAddUsingTests
{
public AddUsingTests(ITestOutputHelper logger)
: base(logger)
{
}
[Theory]
[CombinatorialData]
public async Task TestTypeFromMultipleNamespaces1(TestHost testHost)
{
await TestAsync(
@"class Class
{
[|IDictionary|] Method()
{
Goo();
}
}",
@"using System.Collections;
class Class
{
IDictionary Method()
{
Goo();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestTypeFromMultipleNamespaces1_FileScopedNamespace_Outer(TestHost testHost)
{
await TestAsync(
@"
namespace N;
class Class
{
[|IDictionary|] Method()
{
Goo();
}
}",
@"
using System.Collections;
namespace N;
class Class
{
IDictionary Method()
{
Goo();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestTypeFromMultipleNamespaces1_FileScopedNamespace_Inner(TestHost testHost)
{
await TestAsync(
@"
namespace N;
using System;
class Class
{
[|IDictionary|] Method()
{
Goo();
}
}",
@"
namespace N;
using System;
using System.Collections;
class Class
{
IDictionary Method()
{
Goo();
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(11241, "https://github.com/dotnet/roslyn/issues/11241")]
public async Task TestAddImportWithCaseChange(TestHost testHost)
{
await TestAsync(
@"namespace N1
{
public class TextBox
{
}
}
class Class1 : [|Textbox|]
{
}",
@"using N1;
namespace N1
{
public class TextBox
{
}
}
class Class1 : TextBox
{
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestTypeFromMultipleNamespaces2(TestHost testHost)
{
await TestAsync(
@"class Class
{
[|IDictionary|] Method()
{
Goo();
}
}",
@"using System.Collections.Generic;
class Class
{
IDictionary Method()
{
Goo();
}
}",
testHost, index: 1);
}
[Theory]
[CombinatorialData]
public async Task TestGenericWithNoArgs(TestHost testHost)
{
await TestAsync(
@"class Class
{
[|List|] Method()
{
Goo();
}
}",
@"using System.Collections.Generic;
class Class
{
List Method()
{
Goo();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestGenericWithCorrectArgs(TestHost testHost)
{
await TestAsync(
@"class Class
{
[|List<int>|] Method()
{
Goo();
}
}",
@"using System.Collections.Generic;
class Class
{
List<int> Method()
{
Goo();
}
}", testHost);
}
[Fact]
public async Task TestGenericWithWrongArgs1()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|List<int, string, bool>|] Method()
{
Goo();
}
}");
}
[Fact]
public async Task TestGenericWithWrongArgs2()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|List<int, string>|] Method()
{
Goo();
}
}");
}
[Theory]
[CombinatorialData]
public async Task TestGenericInLocalDeclaration(TestHost testHost)
{
await TestAsync(
@"class Class
{
void Goo()
{
[|List<int>|] a = new List<int>();
}
}",
@"using System.Collections.Generic;
class Class
{
void Goo()
{
List<int> a = new List<int>();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestGenericItemType(TestHost testHost)
{
await TestAsync(
@"using System.Collections.Generic;
class Class
{
List<[|Int32|]> l;
}",
@"using System;
using System.Collections.Generic;
class Class
{
List<Int32> l;
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestGenerateWithExistingUsings(TestHost testHost)
{
await TestAsync(
@"using System;
class Class
{
[|List<int>|] Method()
{
Goo();
}
}",
@"using System;
using System.Collections.Generic;
class Class
{
List<int> Method()
{
Goo();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestGenerateInNamespace(TestHost testHost)
{
await TestAsync(
@"namespace N
{
class Class
{
[|List<int>|] Method()
{
Goo();
}
}
}",
@"using System.Collections.Generic;
namespace N
{
class Class
{
List<int> Method()
{
Goo();
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestGenerateInNamespaceWithUsings(TestHost testHost)
{
await TestAsync(
@"namespace N
{
using System;
class Class
{
[|List<int>|] Method()
{
Goo();
}
}
}",
@"namespace N
{
using System;
using System.Collections.Generic;
class Class
{
List<int> Method()
{
Goo();
}
}
}", testHost);
}
[Fact]
public async Task TestExistingUsing_ActionCount()
{
await TestActionCountAsync(
@"using System.Collections.Generic;
class Class
{
[|IDictionary|] Method()
{
Goo();
}
}",
count: 1);
}
[Theory]
[CombinatorialData]
public async Task TestExistingUsing(TestHost testHost)
{
await TestAsync(
@"using System.Collections.Generic;
class Class
{
[|IDictionary|] Method()
{
Goo();
}
}",
@"using System.Collections;
using System.Collections.Generic;
class Class
{
IDictionary Method()
{
Goo();
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(541730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541730")]
public async Task TestAddUsingForGenericExtensionMethod(TestHost testHost)
{
await TestAsync(
@"using System.Collections.Generic;
class Class
{
void Method(IList<int> args)
{
args.[|Where|]() }
}",
@"using System.Collections.Generic;
using System.Linq;
class Class
{
void Method(IList<int> args)
{
args.Where() }
}", testHost);
}
[Fact]
[WorkItem(541730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541730")]
public async Task TestAddUsingForNormalExtensionMethod()
{
await TestAsync(
@"class Class
{
void Method(Class args)
{
args.[|Where|]() }
}
namespace N
{
static class E
{
public static void Where(this Class c)
{
}
}
}",
@"using N;
class Class
{
void Method(Class args)
{
args.Where() }
}
namespace N
{
static class E
{
public static void Where(this Class c)
{
}
}
}",
parseOptions: Options.Regular);
}
[Theory]
[CombinatorialData]
public async Task TestOnEnum(TestHost testHost)
{
await TestAsync(
@"class Class
{
void Goo()
{
var a = [|Colors|].Red;
}
}
namespace A
{
enum Colors
{
Red,
Green,
Blue
}
}",
@"using A;
class Class
{
void Goo()
{
var a = Colors.Red;
}
}
namespace A
{
enum Colors
{
Red,
Green,
Blue
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestOnClassInheritance(TestHost testHost)
{
await TestAsync(
@"class Class : [|Class2|]
{
}
namespace A
{
class Class2
{
}
}",
@"using A;
class Class : Class2
{
}
namespace A
{
class Class2
{
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestOnImplementedInterface(TestHost testHost)
{
await TestAsync(
@"class Class : [|IGoo|]
{
}
namespace A
{
interface IGoo
{
}
}",
@"using A;
class Class : IGoo
{
}
namespace A
{
interface IGoo
{
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAllInBaseList(TestHost testHost)
{
await TestAsync(
@"class Class : [|IGoo|], Class2
{
}
namespace A
{
class Class2
{
}
}
namespace B
{
interface IGoo
{
}
}",
@"using B;
class Class : IGoo, Class2
{
}
namespace A
{
class Class2
{
}
}
namespace B
{
interface IGoo
{
}
}", testHost);
await TestAsync(
@"using B;
class Class : IGoo, [|Class2|]
{
}
namespace A
{
class Class2
{
}
}
namespace B
{
interface IGoo
{
}
}",
@"using A;
using B;
class Class : IGoo, Class2
{
}
namespace A
{
class Class2
{
}
}
namespace B
{
interface IGoo
{
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAttributeUnexpanded(TestHost testHost)
{
await TestAsync(
@"[[|Obsolete|]]
class Class
{
}",
@"using System;
[Obsolete]
class Class
{
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAttributeExpanded(TestHost testHost)
{
await TestAsync(
@"[[|ObsoleteAttribute|]]
class Class
{
}",
@"using System;
[ObsoleteAttribute]
class Class
{
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(538018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538018")]
public async Task TestAfterNew(TestHost testHost)
{
await TestAsync(
@"class Class
{
void Goo()
{
List<int> l;
l = new [|List<int>|]();
}
}",
@"using System.Collections.Generic;
class Class
{
void Goo()
{
List<int> l;
l = new List<int>();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestArgumentsInMethodCall(TestHost testHost)
{
await TestAsync(
@"class Class
{
void Test()
{
Console.WriteLine([|DateTime|].Today);
}
}",
@"using System;
class Class
{
void Test()
{
Console.WriteLine(DateTime.Today);
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestCallSiteArgs(TestHost testHost)
{
await TestAsync(
@"class Class
{
void Test([|DateTime|] dt)
{
}
}",
@"using System;
class Class
{
void Test(DateTime dt)
{
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestUsePartialClass(TestHost testHost)
{
await TestAsync(
@"namespace A
{
public class Class
{
[|PClass|] c;
}
}
namespace B
{
public partial class PClass
{
}
}",
@"using B;
namespace A
{
public class Class
{
PClass c;
}
}
namespace B
{
public partial class PClass
{
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestGenericClassInNestedNamespace(TestHost testHost)
{
await TestAsync(
@"namespace A
{
namespace B
{
class GenericClass<T>
{
}
}
}
namespace C
{
class Class
{
[|GenericClass<int>|] c;
}
}",
@"using A.B;
namespace A
{
namespace B
{
class GenericClass<T>
{
}
}
}
namespace C
{
class Class
{
GenericClass<int> c;
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(541730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541730")]
public async Task TestExtensionMethods(TestHost testHost)
{
await TestAsync(
@"using System.Collections.Generic;
class Goo
{
void Bar()
{
var values = new List<int>();
values.[|Where|](i => i > 1);
}
}",
@"using System.Collections.Generic;
using System.Linq;
class Goo
{
void Bar()
{
var values = new List<int>();
values.Where(i => i > 1);
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(541730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541730")]
public async Task TestQueryPatterns(TestHost testHost)
{
await TestAsync(
@"using System.Collections.Generic;
class Goo
{
void Bar()
{
var values = new List<int>();
var q = [|from v in values
where v > 1
select v + 10|];
}
}",
@"using System.Collections.Generic;
using System.Linq;
class Goo
{
void Bar()
{
var values = new List<int>();
var q = from v in values
where v > 1
select v + 10;
}
}", testHost);
}
// Tests for Insertion Order
[Theory]
[CombinatorialData]
public async Task TestSimplePresortedUsings1(TestHost testHost)
{
await TestAsync(
@"using B;
using C;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace D
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using B;
using C;
using D;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace D
{
class Goo
{
public static void Bar()
{
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimplePresortedUsings2(TestHost testHost)
{
await TestAsync(
@"using B;
using C;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using A;
using B;
using C;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleUnsortedUsings1(TestHost testHost)
{
await TestAsync(
@"using C;
using B;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using C;
using B;
using A;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleUnsortedUsings2(TestHost testHost)
{
await TestAsync(
@"using D;
using B;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace C
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using D;
using B;
using C;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace C
{
class Goo
{
public static void Bar()
{
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestMultiplePresortedUsings1(TestHost testHost)
{
await TestAsync(
@"using B.X;
using B.Y;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace B
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using B;
using B.X;
using B.Y;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace B
{
class Goo
{
public static void Bar()
{
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestMultiplePresortedUsings2(TestHost testHost)
{
await TestAsync(
@"using B.X;
using B.Y;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace B.A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using B.A;
using B.X;
using B.Y;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace B.A
{
class Goo
{
public static void Bar()
{
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestMultiplePresortedUsings3(TestHost testHost)
{
await TestAsync(
@"using B.X;
using B.Y;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace B
{
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}
}",
@"using B.A;
using B.X;
using B.Y;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace B
{
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestMultipleUnsortedUsings1(TestHost testHost)
{
await TestAsync(
@"using B.Y;
using B.X;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace B
{
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}
}",
@"using B.Y;
using B.X;
using B.A;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace B
{
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestMultipleUnsortedUsings2(TestHost testHost)
{
await TestAsync(
@"using B.Y;
using B.X;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace B
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using B.Y;
using B.X;
using B;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace B
{
class Goo
{
public static void Bar()
{
}
}
}", testHost);
}
// System on top cases
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemSortedUsings1(TestHost testHost)
{
await TestAsync(
@"using System;
using B;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using System;
using A;
using B;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemSortedUsings2(TestHost testHost)
{
await TestAsync(
@"using System;
using System.Collections.Generic;
using B;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using System;
using System.Collections.Generic;
using A;
using B;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemSortedUsings3(TestHost testHost)
{
await TestAsync(
@"using A;
using B;
class Class
{
void Method()
{
[|Console|].Write(1);
}
}",
@"using System;
using A;
using B;
class Class
{
void Method()
{
Console.Write(1);
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemUnsortedUsings1(TestHost testHost)
{
await TestAsync(
@"
using C;
using B;
using System;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"
using C;
using B;
using System;
using A;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemUnsortedUsings2(TestHost testHost)
{
await TestAsync(
@"using System.Collections.Generic;
using System;
using B;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using System.Collections.Generic;
using System;
using B;
using A;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemUnsortedUsings3(TestHost testHost)
{
await TestAsync(
@"using B;
using A;
class Class
{
void Method()
{
[|Console|].Write(1);
}
}",
@"using B;
using A;
using System;
class Class
{
void Method()
{
Console.Write(1);
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleBogusSystemUsings1(TestHost testHost)
{
await TestAsync(
@"using A.System;
class Class
{
void Method()
{
[|Console|].Write(1);
}
}",
@"using System;
using A.System;
class Class
{
void Method()
{
Console.Write(1);
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleBogusSystemUsings2(TestHost testHost)
{
await TestAsync(
@"using System.System;
class Class
{
void Method()
{
[|Console|].Write(1);
}
}",
@"using System;
using System.System;
class Class
{
void Method()
{
Console.Write(1);
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestUsingsWithComments(TestHost testHost)
{
await TestAsync(
@"using System./*...*/.Collections.Generic;
class Class
{
void Method()
{
[|Console|].Write(1);
}
}",
@"using System;
using System./*...*/.Collections.Generic;
class Class
{
void Method()
{
Console.Write(1);
}
}",
testHost);
}
// System Not on top cases
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemUnsortedUsings4(TestHost testHost)
{
await TestAsync(
@"
using C;
using System;
using B;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"
using C;
using System;
using B;
using A;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemSortedUsings5(TestHost testHost)
{
await TestAsync(
@"using B;
using System;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using A;
using B;
using System;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemSortedUsings4(TestHost testHost)
{
await TestAsync(
@"using A;
using B;
class Class
{
void Method()
{
[|Console|].Write(1);
}
}",
@"using A;
using B;
using System;
class Class
{
void Method()
{
Console.Write(1);
}
}",
testHost, options: Option(GenerationOptions.PlaceSystemNamespaceFirst, false));
}
[Fact]
[WorkItem(538136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538136")]
[WorkItem(538763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538763")]
public async Task TestAddUsingForNamespace()
{
await TestMissingInRegularAndScriptAsync(
@"namespace A
{
class Class
{
[|C|].Test t;
}
}
namespace B
{
namespace C
{
class Test
{
}
}
}");
}
[Theory]
[CombinatorialData]
[WorkItem(538220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538220")]
public async Task TestAddUsingForFieldWithFormatting(TestHost testHost)
{
await TestAsync(
@"class C { [|DateTime|] t; }",
@"using System;
class C { DateTime t; }", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(539657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539657")]
public async Task BugFix5688(TestHost testHost)
{
await TestAsync(
@"class Program { static void Main ( string [ ] args ) { [|Console|] . Out . NewLine = ""\r\n\r\n"" ; } } ",
@"using System;
class Program { static void Main ( string [ ] args ) { Console . Out . NewLine = ""\r\n\r\n"" ; } } ", testHost);
}
[Fact]
[WorkItem(539853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539853")]
public async Task BugFix5950()
{
await TestAsync(
@"using System.Console; WriteLine([|Expression|].Constant(123));",
@"using System.Console;
using System.Linq.Expressions;
WriteLine(Expression.Constant(123));",
parseOptions: GetScriptOptions());
}
[Theory]
[CombinatorialData]
[WorkItem(540339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540339")]
public async Task TestAddAfterDefineDirective1(TestHost testHost)
{
await TestAsync(
@"#define goo
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"#define goo
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(540339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540339")]
public async Task TestAddAfterDefineDirective2(TestHost testHost)
{
await TestAsync(
@"#define goo
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"#define goo
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddAfterDefineDirective3(TestHost testHost)
{
await TestAsync(
@"#define goo
/// Goo
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"#define goo
using System;
/// Goo
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddAfterDefineDirective4(TestHost testHost)
{
await TestAsync(
@"#define goo
// Goo
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"#define goo
// Goo
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddAfterExistingBanner(TestHost testHost)
{
await TestAsync(
@"// Banner
// Banner
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"// Banner
// Banner
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddAfterExternAlias1(TestHost testHost)
{
await TestAsync(
@"#define goo
extern alias Goo;
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"#define goo
extern alias Goo;
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddAfterExternAlias2(TestHost testHost)
{
await TestAsync(
@"#define goo
extern alias Goo;
using System.Collections;
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"#define goo
extern alias Goo;
using System;
using System.Collections;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}", testHost);
}
[Fact]
public async Task TestWithReferenceDirective()
{
var resolver = new TestMetadataReferenceResolver(assemblyNames: new Dictionary<string, PortableExecutableReference>()
{
{ "exprs", AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemCore).GetReference() }
});
await TestAsync(
@"#r ""exprs""
[|Expression|]",
@"#r ""exprs""
using System.Linq.Expressions;
Expression",
GetScriptOptions(),
TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver));
}
[Theory]
[CombinatorialData]
[WorkItem(542643, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542643")]
public async Task TestAssemblyAttribute(TestHost testHost)
{
await TestAsync(
@"[assembly: [|InternalsVisibleTo|](""Project"")]",
@"using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo(""Project"")]", testHost);
}
[Fact]
public async Task TestDoNotAddIntoHiddenRegion()
{
await TestMissingInRegularAndScriptAsync(
@"#line hidden
using System.Collections.Generic;
#line default
class Program
{
void Main()
{
[|DateTime|] d;
}
}");
}
[Theory]
[CombinatorialData]
public async Task TestAddToVisibleRegion(TestHost testHost)
{
await TestAsync(
@"#line default
using System.Collections.Generic;
#line hidden
class Program
{
void Main()
{
#line default
[|DateTime|] d;
#line hidden
}
}
#line default",
@"#line default
using System;
using System.Collections.Generic;
#line hidden
class Program
{
void Main()
{
#line default
DateTime d;
#line hidden
}
}
#line default", testHost);
}
[Fact]
[WorkItem(545248, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545248")]
public async Task TestVenusGeneration1()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void Goo()
{
#line 1 ""Default.aspx""
using (new [|StreamReader|]())
{
#line default
#line hidden
}
}");
}
[Fact]
[WorkItem(545774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545774")]
public async Task TestAttribute_ActionCount()
{
var input = @"[ assembly : [|Guid|] ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ";
await TestActionCountAsync(input, 2);
}
[Theory]
[CombinatorialData]
[WorkItem(545774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545774")]
public async Task TestAttribute(TestHost testHost)
{
var input = @"[ assembly : [|Guid|] ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ";
await TestAsync(
input,
@"using System.Runtime.InteropServices;
[ assembly : Guid ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ", testHost);
}
[Fact]
[WorkItem(546833, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546833")]
public async Task TestNotOnOverloadResolutionError()
{
await TestMissingInRegularAndScriptAsync(
@"namespace ConsoleApplication1
{
class Program
{
void Main()
{
var test = new [|Test|]("""");
}
}
class Test
{
}
}");
}
[Theory]
[CombinatorialData]
[WorkItem(17020, "DevDiv_Projects/Roslyn")]
public async Task TestAddUsingForGenericArgument(TestHost testHost)
{
await TestAsync(
@"namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
var inArgument = new InArgument<[|IEnumerable<int>|]>(new int[] { 1, 2, 3 });
}
}
public class InArgument<T>
{
public InArgument(T constValue)
{
}
}
}",
@"using System.Collections.Generic;
namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
var inArgument = new InArgument<IEnumerable<int>>(new int[] { 1, 2, 3 });
}
}
public class InArgument<T>
{
public InArgument(T constValue)
{
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(775448, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775448")]
public async Task ShouldTriggerOnCS0308(TestHost testHost)
{
// CS0308: The non-generic type 'A' cannot be used with type arguments
await TestAsync(
@"using System.Collections;
class Test
{
static void Main(string[] args)
{
[|IEnumerable<int>|] f;
}
}",
@"using System.Collections;
using System.Collections.Generic;
class Test
{
static void Main(string[] args)
{
IEnumerable<int> f;
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(838253, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/838253")]
public async Task TestConflictedInaccessibleType(TestHost testHost)
{
await TestAsync(
@"using System.Diagnostics;
namespace N
{
public class Log
{
}
}
class C
{
static void Main(string[] args)
{
[|Log|] }
}",
@"using System.Diagnostics;
using N;
namespace N
{
public class Log
{
}
}
class C
{
static void Main(string[] args)
{
Log }
}",
testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(858085, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858085")]
public async Task TestConflictedAttributeName(TestHost testHost)
{
await TestAsync(
@"[[|Description|]]
class Description
{
}",
@"using System.ComponentModel;
[Description]
class Description
{
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(872908, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/872908")]
public async Task TestConflictedGenericName(TestHost testHost)
{
await TestAsync(
@"using Task = System.AccessViolationException;
class X
{
[|Task<X> x;|]
}",
@"using System.Threading.Tasks;
using Task = System.AccessViolationException;
class X
{
Task<X> x;
}", testHost);
}
[Fact]
[WorkItem(913300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/913300")]
public async Task TestNoDuplicateReport_ActionCount()
{
await TestActionCountInAllFixesAsync(
@"class C
{
void M(P p)
{
[|Console|]
}
static void Main(string[] args)
{
}
}", count: 1);
}
[Theory]
[CombinatorialData]
[WorkItem(913300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/913300")]
public async Task TestNoDuplicateReport(TestHost testHost)
{
await TestAsync(
@"class C
{
void M(P p)
{
[|Console|] }
static void Main(string[] args)
{
}
}",
@"using System;
class C
{
void M(P p)
{
Console }
static void Main(string[] args)
{
}
}", testHost);
}
[Fact]
[WorkItem(938296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/938296")]
public async Task TestNullParentInNode()
{
await TestMissingInRegularAndScriptAsync(
@"using System.Collections.Generic;
class MultiDictionary<K, V> : Dictionary<K, HashSet<V>>
{
void M()
{
new HashSet<V>([|Comparer|]);
}
}");
}
[Fact]
[WorkItem(968303, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968303")]
public async Task TestMalformedUsingSection()
{
await TestMissingInRegularAndScriptAsync(
@"[ class Class
{
[|List<|] }");
}
[Theory]
[CombinatorialData]
[WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")]
public async Task TestAddUsingsWithExternAlias(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.cs"">
namespace ProjectLib
{
public class Project
{
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference Alias=""P"">lib</ProjectReference>
<Document FilePath=""Program.cs"">
namespace ExternAliases
{
class Program
{
static void Main(string[] args)
{
Project p = new [|Project()|];
}
}
}
</Document>
</Project>
</Workspace>";
const string ExpectedDocumentText = @"extern alias P;
using P::ProjectLib;
namespace ExternAliases
{
class Program
{
static void Main(string[] args)
{
Project p = new Project();
}
}
}
";
await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")]
public async Task TestAddUsingsWithPreExistingExternAlias(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.cs"">
namespace ProjectLib
{
public class Project
{
}
}
namespace AnotherNS
{
public class AnotherClass
{
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference Alias=""P"">lib</ProjectReference>
<Document FilePath=""Program.cs"">
extern alias P;
using P::ProjectLib;
namespace ExternAliases
{
class Program
{
static void Main(string[] args)
{
Project p = new Project();
var x = new [|AnotherClass()|];
}
}
}
</Document>
</Project>
</Workspace>";
const string ExpectedDocumentText = @"
extern alias P;
using P::AnotherNS;
using P::ProjectLib;
namespace ExternAliases
{
class Program
{
static void Main(string[] args)
{
Project p = new Project();
var x = new [|AnotherClass()|];
}
}
}
";
await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")]
public async Task TestAddUsingsWithPreExistingExternAlias_FileScopedNamespace(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.cs"">
namespace ProjectLib;
{
public class Project
{
}
}
namespace AnotherNS
{
public class AnotherClass
{
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference Alias=""P"">lib</ProjectReference>
<Document FilePath=""Program.cs"">
extern alias P;
using P::ProjectLib;
namespace ExternAliases;
class Program
{
static void Main(string[] args)
{
Project p = new Project();
var x = new [|AnotherClass()|];
}
}
</Document>
</Project>
</Workspace>";
const string ExpectedDocumentText = @"
extern alias P;
using P::AnotherNS;
using P::ProjectLib;
namespace ExternAliases;
class Program
{
static void Main(string[] args)
{
Project p = new Project();
var x = new [|AnotherClass()|];
}
}
";
await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")]
public async Task TestAddUsingsNoExtern(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.cs"">
namespace AnotherNS
{
public class AnotherClass
{
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference Alias=""P"">lib</ProjectReference>
<Document FilePath=""Program.cs"">
using P::AnotherNS;
namespace ExternAliases
{
class Program
{
static void Main(string[] args)
{
var x = new [|AnotherClass()|];
}
}
}
</Document>
</Project>
</Workspace>";
const string ExpectedDocumentText = @"extern alias P;
using P::AnotherNS;
namespace ExternAliases
{
class Program
{
static void Main(string[] args)
{
var x = new AnotherClass();
}
}
}
";
await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")]
public async Task TestAddUsingsNoExtern_FileScopedNamespace(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.cs"">
namespace AnotherNS;
public class AnotherClass
{
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference Alias=""P"">lib</ProjectReference>
<Document FilePath=""Program.cs"">
using P::AnotherNS;
namespace ExternAliases;
class Program
{
static void Main(string[] args)
{
var x = new [|AnotherClass()|];
}
}
</Document>
</Project>
</Workspace>";
const string ExpectedDocumentText = @"extern alias P;
using P::AnotherNS;
namespace ExternAliases;
class Program
{
static void Main(string[] args)
{
var x = new AnotherClass();
}
}
";
await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")]
public async Task TestAddUsingsNoExternFilterGlobalAlias(TestHost testHost)
{
await TestAsync(
@"class Program
{
static void Main(string[] args)
{
[|INotifyPropertyChanged.PropertyChanged|]
}
}",
@"using System.ComponentModel;
class Program
{
static void Main(string[] args)
{
INotifyPropertyChanged.PropertyChanged
}
}", testHost);
}
[Fact]
[WorkItem(916368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916368")]
public async Task TestAddUsingForCref()
{
var initialText =
@"/// <summary>
/// This is just like <see cref='[|INotifyPropertyChanged|]'/>, but this one is mine.
/// </summary>
interface MyNotifyPropertyChanged { }";
var expectedText =
@"using System.ComponentModel;
/// <summary>
/// This is just like <see cref='INotifyPropertyChanged'/>, but this one is mine.
/// </summary>
interface MyNotifyPropertyChanged { }";
var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose);
await TestAsync(initialText, expectedText, parseOptions: options);
}
[Fact]
[WorkItem(916368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916368")]
public async Task TestAddUsingForCref2()
{
var initialText =
@"/// <summary>
/// This is just like <see cref='[|INotifyPropertyChanged.PropertyChanged|]'/>, but this one is mine.
/// </summary>
interface MyNotifyPropertyChanged { }";
var expectedText =
@"using System.ComponentModel;
/// <summary>
/// This is just like <see cref='INotifyPropertyChanged.PropertyChanged'/>, but this one is mine.
/// </summary>
interface MyNotifyPropertyChanged { }";
var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose);
await TestAsync(initialText, expectedText, parseOptions: options);
}
[Fact]
[WorkItem(916368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916368")]
public async Task TestAddUsingForCref3()
{
var initialText =
@"namespace N1
{
public class D { }
}
public class MyClass
{
public static explicit operator N1.D (MyClass f)
{
return default(N1.D);
}
}
/// <seealso cref='MyClass.explicit operator [|D(MyClass)|]'/>
public class MyClass2
{
}";
var expectedText =
@"using N1;
namespace N1
{
public class D { }
}
public class MyClass
{
public static explicit operator N1.D (MyClass f)
{
return default(N1.D);
}
}
/// <seealso cref='MyClass.explicit operator D(MyClass)'/>
public class MyClass2
{
}";
var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose);
await TestAsync(initialText, expectedText, parseOptions: options);
}
[Fact]
[WorkItem(916368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916368")]
public async Task TestAddUsingForCref4()
{
var initialText =
@"namespace N1
{
public class D { }
}
/// <seealso cref='[|Test(D)|]'/>
public class MyClass
{
public void Test(N1.D i)
{
}
}";
var expectedText =
@"using N1;
namespace N1
{
public class D { }
}
/// <seealso cref='Test(D)'/>
public class MyClass
{
public void Test(N1.D i)
{
}
}";
var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose);
await TestAsync(initialText, expectedText, parseOptions: options);
}
[Theory]
[CombinatorialData]
[WorkItem(773614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773614")]
public async Task TestAddStaticType(TestHost testHost)
{
var initialText =
@"using System;
public static class Outer
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
[[|My|]]
class Test
{}";
var expectedText =
@"using System;
using static Outer;
public static class Outer
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
[My]
class Test
{}";
await TestAsync(initialText, expectedText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(773614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773614")]
public async Task TestAddStaticType2(TestHost testHost)
{
var initialText =
@"using System;
public static class Outer
{
public static class Inner
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
}
[[|My|]]
class Test
{}";
var expectedText =
@"using System;
using static Outer.Inner;
public static class Outer
{
public static class Inner
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
}
[My]
class Test
{}";
await TestAsync(initialText, expectedText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(773614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773614")]
public async Task TestAddStaticType3(TestHost testHost)
{
await TestAsync(
@"using System;
public static class Outer
{
public class Inner
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
}
[[|My|]]
class Test
{
}",
@"using System;
using static Outer.Inner;
public static class Outer
{
public class Inner
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
}
[My]
class Test
{
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(773614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773614")]
public async Task TestAddStaticType4(TestHost testHost)
{
var initialText =
@"using System;
using Outer;
public static class Outer
{
public static class Inner
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
}
[[|My|]]
class Test
{}";
var expectedText =
@"using System;
using Outer;
using static Outer.Inner;
public static class Outer
{
public static class Inner
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
}
[My]
class Test
{}";
await TestAsync(initialText, expectedText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")]
public async Task TestAddInsideUsingDirective1(TestHost testHost)
{
await TestAsync(
@"namespace ns
{
using B = [|Byte|];
}",
@"using System;
namespace ns
{
using B = Byte;
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")]
public async Task TestAddInsideUsingDirective2(TestHost testHost)
{
await TestAsync(
@"using System.Collections;
namespace ns
{
using B = [|Byte|];
}",
@"using System;
using System.Collections;
namespace ns
{
using B = Byte;
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")]
public async Task TestAddInsideUsingDirective3(TestHost testHost)
{
await TestAsync(
@"namespace ns2
{
namespace ns3
{
namespace ns
{
using B = [|Byte|];
namespace ns4
{
}
}
}
}",
@"using System;
namespace ns2
{
namespace ns3
{
namespace ns
{
using B = Byte;
namespace ns4
{
}
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")]
public async Task TestAddInsideUsingDirective4(TestHost testHost)
{
await TestAsync(
@"namespace ns2
{
using System.Collections;
namespace ns3
{
namespace ns
{
using System.IO;
using B = [|Byte|];
}
}
}",
@"namespace ns2
{
using System;
using System.Collections;
namespace ns3
{
namespace ns
{
using System.IO;
using B = Byte;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")]
public async Task TestAddInsideUsingDirective5(TestHost testHost)
{
await TestAsync(
@"using System.IO;
namespace ns2
{
using System.Diagnostics;
namespace ns3
{
using System.Collections;
namespace ns
{
using B = [|Byte|];
}
}
}",
@"using System.IO;
namespace ns2
{
using System.Diagnostics;
namespace ns3
{
using System;
using System.Collections;
namespace ns
{
using B = Byte;
}
}
}", testHost);
}
[Fact]
[WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")]
public async Task TestAddInsideUsingDirective6()
{
await TestMissingInRegularAndScriptAsync(
@"using B = [|Byte|];");
}
[Theory]
[CombinatorialData]
[WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")]
public async Task TestAddConditionalAccessExpression(TestHost testHost)
{
var initialText =
@"<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<Document FilePath = ""Program"">
public class C
{
void Main(C a)
{
C x = a?[|.B()|];
}
}
</Document>
<Document FilePath = ""Extensions"">
namespace Extensions
{
public static class E
{
public static C B(this C c) { return c; }
}
}
</Document>
</Project>
</Workspace> ";
var expectedText =
@"
using Extensions;
public class C
{
void Main(C a)
{
C x = a?.B();
}
}
";
await TestAsync(initialText, expectedText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")]
public async Task TestAddConditionalAccessExpression2(TestHost testHost)
{
var initialText =
@"<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<Document FilePath = ""Program"">
public class C
{
public E B { get; private set; }
void Main(C a)
{
int? x = a?.B.[|C()|];
}
public class E
{
}
}
</Document>
<Document FilePath = ""Extensions"">
namespace Extensions
{
public static class D
{
public static C.E C(this C.E c) { return c; }
}
}
</Document>
</Project>
</Workspace> ";
var expectedText =
@"
using Extensions;
public class C
{
public E B { get; private set; }
void Main(C a)
{
int? x = a?.B.C();
}
public class E
{
}
}
";
await TestAsync(initialText, expectedText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1089138, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1089138")]
public async Task TestAmbiguousUsingName(TestHost testHost)
{
await TestAsync(
@"namespace ClassLibrary1
{
using System;
public class SomeTypeUser
{
[|SomeType|] field;
}
}
namespace SubNamespaceName
{
using System;
class SomeType
{
}
}
namespace ClassLibrary1.SubNamespaceName
{
using System;
class SomeOtherFile
{
}
}",
@"namespace ClassLibrary1
{
using System;
using global::SubNamespaceName;
public class SomeTypeUser
{
SomeType field;
}
}
namespace SubNamespaceName
{
using System;
class SomeType
{
}
}
namespace ClassLibrary1.SubNamespaceName
{
using System;
class SomeOtherFile
{
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingInDirective(TestHost testHost)
{
await TestAsync(
@"#define DEBUG
#if DEBUG
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text;
#endif
class Program
{
static void Main(string[] args)
{
var a = [|File|].OpenRead("""");
}
}",
@"#define DEBUG
#if DEBUG
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text;
using System.IO;
#endif
class Program
{
static void Main(string[] args)
{
var a = File.OpenRead("""");
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingInDirective2(TestHost testHost)
{
await TestAsync(
@"#define DEBUG
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
#if DEBUG
using System.Text;
#endif
class Program { static void Main ( string [ ] args ) { var a = [|File|] . OpenRead ( """" ) ; } } ",
@"#define DEBUG
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
#if DEBUG
using System.Text;
#endif
class Program { static void Main ( string [ ] args ) { var a = File . OpenRead ( """" ) ; } } ", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingInDirective3(TestHost testHost)
{
await TestAsync(
@"#define DEBUG
using System;
using System.Collections.Generic;
#if DEBUG
using System.Text;
#endif
using System.Linq;
using System.Threading.Tasks;
class Program { static void Main ( string [ ] args ) { var a = [|File|] . OpenRead ( """" ) ; } } ",
@"#define DEBUG
using System;
using System.Collections.Generic;
#if DEBUG
using System.Text;
#endif
using System.Linq;
using System.Threading.Tasks;
using System.IO;
class Program { static void Main ( string [ ] args ) { var a = File . OpenRead ( """" ) ; } } ", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingInDirective4(TestHost testHost)
{
await TestAsync(
@"#define DEBUG
#if DEBUG
using System;
#endif
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
class Program { static void Main ( string [ ] args ) { var a = [|File|] . OpenRead ( """" ) ; } } ",
@"#define DEBUG
#if DEBUG
using System;
#endif
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
class Program { static void Main ( string [ ] args ) { var a = File . OpenRead ( """" ) ; } } ", testHost);
}
[Fact]
public async Task TestInaccessibleExtensionMethod()
{
const string initial = @"
namespace N1
{
public static class C
{
private static bool ExtMethod1(this string arg1)
{
return true;
}
}
}
namespace N2
{
class Program
{
static void Main(string[] args)
{
var x = ""str1"".[|ExtMethod1()|];
}
}
}";
await TestMissingInRegularAndScriptAsync(initial);
}
[Theory]
[CombinatorialData]
[WorkItem(1116011, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1116011")]
public async Task TestAddUsingForProperty(TestHost testHost)
{
await TestAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
public BindingFlags BindingFlags
{
get
{
return BindingFlags.[|Instance|];
}
}
}",
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
class Program
{
public BindingFlags BindingFlags
{
get
{
return BindingFlags.Instance;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1116011, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1116011")]
public async Task TestAddUsingForField(TestHost testHost)
{
await TestAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
public B B
{
get
{
return B.[|Instance|];
}
}
}
namespace A
{
public class B
{
public static readonly B Instance;
}
}",
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using A;
class Program
{
public B B
{
get
{
return B.Instance;
}
}
}
namespace A
{
public class B
{
public static readonly B Instance;
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1893, "https://github.com/dotnet/roslyn/issues/1893")]
public async Task TestNameSimplification(TestHost testHost)
{
// Generated using directive must be simplified from "using A.B;" to "using B;" below.
await TestAsync(
@"namespace A.B
{
class T1
{
}
}
namespace A.C
{
using System;
class T2
{
void Test()
{
Console.WriteLine();
[|T1|] t1;
}
}
}",
@"namespace A.B
{
class T1
{
}
}
namespace A.C
{
using System;
using A.B;
class T2
{
void Test()
{
Console.WriteLine();
T1 t1;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(935, "https://github.com/dotnet/roslyn/issues/935")]
public async Task TestAddUsingWithOtherExtensionsInScope(TestHost testHost)
{
await TestAsync(
@"using System.Linq;
using System.Collections;
using X;
namespace X
{
public static class Ext
{
public static void ExtMethod(this int a)
{
}
}
}
namespace Y
{
public static class Ext
{
public static void ExtMethod(this int a, int v)
{
}
}
}
public class B
{
static void Main()
{
var b = 0;
b.[|ExtMethod|](0);
}
}",
@"using System.Linq;
using System.Collections;
using X;
using Y;
namespace X
{
public static class Ext
{
public static void ExtMethod(this int a)
{
}
}
}
namespace Y
{
public static class Ext
{
public static void ExtMethod(this int a, int v)
{
}
}
}
public class B
{
static void Main()
{
var b = 0;
b.ExtMethod(0);
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(935, "https://github.com/dotnet/roslyn/issues/935")]
public async Task TestAddUsingWithOtherExtensionsInScope2(TestHost testHost)
{
await TestAsync(
@"using System.Linq;
using System.Collections;
using X;
namespace X
{
public static class Ext
{
public static void ExtMethod(this int? a)
{
}
}
}
namespace Y
{
public static class Ext
{
public static void ExtMethod(this int? a, int v)
{
}
}
}
public class B
{
static void Main()
{
var b = new int?();
b?[|.ExtMethod|](0);
}
}",
@"using System.Linq;
using System.Collections;
using X;
using Y;
namespace X
{
public static class Ext
{
public static void ExtMethod(this int? a)
{
}
}
}
namespace Y
{
public static class Ext
{
public static void ExtMethod(this int? a, int v)
{
}
}
}
public class B
{
static void Main()
{
var b = new int?();
b?.ExtMethod(0);
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(562, "https://github.com/dotnet/roslyn/issues/562")]
public async Task TestAddUsingWithOtherExtensionsInScope3(TestHost testHost)
{
await TestAsync(
@"using System.Linq;
class C
{
int i = 0.[|All|]();
}
namespace X
{
static class E
{
public static int All(this int o) => 0;
}
}",
@"using System.Linq;
using X;
class C
{
int i = 0.All();
}
namespace X
{
static class E
{
public static int All(this int o) => 0;
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(562, "https://github.com/dotnet/roslyn/issues/562")]
public async Task TestAddUsingWithOtherExtensionsInScope4(TestHost testHost)
{
await TestAsync(
@"using System.Linq;
class C
{
static void Main(string[] args)
{
var a = new int?();
int? i = a?[|.All|]();
}
}
namespace X
{
static class E
{
public static int? All(this int? o) => 0;
}
}",
@"using System.Linq;
using X;
class C
{
static void Main(string[] args)
{
var a = new int?();
int? i = a?.All();
}
}
namespace X
{
static class E
{
public static int? All(this int? o) => 0;
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")]
public async Task TestNestedNamespaceSimplified(TestHost testHost)
{
await TestAsync(
@"namespace Microsoft.MyApp
{
using Win32;
class Program
{
static void Main(string[] args)
{
[|SafeRegistryHandle|] h;
}
}
}",
@"namespace Microsoft.MyApp
{
using Microsoft.Win32.SafeHandles;
using Win32;
class Program
{
static void Main(string[] args)
{
SafeRegistryHandle h;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")]
public async Task TestNestedNamespaceSimplified2(TestHost testHost)
{
await TestAsync(
@"namespace Microsoft.MyApp
{
using Zin32;
class Program
{
static void Main(string[] args)
{
[|SafeRegistryHandle|] h;
}
}
}",
@"namespace Microsoft.MyApp
{
using Microsoft.Win32.SafeHandles;
using Zin32;
class Program
{
static void Main(string[] args)
{
SafeRegistryHandle h;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")]
public async Task TestNestedNamespaceSimplified3(TestHost testHost)
{
await TestAsync(
@"namespace Microsoft.MyApp
{
using System;
using Win32;
class Program
{
static void Main(string[] args)
{
[|SafeRegistryHandle|] h;
}
}
}",
@"namespace Microsoft.MyApp
{
using System;
using Microsoft.Win32.SafeHandles;
using Win32;
class Program
{
static void Main(string[] args)
{
SafeRegistryHandle h;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")]
public async Task TestNestedNamespaceSimplified4(TestHost testHost)
{
await TestAsync(
@"namespace Microsoft.MyApp
{
using System;
using Zin32;
class Program
{
static void Main(string[] args)
{
[|SafeRegistryHandle|] h;
}
}
}",
@"namespace Microsoft.MyApp
{
using System;
using Microsoft.Win32.SafeHandles;
using Zin32;
class Program
{
static void Main(string[] args)
{
SafeRegistryHandle h;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")]
public async Task TestNestedNamespaceSimplified5(TestHost testHost)
{
await TestAsync(
@"namespace Microsoft.MyApp
{
#if true
using Win32;
#else
using System;
#endif
class Program
{
static void Main(string[] args)
{
[|SafeRegistryHandle|] h;
}
}
}",
@"namespace Microsoft.MyApp
{
using Microsoft.Win32.SafeHandles;
#if true
using Win32;
#else
using System;
#endif
class Program
{
static void Main(string[] args)
{
SafeRegistryHandle h;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")]
public async Task TestNestedNamespaceSimplified6(TestHost testHost)
{
await TestAsync(
@"namespace Microsoft.MyApp
{
using System;
#if false
using Win32;
#endif
using Win32;
class Program
{
static void Main(string[] args)
{
[|SafeRegistryHandle|] h;
}
}
}",
@"namespace Microsoft.MyApp
{
using System;
using Microsoft.Win32.SafeHandles;
#if false
using Win32;
#endif
using Win32;
class Program
{
static void Main(string[] args)
{
SafeRegistryHandle h;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingOrdinalUppercase(TestHost testHost)
{
await TestAsync(
@"namespace A
{
class A
{
static void Main(string[] args)
{
var b = new [|B|]();
}
}
}
namespace lowercase
{
class b
{
}
}
namespace Uppercase
{
class B
{
}
}",
@"using Uppercase;
namespace A
{
class A
{
static void Main(string[] args)
{
var b = new B();
}
}
}
namespace lowercase
{
class b
{
}
}
namespace Uppercase
{
class B
{
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingOrdinalLowercase(TestHost testHost)
{
await TestAsync(
@"namespace A
{
class A
{
static void Main(string[] args)
{
var a = new [|b|]();
}
}
}
namespace lowercase
{
class b
{
}
}
namespace Uppercase
{
class B
{
}
}",
@"using lowercase;
namespace A
{
class A
{
static void Main(string[] args)
{
var a = new b();
}
}
}
namespace lowercase
{
class b
{
}
}
namespace Uppercase
{
class B
{
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(7443, "https://github.com/dotnet/roslyn/issues/7443")]
public async Task TestWithExistingIncompatibleExtension(TestHost testHost)
{
await TestAsync(
@"using N;
class C
{
int x()
{
System.Collections.Generic.IEnumerable<int> x = null;
return x.[|Any|]
}
}
namespace N
{
static class Extensions
{
public static void Any(this string s)
{
}
}
}",
@"using System.Linq;
using N;
class C
{
int x()
{
System.Collections.Generic.IEnumerable<int> x = null;
return x.Any
}
}
namespace N
{
static class Extensions
{
public static void Any(this string s)
{
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1744, @"https://github.com/dotnet/roslyn/issues/1744")]
public async Task TestIncompleteCatchBlockInLambda(TestHost testHost)
{
await TestAsync(
@"class A
{
System.Action a = () => {
try
{
}
catch ([|Exception|]",
@"using System;
class A
{
System.Action a = () => {
try
{
}
catch (Exception", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1033612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033612")]
public async Task TestAddInsideLambda(TestHost testHost)
{
var initialText =
@"using System;
static void Main(string[] args)
{
Func<int> f = () => { [|List<int>|]. }
}";
var expectedText =
@"using System;
using System.Collections.Generic;
static void Main(string[] args)
{
Func<int> f = () => { List<int>. }
}";
await TestAsync(initialText, expectedText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1033612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033612")]
public async Task TestAddInsideLambda2(TestHost testHost)
{
var initialText =
@"using System;
static void Main(string[] args)
{
Func<int> f = () => { [|List<int>|] }
}";
var expectedText =
@"using System;
using System.Collections.Generic;
static void Main(string[] args)
{
Func<int> f = () => { List<int> }
}";
await TestAsync(initialText, expectedText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1033612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033612")]
public async Task TestAddInsideLambda3(TestHost testHost)
{
var initialText =
@"using System;
static void Main(string[] args)
{
Func<int> f = () => {
var a = 3;
[|List<int>|].
return a;
};
}";
var expectedText =
@"using System;
using System.Collections.Generic;
static void Main(string[] args)
{
Func<int> f = () => {
var a = 3;
List<int>.
return a;
};
}";
await TestAsync(initialText, expectedText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1033612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033612")]
public async Task TestAddInsideLambda4(TestHost testHost)
{
var initialText =
@"using System;
static void Main(string[] args)
{
Func<int> f = () => {
var a = 3;
[|List<int>|]
return a;
};
}";
var expectedText =
@"using System;
using System.Collections.Generic;
static void Main(string[] args)
{
Func<int> f = () => {
var a = 3;
List<int>
return a;
};
}";
await TestAsync(initialText, expectedText, testHost);
}
[WorkItem(860648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/860648")]
[Theory]
[CombinatorialData]
[WorkItem(902014, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/902014")]
public async Task TestIncompleteParenthesizedLambdaExpression(TestHost testHost)
{
await TestAsync(
@"using System;
class Test
{
void Goo()
{
Action a = () => {
[|IBindCtx|] };
string a;
}
}",
@"using System;
using System.Runtime.InteropServices.ComTypes;
class Test
{
void Goo()
{
Action a = () => {
IBindCtx };
string a;
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(7461, "https://github.com/dotnet/roslyn/issues/7461")]
public async Task TestExtensionWithIncompatibleInstance(TestHost testHost)
{
await TestAsync(
@"using System.IO;
namespace Namespace1
{
static class StreamExtensions
{
public static void Write(this Stream stream, byte[] bytes)
{
}
}
}
namespace Namespace2
{
class Goo
{
void Bar()
{
Stream stream = null;
stream.[|Write|](new byte[] { 1, 2, 3 });
}
}
}",
@"using System.IO;
using Namespace1;
namespace Namespace1
{
static class StreamExtensions
{
public static void Write(this Stream stream, byte[] bytes)
{
}
}
}
namespace Namespace2
{
class Goo
{
void Bar()
{
Stream stream = null;
stream.Write(new byte[] { 1, 2, 3 });
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(5499, "https://github.com/dotnet/roslyn/issues/5499")]
public async Task TestFormattingForNamespaceUsings(TestHost testHost)
{
await TestAsync(
@"namespace N
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Program
{
void Main()
{
[|Task<int>|]
}
}
}",
@"namespace N
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Program
{
void Main()
{
Task<int>
}
}
}", testHost);
}
[Fact]
public async Task TestGenericAmbiguityInSameNamespace()
{
await TestMissingInRegularAndScriptAsync(
@"namespace NS
{
class C<T> where T : [|C|].N
{
public class N
{
}
}
}");
}
[Fact]
public async Task TestNotOnVar1()
{
await TestMissingInRegularAndScriptAsync(
@"namespace N
{
class var { }
}
class C
{
void M()
{
[|var|]
}
}
");
}
[Fact]
public async Task TestNotOnVar2()
{
await TestMissingInRegularAndScriptAsync(
@"namespace N
{
class Bar { }
}
class C
{
void M()
{
[|var|]
}
}
");
}
[Theory]
[CombinatorialData]
[WorkItem(226826, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=226826")]
public async Task TestAddUsingWithLeadingDocCommentInFrontOfUsing1(TestHost testHost)
{
await TestAsync(
@"
/// Copyright 2016 - MyCompany
/// All Rights Reserved
using System;
class C : [|IEnumerable|]<int>
{
}
",
@"
/// Copyright 2016 - MyCompany
/// All Rights Reserved
using System;
using System.Collections.Generic;
class C : IEnumerable<int>
{
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(226826, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=226826")]
public async Task TestAddUsingWithLeadingDocCommentInFrontOfUsing2(TestHost testHost)
{
await TestAsync(
@"
/// Copyright 2016 - MyCompany
/// All Rights Reserved
using System.Collections;
class C
{
[|DateTime|] d;
}
",
@"
/// Copyright 2016 - MyCompany
/// All Rights Reserved
using System;
using System.Collections;
class C
{
DateTime d;
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(226826, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=226826")]
public async Task TestAddUsingWithLeadingDocCommentInFrontOfClass1(TestHost testHost)
{
await TestAsync(
@"
/// Copyright 2016 - MyCompany
/// All Rights Reserved
class C
{
[|DateTime|] d;
}
",
@"
using System;
/// Copyright 2016 - MyCompany
/// All Rights Reserved
class C
{
DateTime d;
}
", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestPlaceUsingWithUsings_NotWithAliases(TestHost testHost)
{
await TestAsync(
@"
using System;
namespace N
{
using C = System.Collections;
class Class
{
[|List<int>|] Method()
{
Goo();
}
}
}",
@"
using System;
using System.Collections.Generic;
namespace N
{
using C = System.Collections;
class Class
{
List<int> Method()
{
Goo();
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(15025, "https://github.com/dotnet/roslyn/issues/15025")]
public async Task TestPreferSystemNamespaceFirst(TestHost testHost)
{
await TestAsync(
@"
namespace Microsoft
{
public class SomeClass { }
}
namespace System
{
public class SomeClass { }
}
namespace N
{
class Class
{
[|SomeClass|] c;
}
}",
@"
using System;
namespace Microsoft
{
public class SomeClass { }
}
namespace System
{
public class SomeClass { }
}
namespace N
{
class Class
{
SomeClass c;
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(15025, "https://github.com/dotnet/roslyn/issues/15025")]
public async Task TestPreferSystemNamespaceFirst2(TestHost testHost)
{
await TestAsync(
@"
namespace Microsoft
{
public class SomeClass { }
}
namespace System
{
public class SomeClass { }
}
namespace N
{
class Class
{
[|SomeClass|] c;
}
}",
@"
using Microsoft;
namespace Microsoft
{
public class SomeClass { }
}
namespace System
{
public class SomeClass { }
}
namespace N
{
class Class
{
SomeClass c;
}
}", testHost, index: 1);
}
[Fact]
[WorkItem(18275, "https://github.com/dotnet/roslyn/issues/18275")]
public async Task TestContextualKeyword1()
{
await TestMissingInRegularAndScriptAsync(
@"
namespace N
{
class nameof
{
}
}
class C
{
void M()
{
[|nameof|]
}
}");
}
[Theory]
[CombinatorialData]
[WorkItem(19218, "https://github.com/dotnet/roslyn/issues/19218")]
public async Task TestChangeCaseWithUsingsInNestedNamespace(TestHost testHost)
{
await TestAsync(
@"namespace VS
{
interface IVsStatusbar
{
}
}
namespace Outer
{
using System;
class C
{
void M()
{
// Note: IVsStatusBar is cased incorrectly.
[|IVsStatusBar|] b;
}
}
}
",
@"namespace VS
{
interface IVsStatusbar
{
}
}
namespace Outer
{
using System;
using VS;
class C
{
void M()
{
// Note: IVsStatusBar is cased incorrectly.
IVsStatusbar b;
}
}
}
", testHost);
}
[Fact]
[WorkItem(19575, "https://github.com/dotnet/roslyn/issues/19575")]
public async Task TestNoNonGenericsWithGenericCodeParsedAsExpression()
{
var code = @"
class C
{
private void GetEvaluationRuleNames()
{
[|IEnumerable|] < Int32 >
return ImmutableArray.CreateRange();
}
}";
await TestActionCountAsync(code, count: 1);
await TestInRegularAndScriptAsync(
code,
@"
using System.Collections.Generic;
class C
{
private void GetEvaluationRuleNames()
{
IEnumerable < Int32 >
return ImmutableArray.CreateRange();
}
}");
}
[Theory]
[CombinatorialData]
[WorkItem(19796, "https://github.com/dotnet/roslyn/issues/19796")]
public async Task TestWhenInRome1(TestHost testHost)
{
// System is set to be sorted first, but the actual file shows it at the end.
// Keep things sorted, but respect that 'System' is at the end.
await TestAsync(
@"
using B;
using System;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"
using A;
using B;
using System;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(19796, "https://github.com/dotnet/roslyn/issues/19796")]
public async Task TestWhenInRome2(TestHost testHost)
{
// System is set to not be sorted first, but the actual file shows it sorted first.
// Keep things sorted, but respect that 'System' is at the beginning.
await TestAsync(
@"
using System;
using B;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"
using System;
using A;
using B;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}", testHost);
}
[Fact]
public async Task TestExactMatchNoGlyph()
{
await TestSmartTagGlyphTagsAsync(
@"namespace VS
{
interface Other
{
}
}
class C
{
void M()
{
[|Other|] b;
}
}
", ImmutableArray<string>.Empty);
}
[Fact]
public async Task TestFuzzyMatchGlyph()
{
await TestSmartTagGlyphTagsAsync(
@"namespace VS
{
interface Other
{
}
}
class C
{
void M()
{
[|Otter|] b;
}
}
", WellKnownTagArrays.Namespace);
}
[Theory]
[CombinatorialData]
[WorkItem(29313, "https://github.com/dotnet/roslyn/issues/29313")]
public async Task TestGetAwaiterExtensionMethod1(TestHost testHost)
{
await TestAsync(
@"
namespace A
{
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class C
{
async Task M() => await [|Goo|];
C Goo { get; set; }
}
}
namespace B
{
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using A;
static class Extensions
{
public static Awaiter GetAwaiter(this C scheduler) => null;
public class Awaiter : INotifyCompletion
{
public object GetResult() => null;
public void OnCompleted(Action continuation) { }
public bool IsCompleted => true;
}
}
}",
@"
namespace A
{
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using B;
class C
{
async Task M() => await Goo;
C Goo { get; set; }
}
}
namespace B
{
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using A;
static class Extensions
{
public static Awaiter GetAwaiter(this C scheduler) => null;
public class Awaiter : INotifyCompletion
{
public object GetResult() => null;
public void OnCompleted(Action continuation) { }
public bool IsCompleted => true;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(29313, "https://github.com/dotnet/roslyn/issues/29313")]
public async Task TestGetAwaiterExtensionMethod2(TestHost testHost)
{
await TestAsync(
@"
namespace A
{
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class C
{
async Task M() => await [|GetC|]();
C GetC() => null;
}
}
namespace B
{
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using A;
static class Extensions
{
public static Awaiter GetAwaiter(this C scheduler) => null;
public class Awaiter : INotifyCompletion
{
public object GetResult() => null;
public void OnCompleted(Action continuation) { }
public bool IsCompleted => true;
}
}
}",
@"
namespace A
{
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using B;
class C
{
async Task M() => await GetC();
C GetC() => null;
}
}
namespace B
{
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using A;
static class Extensions
{
public static Awaiter GetAwaiter(this C scheduler) => null;
public class Awaiter : INotifyCompletion
{
public object GetResult() => null;
public void OnCompleted(Action continuation) { }
public bool IsCompleted => true;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(745490, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/745490")]
public async Task TestAddUsingForAwaitableReturningExtensionMethod(TestHost testHost)
{
await TestAsync(
@"
namespace A
{
using System;
using System.Threading.Tasks;
class C
{
C Instance { get; }
async Task M() => await Instance.[|Foo|]();
}
}
namespace B
{
using System;
using System.Threading.Tasks;
using A;
static class Extensions
{
public static Task Foo(this C instance) => null;
}
}",
@"
namespace A
{
using System;
using System.Threading.Tasks;
using B;
class C
{
C Instance { get; }
async Task M() => await Instance.Foo();
}
}
namespace B
{
using System;
using System.Threading.Tasks;
using A;
static class Extensions
{
public static Task Foo(this C instance) => null;
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingForExtensionGetEnumeratorReturningIEnumerator(TestHost testHost)
{
await TestAsync(
@"
namespace A
{
class C
{
C Instance { get; }
void M() { foreach (var i in [|Instance|]); }
}
}
namespace B
{
using A;
using System.Collections.Generic;
static class Extensions
{
public static IEnumerator<int> GetEnumerator(this C instance) => null;
}
}",
@"
using B;
namespace A
{
class C
{
C Instance { get; }
void M() { foreach (var i in Instance); }
}
}
namespace B
{
using A;
using System.Collections.Generic;
static class Extensions
{
public static IEnumerator<int> GetEnumerator(this C instance) => null;
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingForExtensionGetEnumeratorReturningPatternEnumerator(TestHost testHost)
{
await TestAsync(
@"
namespace A
{
class C
{
C Instance { get; }
void M() { foreach (var i in [|Instance|]); }
}
}
namespace B
{
using A;
static class Extensions
{
public static Enumerator GetEnumerator(this C instance) => null;
}
public class Enumerator
{
public int Current { get; }
public bool MoveNext();
}
}",
@"
using B;
namespace A
{
class C
{
C Instance { get; }
void M() { foreach (var i in Instance); }
}
}
namespace B
{
using A;
static class Extensions
{
public static Enumerator GetEnumerator(this C instance) => null;
}
public class Enumerator
{
public int Current { get; }
public bool MoveNext();
}
}", testHost);
}
[Fact]
public async Task TestMissingForExtensionInvalidGetEnumerator()
{
await TestMissingAsync(
@"
namespace A
{
class C
{
C Instance { get; }
void M() { foreach (var i in [|Instance|]); }
}
}
namespace B
{
using A;
static class Extensions
{
public static bool GetEnumerator(this C instance) => null;
}
}");
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingForExtensionGetEnumeratorReturningPatternEnumeratorWrongAsync(TestHost testHost)
{
await TestAsync(
@"
namespace A
{
class C
{
C Instance { get; };
void M() { foreach (var i in [|Instance|]); }
public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default)
{
return new Enumerator();
}
public sealed class Enumerator
{
public async System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null;
public int Current => throw null;
}
}
}
namespace B
{
using A;
static class Extensions
{
public static Enumerator GetEnumerator(this C instance) => null;
}
public class Enumerator
{
public int Current { get; }
public bool MoveNext();
}
}",
@"
using B;
namespace A
{
class C
{
C Instance { get; };
void M() { foreach (var i in Instance); }
public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default)
{
return new Enumerator();
}
public sealed class Enumerator
{
public async System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null;
public int Current => throw null;
}
}
}
namespace B
{
using A;
static class Extensions
{
public static Enumerator GetEnumerator(this C instance) => null;
}
public class Enumerator
{
public int Current { get; }
public bool MoveNext();
}
}", testHost);
}
[Fact]
public async Task TestMissingForExtensionGetAsyncEnumeratorOnForeach()
{
await TestMissingAsync(
@"
namespace A
{
class C
{
C Instance { get; }
void M() { foreach (var i in [|Instance|]); }
}
}
namespace B
{
using A;
using System.Collections.Generic;
static class Extensions
{
public static IAsyncEnumerator<int> GetAsyncEnumerator(this C instance) => null;
}
}" + IAsyncEnumerable);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingForExtensionGetAsyncEnumeratorReturningIAsyncEnumerator(TestHost testHost)
{
await TestAsync(
@"
using System.Threading.Tasks;
namespace A
{
class C
{
C Instance { get; }
async Task M() { await foreach (var i in [|Instance|]); }
}
}
namespace B
{
using A;
using System.Collections.Generic;
static class Extensions
{
public static IAsyncEnumerator<int> GetAsyncEnumerator(this C instance) => null;
}
}" + IAsyncEnumerable,
@"
using System.Threading.Tasks;
using B;
namespace A
{
class C
{
C Instance { get; }
async Task M() { await foreach (var i in Instance); }
}
}
namespace B
{
using A;
using System.Collections.Generic;
static class Extensions
{
public static IAsyncEnumerator<int> GetAsyncEnumerator(this C instance) => null;
}
}" + IAsyncEnumerable, testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingForExtensionGetAsyncEnumeratorReturningPatternEnumerator(TestHost testHost)
{
await TestAsync(
@"
using System.Threading.Tasks;
namespace A
{
class C
{
C Instance { get; }
async Task M() { await foreach (var i in [|Instance|]); }
}
}
namespace B
{
using A;
static class Extensions
{
public static Enumerator GetAsyncEnumerator(this C instance) => null;
}
public class Enumerator
{
public int Current { get; }
public Task<bool> MoveNextAsync();
}
}",
@"
using System.Threading.Tasks;
using B;
namespace A
{
class C
{
C Instance { get; }
async Task M() { await foreach (var i in Instance); }
}
}
namespace B
{
using A;
static class Extensions
{
public static Enumerator GetAsyncEnumerator(this C instance) => null;
}
public class Enumerator
{
public int Current { get; }
public Task<bool> MoveNextAsync();
}
}", testHost);
}
[Fact]
public async Task TestMissingForExtensionInvalidGetAsyncEnumerator()
{
await TestMissingAsync(
@"
using System.Threading.Tasks;
namespace A
{
class C
{
C Instance { get; }
async Task M() { await foreach (var i in [|Instance|]); }
}
}
namespace B
{
using A;
static class Extensions
{
public static bool GetAsyncEnumerator(this C instance) => null;
}
}");
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingForExtensionGetAsyncEnumeratorReturningPatternEnumeratorWrongAsync(TestHost testHost)
{
await TestAsync(
@"
using System.Threading.Tasks;
namespace A
{
class C
{
C Instance { get; }
Task M() { await foreach (var i in [|Instance|]); }
public Enumerator GetEnumerator()
{
return new Enumerator();
}
public class Enumerator
{
public int Current { get; }
public bool MoveNext();
}
}
}
namespace B
{
using A;
static class Extensions
{
public static Enumerator GetAsyncEnumerator(this C instance) => null;
}
public sealed class Enumerator
{
public async System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null;
public int Current => throw null;
}
}",
@"
using System.Threading.Tasks;
using B;
namespace A
{
class C
{
C Instance { get; }
Task M() { await foreach (var i in Instance); }
public Enumerator GetEnumerator()
{
return new Enumerator();
}
public class Enumerator
{
public int Current { get; }
public bool MoveNext();
}
}
}
namespace B
{
using A;
static class Extensions
{
public static Enumerator GetAsyncEnumerator(this C instance) => null;
}
public sealed class Enumerator
{
public async System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null;
public int Current => throw null;
}
}", testHost);
}
[Fact]
public async Task TestMissingForExtensionGetEnumeratorOnAsyncForeach()
{
await TestMissingAsync(
@"
using System.Threading.Tasks;
namespace A
{
class C
{
C Instance { get; }
Task M() { await foreach (var i in [|Instance|]); }
}
}
namespace B
{
using A;
using System.Collections.Generic;
static class Extensions
{
public static IEnumerator<int> GetEnumerator(this C instance) => null;
}
}");
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithStaticUsingInNamespace_WhenNoExistingUsings(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
using static System.Math;
class C
{
public [|List<int>|] F;
}
}
",
@"
namespace N
{
using System.Collections.Generic;
using static System.Math;
class C
{
public List<int> F;
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithStaticUsingInInnerNestedNamespace_WhenNoExistingUsings(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
namespace M
{
using static System.Math;
class C
{
public [|List<int>|] F;
}
}
}
",
@"
namespace N
{
namespace M
{
using System.Collections.Generic;
using static System.Math;
class C
{
public List<int> F;
}
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithStaticUsingInOuterNestedNamespace_WhenNoExistingUsings(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
using static System.Math;
namespace M
{
class C
{
public [|List<int>|] F;
}
}
}
",
@"
namespace N
{
using System.Collections.Generic;
using static System.Math;
namespace M
{
class C
{
public List<int> F;
}
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithExistingUsingInCompilationUnit_WhenStaticUsingInNamespace(TestHost testHost)
{
await TestAsync(
@"
using System;
namespace N
{
using static System.Math;
class C
{
public [|List<int>|] F;
}
}
",
@"
using System;
using System.Collections.Generic;
namespace N
{
using static System.Math;
class C
{
public List<int> F;
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithExistingUsing_WhenStaticUsingInInnerNestedNamespace(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
using System;
namespace M
{
using static System.Math;
class C
{
public [|List<int>|] F;
}
}
}
",
@"
namespace N
{
using System;
using System.Collections.Generic;
namespace M
{
using static System.Math;
class C
{
public List<int> F;
}
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithExistingUsing_WhenStaticUsingInOuterNestedNamespace(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
using static System.Math;
namespace M
{
using System;
class C
{
public [|List<int>|] F;
}
}
}
",
@"
namespace N
{
using static System.Math;
namespace M
{
using System;
using System.Collections.Generic;
class C
{
public List<int> F;
}
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithUsingAliasInNamespace_WhenNoExistingUsing(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
using SAction = System.Action;
class C
{
public [|List<int>|] F;
}
}
",
@"
namespace N
{
using System.Collections.Generic;
using SAction = System.Action;
class C
{
public List<int> F;
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithUsingAliasInInnerNestedNamespace_WhenNoExistingUsing(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
namespace M
{
using SAction = System.Action;
class C
{
public [|List<int>|] F;
}
}
}
",
@"
namespace N
{
namespace M
{
using System.Collections.Generic;
using SAction = System.Action;
class C
{
public List<int> F;
}
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithUsingAliasInOuterNestedNamespace_WhenNoExistingUsing(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
using SAction = System.Action;
namespace M
{
class C
{
public [|List<int>|] F;
}
}
}
",
@"
namespace N
{
using System.Collections.Generic;
using SAction = System.Action;
namespace M
{
class C
{
public List<int> F;
}
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithExistingUsingInCompilationUnit_WhenUsingAliasInNamespace(TestHost testHost)
{
await TestAsync(
@"
using System;
namespace N
{
using SAction = System.Action;
class C
{
public [|List<int>|] F;
}
}
",
@"
using System;
using System.Collections.Generic;
namespace N
{
using SAction = System.Action;
class C
{
public List<int> F;
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithExistingUsing_WhenUsingAliasInInnerNestedNamespace(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
using System;
namespace M
{
using SAction = System.Action;
class C
{
public [|List<int>|] F;
}
}
}
",
@"
namespace N
{
using System;
using System.Collections.Generic;
namespace M
{
using SAction = System.Action;
class C
{
public [|List<int>|] F;
}
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithExistingUsing_WhenUsingAliasInOuterNestedNamespace(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
using SAction = System.Action;
namespace M
{
using System;
class C
{
public [|List<int>|] F;
}
}
}
",
@"
namespace N
{
using SAction = System.Action;
namespace M
{
using System;
using System.Collections.Generic;
class C
{
public [|List<int>|] F;
}
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")]
public async Task KeepUsingsGrouped1(TestHost testHost)
{
await TestAsync(
@"
using System;
class Program
{
static void Main(string[] args)
{
[|Goo|]
}
}
namespace Microsoft
{
public class Goo
{
}
}",
@"
using System;
using Microsoft;
class Program
{
static void Main(string[] args)
{
Goo
}
}
namespace Microsoft
{
public class Goo
{
}
}", testHost);
}
[WorkItem(1239, @"https://github.com/dotnet/roslyn/issues/1239")]
[Fact]
public async Task TestIncompleteLambda1()
{
await TestInRegularAndScriptAsync(
@"using System.Linq;
class C
{
C()
{
"""".Select(() => {
new [|Byte|]",
@"using System;
using System.Linq;
class C
{
C()
{
"""".Select(() => {
new Byte");
}
[WorkItem(1239, @"https://github.com/dotnet/roslyn/issues/1239")]
[Fact]
public async Task TestIncompleteLambda2()
{
await TestInRegularAndScriptAsync(
@"using System.Linq;
class C
{
C()
{
"""".Select(() => {
new [|Byte|]() }",
@"using System;
using System.Linq;
class C
{
C()
{
"""".Select(() => {
new Byte() }");
}
[WorkItem(860648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/860648")]
[WorkItem(902014, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/902014")]
[Fact]
public async Task TestIncompleteSimpleLambdaExpression()
{
await TestInRegularAndScriptAsync(
@"using System.Linq;
class Program
{
static void Main(string[] args)
{
args[0].Any(x => [|IBindCtx|]
string a;
}
}",
@"using System.Linq;
using System.Runtime.InteropServices.ComTypes;
class Program
{
static void Main(string[] args)
{
args[0].Any(x => IBindCtx
string a;
}
}");
}
[Theory]
[CombinatorialData]
[WorkItem(1266354, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1266354")]
public async Task TestAddUsingsEditorBrowsableNeverSameProject(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.cs"">
using System.ComponentModel;
namespace ProjectLib
{
[EditorBrowsable(EditorBrowsableState.Never)]
public class Project
{
}
}
</Document>
<Document FilePath=""Program.cs"">
class Program
{
static void Main(string[] args)
{
Project p = new [|Project()|];
}
}
</Document>
</Project>
</Workspace>";
const string ExpectedDocumentText = @"
using ProjectLib;
class Program
{
static void Main(string[] args)
{
Project p = new [|Project()|];
}
}
";
await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1266354, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1266354")]
public async Task TestAddUsingsEditorBrowsableNeverDifferentProject(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""Visual Basic"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.vb"">
imports System.ComponentModel
namespace ProjectLib
<EditorBrowsable(EditorBrowsableState.Never)>
public class Project
end class
end namespace
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference>lib</ProjectReference>
<Document FilePath=""Program.cs"">
class Program
{
static void Main(string[] args)
{
[|Project|] p = new Project();
}
}
</Document>
</Project>
</Workspace>";
await TestMissingAsync(InitialWorkspace, new TestParameters(testHost: testHost));
}
[Theory]
[CombinatorialData]
[WorkItem(1266354, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1266354")]
public async Task TestAddUsingsEditorBrowsableAdvancedDifferentProjectOptionOn(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""Visual Basic"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.vb"">
imports System.ComponentModel
namespace ProjectLib
<EditorBrowsable(EditorBrowsableState.Advanced)>
public class Project
end class
end namespace
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference>lib</ProjectReference>
<Document FilePath=""Program.cs"">
class Program
{
static void Main(string[] args)
{
[|Project|] p = new Project();
}
}
</Document>
</Project>
</Workspace>";
const string ExpectedDocumentText = @"
using ProjectLib;
class Program
{
static void Main(string[] args)
{
Project p = new [|Project()|];
}
}
";
await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1266354, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1266354")]
public async Task TestAddUsingsEditorBrowsableAdvancedDifferentProjectOptionOff(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""Visual Basic"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.vb"">
imports System.ComponentModel
namespace ProjectLib
<EditorBrowsable(EditorBrowsableState.Advanced)>
public class Project
end class
end namespace
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference>lib</ProjectReference>
<Document FilePath=""Program.cs"">
class Program
{
static void Main(string[] args)
{
[|Project|] p = new Project();
}
}
</Document>
</Project>
</Workspace>";
await TestMissingAsync(InitialWorkspace, new TestParameters(
options: Option(CompletionOptions.HideAdvancedMembers, true),
testHost: testHost));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Remote.Testing;
using Microsoft.CodeAnalysis.Tags;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
using static Roslyn.Test.Utilities.TestMetadata;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddUsing
{
[Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public partial class AddUsingTests : AbstractAddUsingTests
{
public AddUsingTests(ITestOutputHelper logger)
: base(logger)
{
}
[Theory]
[CombinatorialData]
public async Task TestTypeFromMultipleNamespaces1(TestHost testHost)
{
await TestAsync(
@"class Class
{
[|IDictionary|] Method()
{
Goo();
}
}",
@"using System.Collections;
class Class
{
IDictionary Method()
{
Goo();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestTypeFromMultipleNamespaces1_FileScopedNamespace_Outer(TestHost testHost)
{
await TestAsync(
@"
namespace N;
class Class
{
[|IDictionary|] Method()
{
Goo();
}
}",
@"
using System.Collections;
namespace N;
class Class
{
IDictionary Method()
{
Goo();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestTypeFromMultipleNamespaces1_FileScopedNamespace_Inner(TestHost testHost)
{
await TestAsync(
@"
namespace N;
using System;
class Class
{
[|IDictionary|] Method()
{
Goo();
}
}",
@"
namespace N;
using System;
using System.Collections;
class Class
{
IDictionary Method()
{
Goo();
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(11241, "https://github.com/dotnet/roslyn/issues/11241")]
public async Task TestAddImportWithCaseChange(TestHost testHost)
{
await TestAsync(
@"namespace N1
{
public class TextBox
{
}
}
class Class1 : [|Textbox|]
{
}",
@"using N1;
namespace N1
{
public class TextBox
{
}
}
class Class1 : TextBox
{
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestTypeFromMultipleNamespaces2(TestHost testHost)
{
await TestAsync(
@"class Class
{
[|IDictionary|] Method()
{
Goo();
}
}",
@"using System.Collections.Generic;
class Class
{
IDictionary Method()
{
Goo();
}
}",
testHost, index: 1);
}
[Theory]
[CombinatorialData]
public async Task TestGenericWithNoArgs(TestHost testHost)
{
await TestAsync(
@"class Class
{
[|List|] Method()
{
Goo();
}
}",
@"using System.Collections.Generic;
class Class
{
List Method()
{
Goo();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestGenericWithCorrectArgs(TestHost testHost)
{
await TestAsync(
@"class Class
{
[|List<int>|] Method()
{
Goo();
}
}",
@"using System.Collections.Generic;
class Class
{
List<int> Method()
{
Goo();
}
}", testHost);
}
[Fact]
public async Task TestGenericWithWrongArgs1()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|List<int, string, bool>|] Method()
{
Goo();
}
}");
}
[Fact]
public async Task TestGenericWithWrongArgs2()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|List<int, string>|] Method()
{
Goo();
}
}");
}
[Theory]
[CombinatorialData]
public async Task TestGenericInLocalDeclaration(TestHost testHost)
{
await TestAsync(
@"class Class
{
void Goo()
{
[|List<int>|] a = new List<int>();
}
}",
@"using System.Collections.Generic;
class Class
{
void Goo()
{
List<int> a = new List<int>();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestGenericItemType(TestHost testHost)
{
await TestAsync(
@"using System.Collections.Generic;
class Class
{
List<[|Int32|]> l;
}",
@"using System;
using System.Collections.Generic;
class Class
{
List<Int32> l;
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestGenerateWithExistingUsings(TestHost testHost)
{
await TestAsync(
@"using System;
class Class
{
[|List<int>|] Method()
{
Goo();
}
}",
@"using System;
using System.Collections.Generic;
class Class
{
List<int> Method()
{
Goo();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestGenerateInNamespace(TestHost testHost)
{
await TestAsync(
@"namespace N
{
class Class
{
[|List<int>|] Method()
{
Goo();
}
}
}",
@"using System.Collections.Generic;
namespace N
{
class Class
{
List<int> Method()
{
Goo();
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestGenerateInNamespaceWithUsings(TestHost testHost)
{
await TestAsync(
@"namespace N
{
using System;
class Class
{
[|List<int>|] Method()
{
Goo();
}
}
}",
@"namespace N
{
using System;
using System.Collections.Generic;
class Class
{
List<int> Method()
{
Goo();
}
}
}", testHost);
}
[Fact]
public async Task TestExistingUsing_ActionCount()
{
await TestActionCountAsync(
@"using System.Collections.Generic;
class Class
{
[|IDictionary|] Method()
{
Goo();
}
}",
count: 1);
}
[Theory]
[CombinatorialData]
public async Task TestExistingUsing(TestHost testHost)
{
await TestAsync(
@"using System.Collections.Generic;
class Class
{
[|IDictionary|] Method()
{
Goo();
}
}",
@"using System.Collections;
using System.Collections.Generic;
class Class
{
IDictionary Method()
{
Goo();
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(541730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541730")]
public async Task TestAddUsingForGenericExtensionMethod(TestHost testHost)
{
await TestAsync(
@"using System.Collections.Generic;
class Class
{
void Method(IList<int> args)
{
args.[|Where|]() }
}",
@"using System.Collections.Generic;
using System.Linq;
class Class
{
void Method(IList<int> args)
{
args.Where() }
}", testHost);
}
[Fact]
[WorkItem(541730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541730")]
public async Task TestAddUsingForNormalExtensionMethod()
{
await TestAsync(
@"class Class
{
void Method(Class args)
{
args.[|Where|]() }
}
namespace N
{
static class E
{
public static void Where(this Class c)
{
}
}
}",
@"using N;
class Class
{
void Method(Class args)
{
args.Where() }
}
namespace N
{
static class E
{
public static void Where(this Class c)
{
}
}
}",
parseOptions: Options.Regular);
}
[Theory]
[CombinatorialData]
public async Task TestOnEnum(TestHost testHost)
{
await TestAsync(
@"class Class
{
void Goo()
{
var a = [|Colors|].Red;
}
}
namespace A
{
enum Colors
{
Red,
Green,
Blue
}
}",
@"using A;
class Class
{
void Goo()
{
var a = Colors.Red;
}
}
namespace A
{
enum Colors
{
Red,
Green,
Blue
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestOnClassInheritance(TestHost testHost)
{
await TestAsync(
@"class Class : [|Class2|]
{
}
namespace A
{
class Class2
{
}
}",
@"using A;
class Class : Class2
{
}
namespace A
{
class Class2
{
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestOnImplementedInterface(TestHost testHost)
{
await TestAsync(
@"class Class : [|IGoo|]
{
}
namespace A
{
interface IGoo
{
}
}",
@"using A;
class Class : IGoo
{
}
namespace A
{
interface IGoo
{
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAllInBaseList(TestHost testHost)
{
await TestAsync(
@"class Class : [|IGoo|], Class2
{
}
namespace A
{
class Class2
{
}
}
namespace B
{
interface IGoo
{
}
}",
@"using B;
class Class : IGoo, Class2
{
}
namespace A
{
class Class2
{
}
}
namespace B
{
interface IGoo
{
}
}", testHost);
await TestAsync(
@"using B;
class Class : IGoo, [|Class2|]
{
}
namespace A
{
class Class2
{
}
}
namespace B
{
interface IGoo
{
}
}",
@"using A;
using B;
class Class : IGoo, Class2
{
}
namespace A
{
class Class2
{
}
}
namespace B
{
interface IGoo
{
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAttributeUnexpanded(TestHost testHost)
{
await TestAsync(
@"[[|Obsolete|]]
class Class
{
}",
@"using System;
[Obsolete]
class Class
{
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAttributeExpanded(TestHost testHost)
{
await TestAsync(
@"[[|ObsoleteAttribute|]]
class Class
{
}",
@"using System;
[ObsoleteAttribute]
class Class
{
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(538018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538018")]
public async Task TestAfterNew(TestHost testHost)
{
await TestAsync(
@"class Class
{
void Goo()
{
List<int> l;
l = new [|List<int>|]();
}
}",
@"using System.Collections.Generic;
class Class
{
void Goo()
{
List<int> l;
l = new List<int>();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestArgumentsInMethodCall(TestHost testHost)
{
await TestAsync(
@"class Class
{
void Test()
{
Console.WriteLine([|DateTime|].Today);
}
}",
@"using System;
class Class
{
void Test()
{
Console.WriteLine(DateTime.Today);
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestCallSiteArgs(TestHost testHost)
{
await TestAsync(
@"class Class
{
void Test([|DateTime|] dt)
{
}
}",
@"using System;
class Class
{
void Test(DateTime dt)
{
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestUsePartialClass(TestHost testHost)
{
await TestAsync(
@"namespace A
{
public class Class
{
[|PClass|] c;
}
}
namespace B
{
public partial class PClass
{
}
}",
@"using B;
namespace A
{
public class Class
{
PClass c;
}
}
namespace B
{
public partial class PClass
{
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestGenericClassInNestedNamespace(TestHost testHost)
{
await TestAsync(
@"namespace A
{
namespace B
{
class GenericClass<T>
{
}
}
}
namespace C
{
class Class
{
[|GenericClass<int>|] c;
}
}",
@"using A.B;
namespace A
{
namespace B
{
class GenericClass<T>
{
}
}
}
namespace C
{
class Class
{
GenericClass<int> c;
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(541730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541730")]
public async Task TestExtensionMethods(TestHost testHost)
{
await TestAsync(
@"using System.Collections.Generic;
class Goo
{
void Bar()
{
var values = new List<int>();
values.[|Where|](i => i > 1);
}
}",
@"using System.Collections.Generic;
using System.Linq;
class Goo
{
void Bar()
{
var values = new List<int>();
values.Where(i => i > 1);
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(541730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541730")]
public async Task TestQueryPatterns(TestHost testHost)
{
await TestAsync(
@"using System.Collections.Generic;
class Goo
{
void Bar()
{
var values = new List<int>();
var q = [|from v in values
where v > 1
select v + 10|];
}
}",
@"using System.Collections.Generic;
using System.Linq;
class Goo
{
void Bar()
{
var values = new List<int>();
var q = from v in values
where v > 1
select v + 10;
}
}", testHost);
}
// Tests for Insertion Order
[Theory]
[CombinatorialData]
public async Task TestSimplePresortedUsings1(TestHost testHost)
{
await TestAsync(
@"using B;
using C;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace D
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using B;
using C;
using D;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace D
{
class Goo
{
public static void Bar()
{
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimplePresortedUsings2(TestHost testHost)
{
await TestAsync(
@"using B;
using C;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using A;
using B;
using C;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleUnsortedUsings1(TestHost testHost)
{
await TestAsync(
@"using C;
using B;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using C;
using B;
using A;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleUnsortedUsings2(TestHost testHost)
{
await TestAsync(
@"using D;
using B;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace C
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using D;
using B;
using C;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace C
{
class Goo
{
public static void Bar()
{
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestMultiplePresortedUsings1(TestHost testHost)
{
await TestAsync(
@"using B.X;
using B.Y;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace B
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using B;
using B.X;
using B.Y;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace B
{
class Goo
{
public static void Bar()
{
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestMultiplePresortedUsings2(TestHost testHost)
{
await TestAsync(
@"using B.X;
using B.Y;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace B.A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using B.A;
using B.X;
using B.Y;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace B.A
{
class Goo
{
public static void Bar()
{
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestMultiplePresortedUsings3(TestHost testHost)
{
await TestAsync(
@"using B.X;
using B.Y;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace B
{
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}
}",
@"using B.A;
using B.X;
using B.Y;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace B
{
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestMultipleUnsortedUsings1(TestHost testHost)
{
await TestAsync(
@"using B.Y;
using B.X;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace B
{
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}
}",
@"using B.Y;
using B.X;
using B.A;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace B
{
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestMultipleUnsortedUsings2(TestHost testHost)
{
await TestAsync(
@"using B.Y;
using B.X;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace B
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using B.Y;
using B.X;
using B;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace B
{
class Goo
{
public static void Bar()
{
}
}
}", testHost);
}
// System on top cases
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemSortedUsings1(TestHost testHost)
{
await TestAsync(
@"using System;
using B;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using System;
using A;
using B;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemSortedUsings2(TestHost testHost)
{
await TestAsync(
@"using System;
using System.Collections.Generic;
using B;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using System;
using System.Collections.Generic;
using A;
using B;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemSortedUsings3(TestHost testHost)
{
await TestAsync(
@"using A;
using B;
class Class
{
void Method()
{
[|Console|].Write(1);
}
}",
@"using System;
using A;
using B;
class Class
{
void Method()
{
Console.Write(1);
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemUnsortedUsings1(TestHost testHost)
{
await TestAsync(
@"
using C;
using B;
using System;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"
using C;
using B;
using System;
using A;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemUnsortedUsings2(TestHost testHost)
{
await TestAsync(
@"using System.Collections.Generic;
using System;
using B;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using System.Collections.Generic;
using System;
using B;
using A;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemUnsortedUsings3(TestHost testHost)
{
await TestAsync(
@"using B;
using A;
class Class
{
void Method()
{
[|Console|].Write(1);
}
}",
@"using B;
using A;
using System;
class Class
{
void Method()
{
Console.Write(1);
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleBogusSystemUsings1(TestHost testHost)
{
await TestAsync(
@"using A.System;
class Class
{
void Method()
{
[|Console|].Write(1);
}
}",
@"using System;
using A.System;
class Class
{
void Method()
{
Console.Write(1);
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleBogusSystemUsings2(TestHost testHost)
{
await TestAsync(
@"using System.System;
class Class
{
void Method()
{
[|Console|].Write(1);
}
}",
@"using System;
using System.System;
class Class
{
void Method()
{
Console.Write(1);
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestUsingsWithComments(TestHost testHost)
{
await TestAsync(
@"using System./*...*/.Collections.Generic;
class Class
{
void Method()
{
[|Console|].Write(1);
}
}",
@"using System;
using System./*...*/.Collections.Generic;
class Class
{
void Method()
{
Console.Write(1);
}
}",
testHost);
}
// System Not on top cases
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemUnsortedUsings4(TestHost testHost)
{
await TestAsync(
@"
using C;
using System;
using B;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"
using C;
using System;
using B;
using A;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemSortedUsings5(TestHost testHost)
{
await TestAsync(
@"using B;
using System;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using A;
using B;
using System;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemSortedUsings4(TestHost testHost)
{
await TestAsync(
@"using A;
using B;
class Class
{
void Method()
{
[|Console|].Write(1);
}
}",
@"using A;
using B;
using System;
class Class
{
void Method()
{
Console.Write(1);
}
}",
testHost, options: Option(GenerationOptions.PlaceSystemNamespaceFirst, false));
}
[Fact]
[WorkItem(538136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538136")]
[WorkItem(538763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538763")]
public async Task TestAddUsingForNamespace()
{
await TestMissingInRegularAndScriptAsync(
@"namespace A
{
class Class
{
[|C|].Test t;
}
}
namespace B
{
namespace C
{
class Test
{
}
}
}");
}
[Theory]
[CombinatorialData]
[WorkItem(538220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538220")]
public async Task TestAddUsingForFieldWithFormatting(TestHost testHost)
{
await TestAsync(
@"class C { [|DateTime|] t; }",
@"using System;
class C { DateTime t; }", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(539657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539657")]
public async Task BugFix5688(TestHost testHost)
{
await TestAsync(
@"class Program { static void Main ( string [ ] args ) { [|Console|] . Out . NewLine = ""\r\n\r\n"" ; } } ",
@"using System;
class Program { static void Main ( string [ ] args ) { Console . Out . NewLine = ""\r\n\r\n"" ; } } ", testHost);
}
[Fact]
[WorkItem(539853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539853")]
public async Task BugFix5950()
{
await TestAsync(
@"using System.Console; WriteLine([|Expression|].Constant(123));",
@"using System.Console;
using System.Linq.Expressions;
WriteLine(Expression.Constant(123));",
parseOptions: GetScriptOptions());
}
[Theory]
[CombinatorialData]
[WorkItem(540339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540339")]
public async Task TestAddAfterDefineDirective1(TestHost testHost)
{
await TestAsync(
@"#define goo
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"#define goo
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(540339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540339")]
public async Task TestAddAfterDefineDirective2(TestHost testHost)
{
await TestAsync(
@"#define goo
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"#define goo
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddAfterDefineDirective3(TestHost testHost)
{
await TestAsync(
@"#define goo
/// Goo
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"#define goo
using System;
/// Goo
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddAfterDefineDirective4(TestHost testHost)
{
await TestAsync(
@"#define goo
// Goo
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"#define goo
// Goo
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddAfterExistingBanner(TestHost testHost)
{
await TestAsync(
@"// Banner
// Banner
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"// Banner
// Banner
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddAfterExternAlias1(TestHost testHost)
{
await TestAsync(
@"#define goo
extern alias Goo;
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"#define goo
extern alias Goo;
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddAfterExternAlias2(TestHost testHost)
{
await TestAsync(
@"#define goo
extern alias Goo;
using System.Collections;
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"#define goo
extern alias Goo;
using System;
using System.Collections;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}", testHost);
}
[Fact]
public async Task TestWithReferenceDirective()
{
var resolver = new TestMetadataReferenceResolver(assemblyNames: new Dictionary<string, PortableExecutableReference>()
{
{ "exprs", AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemCore).GetReference() }
});
await TestAsync(
@"#r ""exprs""
[|Expression|]",
@"#r ""exprs""
using System.Linq.Expressions;
Expression",
GetScriptOptions(),
TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver));
}
[Theory]
[CombinatorialData]
[WorkItem(542643, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542643")]
public async Task TestAssemblyAttribute(TestHost testHost)
{
await TestAsync(
@"[assembly: [|InternalsVisibleTo|](""Project"")]",
@"using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo(""Project"")]", testHost);
}
[Fact]
public async Task TestDoNotAddIntoHiddenRegion()
{
await TestMissingInRegularAndScriptAsync(
@"#line hidden
using System.Collections.Generic;
#line default
class Program
{
void Main()
{
[|DateTime|] d;
}
}");
}
[Theory]
[CombinatorialData]
public async Task TestAddToVisibleRegion(TestHost testHost)
{
await TestAsync(
@"#line default
using System.Collections.Generic;
#line hidden
class Program
{
void Main()
{
#line default
[|DateTime|] d;
#line hidden
}
}
#line default",
@"#line default
using System;
using System.Collections.Generic;
#line hidden
class Program
{
void Main()
{
#line default
DateTime d;
#line hidden
}
}
#line default", testHost);
}
[Fact]
[WorkItem(545248, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545248")]
public async Task TestVenusGeneration1()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void Goo()
{
#line 1 ""Default.aspx""
using (new [|StreamReader|]())
{
#line default
#line hidden
}
}");
}
[Fact]
[WorkItem(545774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545774")]
public async Task TestAttribute_ActionCount()
{
var input = @"[ assembly : [|Guid|] ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ";
await TestActionCountAsync(input, 2);
}
[Theory]
[CombinatorialData]
[WorkItem(545774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545774")]
public async Task TestAttribute(TestHost testHost)
{
var input = @"[ assembly : [|Guid|] ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ";
await TestAsync(
input,
@"using System.Runtime.InteropServices;
[ assembly : Guid ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ", testHost);
}
[Fact]
[WorkItem(546833, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546833")]
public async Task TestNotOnOverloadResolutionError()
{
await TestMissingInRegularAndScriptAsync(
@"namespace ConsoleApplication1
{
class Program
{
void Main()
{
var test = new [|Test|]("""");
}
}
class Test
{
}
}");
}
[Theory]
[CombinatorialData]
[WorkItem(17020, "DevDiv_Projects/Roslyn")]
public async Task TestAddUsingForGenericArgument(TestHost testHost)
{
await TestAsync(
@"namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
var inArgument = new InArgument<[|IEnumerable<int>|]>(new int[] { 1, 2, 3 });
}
}
public class InArgument<T>
{
public InArgument(T constValue)
{
}
}
}",
@"using System.Collections.Generic;
namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
var inArgument = new InArgument<IEnumerable<int>>(new int[] { 1, 2, 3 });
}
}
public class InArgument<T>
{
public InArgument(T constValue)
{
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(775448, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775448")]
public async Task ShouldTriggerOnCS0308(TestHost testHost)
{
// CS0308: The non-generic type 'A' cannot be used with type arguments
await TestAsync(
@"using System.Collections;
class Test
{
static void Main(string[] args)
{
[|IEnumerable<int>|] f;
}
}",
@"using System.Collections;
using System.Collections.Generic;
class Test
{
static void Main(string[] args)
{
IEnumerable<int> f;
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(838253, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/838253")]
public async Task TestConflictedInaccessibleType(TestHost testHost)
{
await TestAsync(
@"using System.Diagnostics;
namespace N
{
public class Log
{
}
}
class C
{
static void Main(string[] args)
{
[|Log|] }
}",
@"using System.Diagnostics;
using N;
namespace N
{
public class Log
{
}
}
class C
{
static void Main(string[] args)
{
Log }
}",
testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(858085, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858085")]
public async Task TestConflictedAttributeName(TestHost testHost)
{
await TestAsync(
@"[[|Description|]]
class Description
{
}",
@"using System.ComponentModel;
[Description]
class Description
{
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(872908, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/872908")]
public async Task TestConflictedGenericName(TestHost testHost)
{
await TestAsync(
@"using Task = System.AccessViolationException;
class X
{
[|Task<X> x;|]
}",
@"using System.Threading.Tasks;
using Task = System.AccessViolationException;
class X
{
Task<X> x;
}", testHost);
}
[Fact]
[WorkItem(913300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/913300")]
public async Task TestNoDuplicateReport_ActionCount()
{
await TestActionCountInAllFixesAsync(
@"class C
{
void M(P p)
{
[|Console|]
}
static void Main(string[] args)
{
}
}", count: 1);
}
[Theory]
[CombinatorialData]
[WorkItem(913300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/913300")]
public async Task TestNoDuplicateReport(TestHost testHost)
{
await TestAsync(
@"class C
{
void M(P p)
{
[|Console|] }
static void Main(string[] args)
{
}
}",
@"using System;
class C
{
void M(P p)
{
Console }
static void Main(string[] args)
{
}
}", testHost);
}
[Fact]
[WorkItem(938296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/938296")]
public async Task TestNullParentInNode()
{
await TestMissingInRegularAndScriptAsync(
@"using System.Collections.Generic;
class MultiDictionary<K, V> : Dictionary<K, HashSet<V>>
{
void M()
{
new HashSet<V>([|Comparer|]);
}
}");
}
[Fact]
[WorkItem(968303, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968303")]
public async Task TestMalformedUsingSection()
{
await TestMissingInRegularAndScriptAsync(
@"[ class Class
{
[|List<|] }");
}
[Theory]
[CombinatorialData]
[WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")]
public async Task TestAddUsingsWithExternAlias(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.cs"">
namespace ProjectLib
{
public class Project
{
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference Alias=""P"">lib</ProjectReference>
<Document FilePath=""Program.cs"">
namespace ExternAliases
{
class Program
{
static void Main(string[] args)
{
Project p = new [|Project()|];
}
}
}
</Document>
</Project>
</Workspace>";
const string ExpectedDocumentText = @"extern alias P;
using P::ProjectLib;
namespace ExternAliases
{
class Program
{
static void Main(string[] args)
{
Project p = new Project();
}
}
}
";
await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")]
public async Task TestAddUsingsWithPreExistingExternAlias(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.cs"">
namespace ProjectLib
{
public class Project
{
}
}
namespace AnotherNS
{
public class AnotherClass
{
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference Alias=""P"">lib</ProjectReference>
<Document FilePath=""Program.cs"">
extern alias P;
using P::ProjectLib;
namespace ExternAliases
{
class Program
{
static void Main(string[] args)
{
Project p = new Project();
var x = new [|AnotherClass()|];
}
}
}
</Document>
</Project>
</Workspace>";
const string ExpectedDocumentText = @"
extern alias P;
using P::AnotherNS;
using P::ProjectLib;
namespace ExternAliases
{
class Program
{
static void Main(string[] args)
{
Project p = new Project();
var x = new [|AnotherClass()|];
}
}
}
";
await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")]
public async Task TestAddUsingsWithPreExistingExternAlias_FileScopedNamespace(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.cs"">
namespace ProjectLib;
{
public class Project
{
}
}
namespace AnotherNS
{
public class AnotherClass
{
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference Alias=""P"">lib</ProjectReference>
<Document FilePath=""Program.cs"">
extern alias P;
using P::ProjectLib;
namespace ExternAliases;
class Program
{
static void Main(string[] args)
{
Project p = new Project();
var x = new [|AnotherClass()|];
}
}
</Document>
</Project>
</Workspace>";
const string ExpectedDocumentText = @"
extern alias P;
using P::AnotherNS;
using P::ProjectLib;
namespace ExternAliases;
class Program
{
static void Main(string[] args)
{
Project p = new Project();
var x = new [|AnotherClass()|];
}
}
";
await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")]
public async Task TestAddUsingsNoExtern(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.cs"">
namespace AnotherNS
{
public class AnotherClass
{
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference Alias=""P"">lib</ProjectReference>
<Document FilePath=""Program.cs"">
using P::AnotherNS;
namespace ExternAliases
{
class Program
{
static void Main(string[] args)
{
var x = new [|AnotherClass()|];
}
}
}
</Document>
</Project>
</Workspace>";
const string ExpectedDocumentText = @"extern alias P;
using P::AnotherNS;
namespace ExternAliases
{
class Program
{
static void Main(string[] args)
{
var x = new AnotherClass();
}
}
}
";
await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")]
public async Task TestAddUsingsNoExtern_FileScopedNamespace(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.cs"">
namespace AnotherNS;
public class AnotherClass
{
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference Alias=""P"">lib</ProjectReference>
<Document FilePath=""Program.cs"">
using P::AnotherNS;
namespace ExternAliases;
class Program
{
static void Main(string[] args)
{
var x = new [|AnotherClass()|];
}
}
</Document>
</Project>
</Workspace>";
const string ExpectedDocumentText = @"extern alias P;
using P::AnotherNS;
namespace ExternAliases;
class Program
{
static void Main(string[] args)
{
var x = new AnotherClass();
}
}
";
await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")]
public async Task TestAddUsingsNoExternFilterGlobalAlias(TestHost testHost)
{
await TestAsync(
@"class Program
{
static void Main(string[] args)
{
[|INotifyPropertyChanged.PropertyChanged|]
}
}",
@"using System.ComponentModel;
class Program
{
static void Main(string[] args)
{
INotifyPropertyChanged.PropertyChanged
}
}", testHost);
}
[Fact]
[WorkItem(916368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916368")]
public async Task TestAddUsingForCref()
{
var initialText =
@"/// <summary>
/// This is just like <see cref='[|INotifyPropertyChanged|]'/>, but this one is mine.
/// </summary>
interface MyNotifyPropertyChanged { }";
var expectedText =
@"using System.ComponentModel;
/// <summary>
/// This is just like <see cref='INotifyPropertyChanged'/>, but this one is mine.
/// </summary>
interface MyNotifyPropertyChanged { }";
var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose);
await TestAsync(initialText, expectedText, parseOptions: options);
}
[Fact]
[WorkItem(916368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916368")]
public async Task TestAddUsingForCref2()
{
var initialText =
@"/// <summary>
/// This is just like <see cref='[|INotifyPropertyChanged.PropertyChanged|]'/>, but this one is mine.
/// </summary>
interface MyNotifyPropertyChanged { }";
var expectedText =
@"using System.ComponentModel;
/// <summary>
/// This is just like <see cref='INotifyPropertyChanged.PropertyChanged'/>, but this one is mine.
/// </summary>
interface MyNotifyPropertyChanged { }";
var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose);
await TestAsync(initialText, expectedText, parseOptions: options);
}
[Fact]
[WorkItem(916368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916368")]
public async Task TestAddUsingForCref3()
{
var initialText =
@"namespace N1
{
public class D { }
}
public class MyClass
{
public static explicit operator N1.D (MyClass f)
{
return default(N1.D);
}
}
/// <seealso cref='MyClass.explicit operator [|D(MyClass)|]'/>
public class MyClass2
{
}";
var expectedText =
@"using N1;
namespace N1
{
public class D { }
}
public class MyClass
{
public static explicit operator N1.D (MyClass f)
{
return default(N1.D);
}
}
/// <seealso cref='MyClass.explicit operator D(MyClass)'/>
public class MyClass2
{
}";
var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose);
await TestAsync(initialText, expectedText, parseOptions: options);
}
[Fact]
[WorkItem(916368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916368")]
public async Task TestAddUsingForCref4()
{
var initialText =
@"namespace N1
{
public class D { }
}
/// <seealso cref='[|Test(D)|]'/>
public class MyClass
{
public void Test(N1.D i)
{
}
}";
var expectedText =
@"using N1;
namespace N1
{
public class D { }
}
/// <seealso cref='Test(D)'/>
public class MyClass
{
public void Test(N1.D i)
{
}
}";
var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose);
await TestAsync(initialText, expectedText, parseOptions: options);
}
[Theory]
[CombinatorialData]
[WorkItem(773614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773614")]
public async Task TestAddStaticType(TestHost testHost)
{
var initialText =
@"using System;
public static class Outer
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
[[|My|]]
class Test
{}";
var expectedText =
@"using System;
using static Outer;
public static class Outer
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
[My]
class Test
{}";
await TestAsync(initialText, expectedText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(773614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773614")]
public async Task TestAddStaticType2(TestHost testHost)
{
var initialText =
@"using System;
public static class Outer
{
public static class Inner
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
}
[[|My|]]
class Test
{}";
var expectedText =
@"using System;
using static Outer.Inner;
public static class Outer
{
public static class Inner
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
}
[My]
class Test
{}";
await TestAsync(initialText, expectedText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(773614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773614")]
public async Task TestAddStaticType3(TestHost testHost)
{
await TestAsync(
@"using System;
public static class Outer
{
public class Inner
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
}
[[|My|]]
class Test
{
}",
@"using System;
using static Outer.Inner;
public static class Outer
{
public class Inner
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
}
[My]
class Test
{
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(773614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773614")]
public async Task TestAddStaticType4(TestHost testHost)
{
var initialText =
@"using System;
using Outer;
public static class Outer
{
public static class Inner
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
}
[[|My|]]
class Test
{}";
var expectedText =
@"using System;
using Outer;
using static Outer.Inner;
public static class Outer
{
public static class Inner
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
}
[My]
class Test
{}";
await TestAsync(initialText, expectedText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")]
public async Task TestAddInsideUsingDirective1(TestHost testHost)
{
await TestAsync(
@"namespace ns
{
using B = [|Byte|];
}",
@"using System;
namespace ns
{
using B = Byte;
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")]
public async Task TestAddInsideUsingDirective2(TestHost testHost)
{
await TestAsync(
@"using System.Collections;
namespace ns
{
using B = [|Byte|];
}",
@"using System;
using System.Collections;
namespace ns
{
using B = Byte;
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")]
public async Task TestAddInsideUsingDirective3(TestHost testHost)
{
await TestAsync(
@"namespace ns2
{
namespace ns3
{
namespace ns
{
using B = [|Byte|];
namespace ns4
{
}
}
}
}",
@"using System;
namespace ns2
{
namespace ns3
{
namespace ns
{
using B = Byte;
namespace ns4
{
}
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")]
public async Task TestAddInsideUsingDirective4(TestHost testHost)
{
await TestAsync(
@"namespace ns2
{
using System.Collections;
namespace ns3
{
namespace ns
{
using System.IO;
using B = [|Byte|];
}
}
}",
@"namespace ns2
{
using System;
using System.Collections;
namespace ns3
{
namespace ns
{
using System.IO;
using B = Byte;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")]
public async Task TestAddInsideUsingDirective5(TestHost testHost)
{
await TestAsync(
@"using System.IO;
namespace ns2
{
using System.Diagnostics;
namespace ns3
{
using System.Collections;
namespace ns
{
using B = [|Byte|];
}
}
}",
@"using System.IO;
namespace ns2
{
using System.Diagnostics;
namespace ns3
{
using System;
using System.Collections;
namespace ns
{
using B = Byte;
}
}
}", testHost);
}
[Fact]
[WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")]
public async Task TestAddInsideUsingDirective6()
{
await TestMissingInRegularAndScriptAsync(
@"using B = [|Byte|];");
}
[Theory]
[CombinatorialData]
[WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")]
public async Task TestAddConditionalAccessExpression(TestHost testHost)
{
var initialText =
@"<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<Document FilePath = ""Program"">
public class C
{
void Main(C a)
{
C x = a?[|.B()|];
}
}
</Document>
<Document FilePath = ""Extensions"">
namespace Extensions
{
public static class E
{
public static C B(this C c) { return c; }
}
}
</Document>
</Project>
</Workspace> ";
var expectedText =
@"
using Extensions;
public class C
{
void Main(C a)
{
C x = a?.B();
}
}
";
await TestAsync(initialText, expectedText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")]
public async Task TestAddConditionalAccessExpression2(TestHost testHost)
{
var initialText =
@"<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<Document FilePath = ""Program"">
public class C
{
public E B { get; private set; }
void Main(C a)
{
int? x = a?.B.[|C()|];
}
public class E
{
}
}
</Document>
<Document FilePath = ""Extensions"">
namespace Extensions
{
public static class D
{
public static C.E C(this C.E c) { return c; }
}
}
</Document>
</Project>
</Workspace> ";
var expectedText =
@"
using Extensions;
public class C
{
public E B { get; private set; }
void Main(C a)
{
int? x = a?.B.C();
}
public class E
{
}
}
";
await TestAsync(initialText, expectedText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1089138, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1089138")]
public async Task TestAmbiguousUsingName(TestHost testHost)
{
await TestAsync(
@"namespace ClassLibrary1
{
using System;
public class SomeTypeUser
{
[|SomeType|] field;
}
}
namespace SubNamespaceName
{
using System;
class SomeType
{
}
}
namespace ClassLibrary1.SubNamespaceName
{
using System;
class SomeOtherFile
{
}
}",
@"namespace ClassLibrary1
{
using System;
using global::SubNamespaceName;
public class SomeTypeUser
{
SomeType field;
}
}
namespace SubNamespaceName
{
using System;
class SomeType
{
}
}
namespace ClassLibrary1.SubNamespaceName
{
using System;
class SomeOtherFile
{
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingInDirective(TestHost testHost)
{
await TestAsync(
@"#define DEBUG
#if DEBUG
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text;
#endif
class Program
{
static void Main(string[] args)
{
var a = [|File|].OpenRead("""");
}
}",
@"#define DEBUG
#if DEBUG
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text;
using System.IO;
#endif
class Program
{
static void Main(string[] args)
{
var a = File.OpenRead("""");
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingInDirective2(TestHost testHost)
{
await TestAsync(
@"#define DEBUG
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
#if DEBUG
using System.Text;
#endif
class Program { static void Main ( string [ ] args ) { var a = [|File|] . OpenRead ( """" ) ; } } ",
@"#define DEBUG
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
#if DEBUG
using System.Text;
#endif
class Program { static void Main ( string [ ] args ) { var a = File . OpenRead ( """" ) ; } } ", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingInDirective3(TestHost testHost)
{
await TestAsync(
@"#define DEBUG
using System;
using System.Collections.Generic;
#if DEBUG
using System.Text;
#endif
using System.Linq;
using System.Threading.Tasks;
class Program { static void Main ( string [ ] args ) { var a = [|File|] . OpenRead ( """" ) ; } } ",
@"#define DEBUG
using System;
using System.Collections.Generic;
#if DEBUG
using System.Text;
#endif
using System.Linq;
using System.Threading.Tasks;
using System.IO;
class Program { static void Main ( string [ ] args ) { var a = File . OpenRead ( """" ) ; } } ", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingInDirective4(TestHost testHost)
{
await TestAsync(
@"#define DEBUG
#if DEBUG
using System;
#endif
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
class Program { static void Main ( string [ ] args ) { var a = [|File|] . OpenRead ( """" ) ; } } ",
@"#define DEBUG
#if DEBUG
using System;
#endif
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
class Program { static void Main ( string [ ] args ) { var a = File . OpenRead ( """" ) ; } } ", testHost);
}
[Fact]
public async Task TestInaccessibleExtensionMethod()
{
const string initial = @"
namespace N1
{
public static class C
{
private static bool ExtMethod1(this string arg1)
{
return true;
}
}
}
namespace N2
{
class Program
{
static void Main(string[] args)
{
var x = ""str1"".[|ExtMethod1()|];
}
}
}";
await TestMissingInRegularAndScriptAsync(initial);
}
[Theory]
[CombinatorialData]
[WorkItem(1116011, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1116011")]
public async Task TestAddUsingForProperty(TestHost testHost)
{
await TestAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
public BindingFlags BindingFlags
{
get
{
return BindingFlags.[|Instance|];
}
}
}",
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
class Program
{
public BindingFlags BindingFlags
{
get
{
return BindingFlags.Instance;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1116011, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1116011")]
public async Task TestAddUsingForField(TestHost testHost)
{
await TestAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
public B B
{
get
{
return B.[|Instance|];
}
}
}
namespace A
{
public class B
{
public static readonly B Instance;
}
}",
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using A;
class Program
{
public B B
{
get
{
return B.Instance;
}
}
}
namespace A
{
public class B
{
public static readonly B Instance;
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1893, "https://github.com/dotnet/roslyn/issues/1893")]
public async Task TestNameSimplification(TestHost testHost)
{
// Generated using directive must be simplified from "using A.B;" to "using B;" below.
await TestAsync(
@"namespace A.B
{
class T1
{
}
}
namespace A.C
{
using System;
class T2
{
void Test()
{
Console.WriteLine();
[|T1|] t1;
}
}
}",
@"namespace A.B
{
class T1
{
}
}
namespace A.C
{
using System;
using A.B;
class T2
{
void Test()
{
Console.WriteLine();
T1 t1;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(935, "https://github.com/dotnet/roslyn/issues/935")]
public async Task TestAddUsingWithOtherExtensionsInScope(TestHost testHost)
{
await TestAsync(
@"using System.Linq;
using System.Collections;
using X;
namespace X
{
public static class Ext
{
public static void ExtMethod(this int a)
{
}
}
}
namespace Y
{
public static class Ext
{
public static void ExtMethod(this int a, int v)
{
}
}
}
public class B
{
static void Main()
{
var b = 0;
b.[|ExtMethod|](0);
}
}",
@"using System.Linq;
using System.Collections;
using X;
using Y;
namespace X
{
public static class Ext
{
public static void ExtMethod(this int a)
{
}
}
}
namespace Y
{
public static class Ext
{
public static void ExtMethod(this int a, int v)
{
}
}
}
public class B
{
static void Main()
{
var b = 0;
b.ExtMethod(0);
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(935, "https://github.com/dotnet/roslyn/issues/935")]
public async Task TestAddUsingWithOtherExtensionsInScope2(TestHost testHost)
{
await TestAsync(
@"using System.Linq;
using System.Collections;
using X;
namespace X
{
public static class Ext
{
public static void ExtMethod(this int? a)
{
}
}
}
namespace Y
{
public static class Ext
{
public static void ExtMethod(this int? a, int v)
{
}
}
}
public class B
{
static void Main()
{
var b = new int?();
b?[|.ExtMethod|](0);
}
}",
@"using System.Linq;
using System.Collections;
using X;
using Y;
namespace X
{
public static class Ext
{
public static void ExtMethod(this int? a)
{
}
}
}
namespace Y
{
public static class Ext
{
public static void ExtMethod(this int? a, int v)
{
}
}
}
public class B
{
static void Main()
{
var b = new int?();
b?.ExtMethod(0);
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(562, "https://github.com/dotnet/roslyn/issues/562")]
public async Task TestAddUsingWithOtherExtensionsInScope3(TestHost testHost)
{
await TestAsync(
@"using System.Linq;
class C
{
int i = 0.[|All|]();
}
namespace X
{
static class E
{
public static int All(this int o) => 0;
}
}",
@"using System.Linq;
using X;
class C
{
int i = 0.All();
}
namespace X
{
static class E
{
public static int All(this int o) => 0;
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(562, "https://github.com/dotnet/roslyn/issues/562")]
public async Task TestAddUsingWithOtherExtensionsInScope4(TestHost testHost)
{
await TestAsync(
@"using System.Linq;
class C
{
static void Main(string[] args)
{
var a = new int?();
int? i = a?[|.All|]();
}
}
namespace X
{
static class E
{
public static int? All(this int? o) => 0;
}
}",
@"using System.Linq;
using X;
class C
{
static void Main(string[] args)
{
var a = new int?();
int? i = a?.All();
}
}
namespace X
{
static class E
{
public static int? All(this int? o) => 0;
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")]
public async Task TestNestedNamespaceSimplified(TestHost testHost)
{
await TestAsync(
@"namespace Microsoft.MyApp
{
using Win32;
class Program
{
static void Main(string[] args)
{
[|SafeRegistryHandle|] h;
}
}
}",
@"namespace Microsoft.MyApp
{
using Microsoft.Win32.SafeHandles;
using Win32;
class Program
{
static void Main(string[] args)
{
SafeRegistryHandle h;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")]
public async Task TestNestedNamespaceSimplified2(TestHost testHost)
{
await TestAsync(
@"namespace Microsoft.MyApp
{
using Zin32;
class Program
{
static void Main(string[] args)
{
[|SafeRegistryHandle|] h;
}
}
}",
@"namespace Microsoft.MyApp
{
using Microsoft.Win32.SafeHandles;
using Zin32;
class Program
{
static void Main(string[] args)
{
SafeRegistryHandle h;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")]
public async Task TestNestedNamespaceSimplified3(TestHost testHost)
{
await TestAsync(
@"namespace Microsoft.MyApp
{
using System;
using Win32;
class Program
{
static void Main(string[] args)
{
[|SafeRegistryHandle|] h;
}
}
}",
@"namespace Microsoft.MyApp
{
using System;
using Microsoft.Win32.SafeHandles;
using Win32;
class Program
{
static void Main(string[] args)
{
SafeRegistryHandle h;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")]
public async Task TestNestedNamespaceSimplified4(TestHost testHost)
{
await TestAsync(
@"namespace Microsoft.MyApp
{
using System;
using Zin32;
class Program
{
static void Main(string[] args)
{
[|SafeRegistryHandle|] h;
}
}
}",
@"namespace Microsoft.MyApp
{
using System;
using Microsoft.Win32.SafeHandles;
using Zin32;
class Program
{
static void Main(string[] args)
{
SafeRegistryHandle h;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")]
public async Task TestNestedNamespaceSimplified5(TestHost testHost)
{
await TestAsync(
@"namespace Microsoft.MyApp
{
#if true
using Win32;
#else
using System;
#endif
class Program
{
static void Main(string[] args)
{
[|SafeRegistryHandle|] h;
}
}
}",
@"namespace Microsoft.MyApp
{
using Microsoft.Win32.SafeHandles;
#if true
using Win32;
#else
using System;
#endif
class Program
{
static void Main(string[] args)
{
SafeRegistryHandle h;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")]
public async Task TestNestedNamespaceSimplified6(TestHost testHost)
{
await TestAsync(
@"namespace Microsoft.MyApp
{
using System;
#if false
using Win32;
#endif
using Win32;
class Program
{
static void Main(string[] args)
{
[|SafeRegistryHandle|] h;
}
}
}",
@"namespace Microsoft.MyApp
{
using System;
using Microsoft.Win32.SafeHandles;
#if false
using Win32;
#endif
using Win32;
class Program
{
static void Main(string[] args)
{
SafeRegistryHandle h;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingOrdinalUppercase(TestHost testHost)
{
await TestAsync(
@"namespace A
{
class A
{
static void Main(string[] args)
{
var b = new [|B|]();
}
}
}
namespace lowercase
{
class b
{
}
}
namespace Uppercase
{
class B
{
}
}",
@"using Uppercase;
namespace A
{
class A
{
static void Main(string[] args)
{
var b = new B();
}
}
}
namespace lowercase
{
class b
{
}
}
namespace Uppercase
{
class B
{
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingOrdinalLowercase(TestHost testHost)
{
await TestAsync(
@"namespace A
{
class A
{
static void Main(string[] args)
{
var a = new [|b|]();
}
}
}
namespace lowercase
{
class b
{
}
}
namespace Uppercase
{
class B
{
}
}",
@"using lowercase;
namespace A
{
class A
{
static void Main(string[] args)
{
var a = new b();
}
}
}
namespace lowercase
{
class b
{
}
}
namespace Uppercase
{
class B
{
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(7443, "https://github.com/dotnet/roslyn/issues/7443")]
public async Task TestWithExistingIncompatibleExtension(TestHost testHost)
{
await TestAsync(
@"using N;
class C
{
int x()
{
System.Collections.Generic.IEnumerable<int> x = null;
return x.[|Any|]
}
}
namespace N
{
static class Extensions
{
public static void Any(this string s)
{
}
}
}",
@"using System.Linq;
using N;
class C
{
int x()
{
System.Collections.Generic.IEnumerable<int> x = null;
return x.Any
}
}
namespace N
{
static class Extensions
{
public static void Any(this string s)
{
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1744, @"https://github.com/dotnet/roslyn/issues/1744")]
public async Task TestIncompleteCatchBlockInLambda(TestHost testHost)
{
await TestAsync(
@"class A
{
System.Action a = () => {
try
{
}
catch ([|Exception|]",
@"using System;
class A
{
System.Action a = () => {
try
{
}
catch (Exception", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1033612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033612")]
public async Task TestAddInsideLambda(TestHost testHost)
{
var initialText =
@"using System;
static void Main(string[] args)
{
Func<int> f = () => { [|List<int>|]. }
}";
var expectedText =
@"using System;
using System.Collections.Generic;
static void Main(string[] args)
{
Func<int> f = () => { List<int>. }
}";
await TestAsync(initialText, expectedText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1033612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033612")]
public async Task TestAddInsideLambda2(TestHost testHost)
{
var initialText =
@"using System;
static void Main(string[] args)
{
Func<int> f = () => { [|List<int>|] }
}";
var expectedText =
@"using System;
using System.Collections.Generic;
static void Main(string[] args)
{
Func<int> f = () => { List<int> }
}";
await TestAsync(initialText, expectedText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1033612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033612")]
public async Task TestAddInsideLambda3(TestHost testHost)
{
var initialText =
@"using System;
static void Main(string[] args)
{
Func<int> f = () => {
var a = 3;
[|List<int>|].
return a;
};
}";
var expectedText =
@"using System;
using System.Collections.Generic;
static void Main(string[] args)
{
Func<int> f = () => {
var a = 3;
List<int>.
return a;
};
}";
await TestAsync(initialText, expectedText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1033612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033612")]
public async Task TestAddInsideLambda4(TestHost testHost)
{
var initialText =
@"using System;
static void Main(string[] args)
{
Func<int> f = () => {
var a = 3;
[|List<int>|]
return a;
};
}";
var expectedText =
@"using System;
using System.Collections.Generic;
static void Main(string[] args)
{
Func<int> f = () => {
var a = 3;
List<int>
return a;
};
}";
await TestAsync(initialText, expectedText, testHost);
}
[WorkItem(860648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/860648")]
[Theory]
[CombinatorialData]
[WorkItem(902014, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/902014")]
public async Task TestIncompleteParenthesizedLambdaExpression(TestHost testHost)
{
await TestAsync(
@"using System;
class Test
{
void Goo()
{
Action a = () => {
[|IBindCtx|] };
string a;
}
}",
@"using System;
using System.Runtime.InteropServices.ComTypes;
class Test
{
void Goo()
{
Action a = () => {
IBindCtx };
string a;
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(7461, "https://github.com/dotnet/roslyn/issues/7461")]
public async Task TestExtensionWithIncompatibleInstance(TestHost testHost)
{
await TestAsync(
@"using System.IO;
namespace Namespace1
{
static class StreamExtensions
{
public static void Write(this Stream stream, byte[] bytes)
{
}
}
}
namespace Namespace2
{
class Goo
{
void Bar()
{
Stream stream = null;
stream.[|Write|](new byte[] { 1, 2, 3 });
}
}
}",
@"using System.IO;
using Namespace1;
namespace Namespace1
{
static class StreamExtensions
{
public static void Write(this Stream stream, byte[] bytes)
{
}
}
}
namespace Namespace2
{
class Goo
{
void Bar()
{
Stream stream = null;
stream.Write(new byte[] { 1, 2, 3 });
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(5499, "https://github.com/dotnet/roslyn/issues/5499")]
public async Task TestFormattingForNamespaceUsings(TestHost testHost)
{
await TestAsync(
@"namespace N
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Program
{
void Main()
{
[|Task<int>|]
}
}
}",
@"namespace N
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Program
{
void Main()
{
Task<int>
}
}
}", testHost);
}
[Fact]
public async Task TestGenericAmbiguityInSameNamespace()
{
await TestMissingInRegularAndScriptAsync(
@"namespace NS
{
class C<T> where T : [|C|].N
{
public class N
{
}
}
}");
}
[Fact]
public async Task TestNotOnVar1()
{
await TestMissingInRegularAndScriptAsync(
@"namespace N
{
class var { }
}
class C
{
void M()
{
[|var|]
}
}
");
}
[Fact]
public async Task TestNotOnVar2()
{
await TestMissingInRegularAndScriptAsync(
@"namespace N
{
class Bar { }
}
class C
{
void M()
{
[|var|]
}
}
");
}
[Theory]
[CombinatorialData]
[WorkItem(226826, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=226826")]
public async Task TestAddUsingWithLeadingDocCommentInFrontOfUsing1(TestHost testHost)
{
await TestAsync(
@"
/// Copyright 2016 - MyCompany
/// All Rights Reserved
using System;
class C : [|IEnumerable|]<int>
{
}
",
@"
/// Copyright 2016 - MyCompany
/// All Rights Reserved
using System;
using System.Collections.Generic;
class C : IEnumerable<int>
{
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(226826, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=226826")]
public async Task TestAddUsingWithLeadingDocCommentInFrontOfUsing2(TestHost testHost)
{
await TestAsync(
@"
/// Copyright 2016 - MyCompany
/// All Rights Reserved
using System.Collections;
class C
{
[|DateTime|] d;
}
",
@"
/// Copyright 2016 - MyCompany
/// All Rights Reserved
using System;
using System.Collections;
class C
{
DateTime d;
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(226826, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=226826")]
public async Task TestAddUsingWithLeadingDocCommentInFrontOfClass1(TestHost testHost)
{
await TestAsync(
@"
/// Copyright 2016 - MyCompany
/// All Rights Reserved
class C
{
[|DateTime|] d;
}
",
@"
using System;
/// Copyright 2016 - MyCompany
/// All Rights Reserved
class C
{
DateTime d;
}
", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestPlaceUsingWithUsings_NotWithAliases(TestHost testHost)
{
await TestAsync(
@"
using System;
namespace N
{
using C = System.Collections;
class Class
{
[|List<int>|] Method()
{
Goo();
}
}
}",
@"
using System;
using System.Collections.Generic;
namespace N
{
using C = System.Collections;
class Class
{
List<int> Method()
{
Goo();
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(15025, "https://github.com/dotnet/roslyn/issues/15025")]
public async Task TestPreferSystemNamespaceFirst(TestHost testHost)
{
await TestAsync(
@"
namespace Microsoft
{
public class SomeClass { }
}
namespace System
{
public class SomeClass { }
}
namespace N
{
class Class
{
[|SomeClass|] c;
}
}",
@"
using System;
namespace Microsoft
{
public class SomeClass { }
}
namespace System
{
public class SomeClass { }
}
namespace N
{
class Class
{
SomeClass c;
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(15025, "https://github.com/dotnet/roslyn/issues/15025")]
public async Task TestPreferSystemNamespaceFirst2(TestHost testHost)
{
await TestAsync(
@"
namespace Microsoft
{
public class SomeClass { }
}
namespace System
{
public class SomeClass { }
}
namespace N
{
class Class
{
[|SomeClass|] c;
}
}",
@"
using Microsoft;
namespace Microsoft
{
public class SomeClass { }
}
namespace System
{
public class SomeClass { }
}
namespace N
{
class Class
{
SomeClass c;
}
}", testHost, index: 1);
}
[Fact]
[WorkItem(18275, "https://github.com/dotnet/roslyn/issues/18275")]
public async Task TestContextualKeyword1()
{
await TestMissingInRegularAndScriptAsync(
@"
namespace N
{
class nameof
{
}
}
class C
{
void M()
{
[|nameof|]
}
}");
}
[Theory]
[CombinatorialData]
[WorkItem(19218, "https://github.com/dotnet/roslyn/issues/19218")]
public async Task TestChangeCaseWithUsingsInNestedNamespace(TestHost testHost)
{
await TestAsync(
@"namespace VS
{
interface IVsStatusbar
{
}
}
namespace Outer
{
using System;
class C
{
void M()
{
// Note: IVsStatusBar is cased incorrectly.
[|IVsStatusBar|] b;
}
}
}
",
@"namespace VS
{
interface IVsStatusbar
{
}
}
namespace Outer
{
using System;
using VS;
class C
{
void M()
{
// Note: IVsStatusBar is cased incorrectly.
IVsStatusbar b;
}
}
}
", testHost);
}
[Fact]
[WorkItem(19575, "https://github.com/dotnet/roslyn/issues/19575")]
public async Task TestNoNonGenericsWithGenericCodeParsedAsExpression()
{
var code = @"
class C
{
private void GetEvaluationRuleNames()
{
[|IEnumerable|] < Int32 >
return ImmutableArray.CreateRange();
}
}";
await TestActionCountAsync(code, count: 1);
await TestInRegularAndScriptAsync(
code,
@"
using System.Collections.Generic;
class C
{
private void GetEvaluationRuleNames()
{
IEnumerable < Int32 >
return ImmutableArray.CreateRange();
}
}");
}
[Theory]
[CombinatorialData]
[WorkItem(19796, "https://github.com/dotnet/roslyn/issues/19796")]
public async Task TestWhenInRome1(TestHost testHost)
{
// System is set to be sorted first, but the actual file shows it at the end.
// Keep things sorted, but respect that 'System' is at the end.
await TestAsync(
@"
using B;
using System;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"
using A;
using B;
using System;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(19796, "https://github.com/dotnet/roslyn/issues/19796")]
public async Task TestWhenInRome2(TestHost testHost)
{
// System is set to not be sorted first, but the actual file shows it sorted first.
// Keep things sorted, but respect that 'System' is at the beginning.
await TestAsync(
@"
using System;
using B;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"
using System;
using A;
using B;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}", testHost);
}
[Fact]
public async Task TestExactMatchNoGlyph()
{
await TestSmartTagGlyphTagsAsync(
@"namespace VS
{
interface Other
{
}
}
class C
{
void M()
{
[|Other|] b;
}
}
", ImmutableArray<string>.Empty);
}
[Fact]
public async Task TestFuzzyMatchGlyph()
{
await TestSmartTagGlyphTagsAsync(
@"namespace VS
{
interface Other
{
}
}
class C
{
void M()
{
[|Otter|] b;
}
}
", WellKnownTagArrays.Namespace);
}
[Theory]
[CombinatorialData]
[WorkItem(29313, "https://github.com/dotnet/roslyn/issues/29313")]
public async Task TestGetAwaiterExtensionMethod1(TestHost testHost)
{
await TestAsync(
@"
namespace A
{
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class C
{
async Task M() => await [|Goo|];
C Goo { get; set; }
}
}
namespace B
{
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using A;
static class Extensions
{
public static Awaiter GetAwaiter(this C scheduler) => null;
public class Awaiter : INotifyCompletion
{
public object GetResult() => null;
public void OnCompleted(Action continuation) { }
public bool IsCompleted => true;
}
}
}",
@"
namespace A
{
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using B;
class C
{
async Task M() => await Goo;
C Goo { get; set; }
}
}
namespace B
{
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using A;
static class Extensions
{
public static Awaiter GetAwaiter(this C scheduler) => null;
public class Awaiter : INotifyCompletion
{
public object GetResult() => null;
public void OnCompleted(Action continuation) { }
public bool IsCompleted => true;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(29313, "https://github.com/dotnet/roslyn/issues/29313")]
public async Task TestGetAwaiterExtensionMethod2(TestHost testHost)
{
await TestAsync(
@"
namespace A
{
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class C
{
async Task M() => await [|GetC|]();
C GetC() => null;
}
}
namespace B
{
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using A;
static class Extensions
{
public static Awaiter GetAwaiter(this C scheduler) => null;
public class Awaiter : INotifyCompletion
{
public object GetResult() => null;
public void OnCompleted(Action continuation) { }
public bool IsCompleted => true;
}
}
}",
@"
namespace A
{
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using B;
class C
{
async Task M() => await GetC();
C GetC() => null;
}
}
namespace B
{
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using A;
static class Extensions
{
public static Awaiter GetAwaiter(this C scheduler) => null;
public class Awaiter : INotifyCompletion
{
public object GetResult() => null;
public void OnCompleted(Action continuation) { }
public bool IsCompleted => true;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(745490, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/745490")]
public async Task TestAddUsingForAwaitableReturningExtensionMethod(TestHost testHost)
{
await TestAsync(
@"
namespace A
{
using System;
using System.Threading.Tasks;
class C
{
C Instance { get; }
async Task M() => await Instance.[|Foo|]();
}
}
namespace B
{
using System;
using System.Threading.Tasks;
using A;
static class Extensions
{
public static Task Foo(this C instance) => null;
}
}",
@"
namespace A
{
using System;
using System.Threading.Tasks;
using B;
class C
{
C Instance { get; }
async Task M() => await Instance.Foo();
}
}
namespace B
{
using System;
using System.Threading.Tasks;
using A;
static class Extensions
{
public static Task Foo(this C instance) => null;
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingForExtensionGetEnumeratorReturningIEnumerator(TestHost testHost)
{
await TestAsync(
@"
namespace A
{
class C
{
C Instance { get; }
void M() { foreach (var i in [|Instance|]); }
}
}
namespace B
{
using A;
using System.Collections.Generic;
static class Extensions
{
public static IEnumerator<int> GetEnumerator(this C instance) => null;
}
}",
@"
using B;
namespace A
{
class C
{
C Instance { get; }
void M() { foreach (var i in Instance); }
}
}
namespace B
{
using A;
using System.Collections.Generic;
static class Extensions
{
public static IEnumerator<int> GetEnumerator(this C instance) => null;
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingForExtensionGetEnumeratorReturningPatternEnumerator(TestHost testHost)
{
await TestAsync(
@"
namespace A
{
class C
{
C Instance { get; }
void M() { foreach (var i in [|Instance|]); }
}
}
namespace B
{
using A;
static class Extensions
{
public static Enumerator GetEnumerator(this C instance) => null;
}
public class Enumerator
{
public int Current { get; }
public bool MoveNext();
}
}",
@"
using B;
namespace A
{
class C
{
C Instance { get; }
void M() { foreach (var i in Instance); }
}
}
namespace B
{
using A;
static class Extensions
{
public static Enumerator GetEnumerator(this C instance) => null;
}
public class Enumerator
{
public int Current { get; }
public bool MoveNext();
}
}", testHost);
}
[Fact]
public async Task TestMissingForExtensionInvalidGetEnumerator()
{
await TestMissingAsync(
@"
namespace A
{
class C
{
C Instance { get; }
void M() { foreach (var i in [|Instance|]); }
}
}
namespace B
{
using A;
static class Extensions
{
public static bool GetEnumerator(this C instance) => null;
}
}");
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingForExtensionGetEnumeratorReturningPatternEnumeratorWrongAsync(TestHost testHost)
{
await TestAsync(
@"
namespace A
{
class C
{
C Instance { get; };
void M() { foreach (var i in [|Instance|]); }
public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default)
{
return new Enumerator();
}
public sealed class Enumerator
{
public async System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null;
public int Current => throw null;
}
}
}
namespace B
{
using A;
static class Extensions
{
public static Enumerator GetEnumerator(this C instance) => null;
}
public class Enumerator
{
public int Current { get; }
public bool MoveNext();
}
}",
@"
using B;
namespace A
{
class C
{
C Instance { get; };
void M() { foreach (var i in Instance); }
public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default)
{
return new Enumerator();
}
public sealed class Enumerator
{
public async System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null;
public int Current => throw null;
}
}
}
namespace B
{
using A;
static class Extensions
{
public static Enumerator GetEnumerator(this C instance) => null;
}
public class Enumerator
{
public int Current { get; }
public bool MoveNext();
}
}", testHost);
}
[Fact]
public async Task TestMissingForExtensionGetAsyncEnumeratorOnForeach()
{
await TestMissingAsync(
@"
namespace A
{
class C
{
C Instance { get; }
void M() { foreach (var i in [|Instance|]); }
}
}
namespace B
{
using A;
using System.Collections.Generic;
static class Extensions
{
public static IAsyncEnumerator<int> GetAsyncEnumerator(this C instance) => null;
}
}" + IAsyncEnumerable);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingForExtensionGetAsyncEnumeratorReturningIAsyncEnumerator(TestHost testHost)
{
await TestAsync(
@"
using System.Threading.Tasks;
namespace A
{
class C
{
C Instance { get; }
async Task M() { await foreach (var i in [|Instance|]); }
}
}
namespace B
{
using A;
using System.Collections.Generic;
static class Extensions
{
public static IAsyncEnumerator<int> GetAsyncEnumerator(this C instance) => null;
}
}" + IAsyncEnumerable,
@"
using System.Threading.Tasks;
using B;
namespace A
{
class C
{
C Instance { get; }
async Task M() { await foreach (var i in Instance); }
}
}
namespace B
{
using A;
using System.Collections.Generic;
static class Extensions
{
public static IAsyncEnumerator<int> GetAsyncEnumerator(this C instance) => null;
}
}" + IAsyncEnumerable, testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingForExtensionGetAsyncEnumeratorReturningPatternEnumerator(TestHost testHost)
{
await TestAsync(
@"
using System.Threading.Tasks;
namespace A
{
class C
{
C Instance { get; }
async Task M() { await foreach (var i in [|Instance|]); }
}
}
namespace B
{
using A;
static class Extensions
{
public static Enumerator GetAsyncEnumerator(this C instance) => null;
}
public class Enumerator
{
public int Current { get; }
public Task<bool> MoveNextAsync();
}
}",
@"
using System.Threading.Tasks;
using B;
namespace A
{
class C
{
C Instance { get; }
async Task M() { await foreach (var i in Instance); }
}
}
namespace B
{
using A;
static class Extensions
{
public static Enumerator GetAsyncEnumerator(this C instance) => null;
}
public class Enumerator
{
public int Current { get; }
public Task<bool> MoveNextAsync();
}
}", testHost);
}
[Fact]
public async Task TestMissingForExtensionInvalidGetAsyncEnumerator()
{
await TestMissingAsync(
@"
using System.Threading.Tasks;
namespace A
{
class C
{
C Instance { get; }
async Task M() { await foreach (var i in [|Instance|]); }
}
}
namespace B
{
using A;
static class Extensions
{
public static bool GetAsyncEnumerator(this C instance) => null;
}
}");
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingForExtensionGetAsyncEnumeratorReturningPatternEnumeratorWrongAsync(TestHost testHost)
{
await TestAsync(
@"
using System.Threading.Tasks;
namespace A
{
class C
{
C Instance { get; }
Task M() { await foreach (var i in [|Instance|]); }
public Enumerator GetEnumerator()
{
return new Enumerator();
}
public class Enumerator
{
public int Current { get; }
public bool MoveNext();
}
}
}
namespace B
{
using A;
static class Extensions
{
public static Enumerator GetAsyncEnumerator(this C instance) => null;
}
public sealed class Enumerator
{
public async System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null;
public int Current => throw null;
}
}",
@"
using System.Threading.Tasks;
using B;
namespace A
{
class C
{
C Instance { get; }
Task M() { await foreach (var i in Instance); }
public Enumerator GetEnumerator()
{
return new Enumerator();
}
public class Enumerator
{
public int Current { get; }
public bool MoveNext();
}
}
}
namespace B
{
using A;
static class Extensions
{
public static Enumerator GetAsyncEnumerator(this C instance) => null;
}
public sealed class Enumerator
{
public async System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null;
public int Current => throw null;
}
}", testHost);
}
[Fact]
public async Task TestMissingForExtensionGetEnumeratorOnAsyncForeach()
{
await TestMissingAsync(
@"
using System.Threading.Tasks;
namespace A
{
class C
{
C Instance { get; }
Task M() { await foreach (var i in [|Instance|]); }
}
}
namespace B
{
using A;
using System.Collections.Generic;
static class Extensions
{
public static IEnumerator<int> GetEnumerator(this C instance) => null;
}
}");
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithStaticUsingInNamespace_WhenNoExistingUsings(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
using static System.Math;
class C
{
public [|List<int>|] F;
}
}
",
@"
namespace N
{
using System.Collections.Generic;
using static System.Math;
class C
{
public List<int> F;
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithStaticUsingInInnerNestedNamespace_WhenNoExistingUsings(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
namespace M
{
using static System.Math;
class C
{
public [|List<int>|] F;
}
}
}
",
@"
namespace N
{
namespace M
{
using System.Collections.Generic;
using static System.Math;
class C
{
public List<int> F;
}
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithStaticUsingInOuterNestedNamespace_WhenNoExistingUsings(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
using static System.Math;
namespace M
{
class C
{
public [|List<int>|] F;
}
}
}
",
@"
namespace N
{
using System.Collections.Generic;
using static System.Math;
namespace M
{
class C
{
public List<int> F;
}
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithExistingUsingInCompilationUnit_WhenStaticUsingInNamespace(TestHost testHost)
{
await TestAsync(
@"
using System;
namespace N
{
using static System.Math;
class C
{
public [|List<int>|] F;
}
}
",
@"
using System;
using System.Collections.Generic;
namespace N
{
using static System.Math;
class C
{
public List<int> F;
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithExistingUsing_WhenStaticUsingInInnerNestedNamespace(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
using System;
namespace M
{
using static System.Math;
class C
{
public [|List<int>|] F;
}
}
}
",
@"
namespace N
{
using System;
using System.Collections.Generic;
namespace M
{
using static System.Math;
class C
{
public List<int> F;
}
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithExistingUsing_WhenStaticUsingInOuterNestedNamespace(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
using static System.Math;
namespace M
{
using System;
class C
{
public [|List<int>|] F;
}
}
}
",
@"
namespace N
{
using static System.Math;
namespace M
{
using System;
using System.Collections.Generic;
class C
{
public List<int> F;
}
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithUsingAliasInNamespace_WhenNoExistingUsing(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
using SAction = System.Action;
class C
{
public [|List<int>|] F;
}
}
",
@"
namespace N
{
using System.Collections.Generic;
using SAction = System.Action;
class C
{
public List<int> F;
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithUsingAliasInInnerNestedNamespace_WhenNoExistingUsing(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
namespace M
{
using SAction = System.Action;
class C
{
public [|List<int>|] F;
}
}
}
",
@"
namespace N
{
namespace M
{
using System.Collections.Generic;
using SAction = System.Action;
class C
{
public List<int> F;
}
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithUsingAliasInOuterNestedNamespace_WhenNoExistingUsing(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
using SAction = System.Action;
namespace M
{
class C
{
public [|List<int>|] F;
}
}
}
",
@"
namespace N
{
using System.Collections.Generic;
using SAction = System.Action;
namespace M
{
class C
{
public List<int> F;
}
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithExistingUsingInCompilationUnit_WhenUsingAliasInNamespace(TestHost testHost)
{
await TestAsync(
@"
using System;
namespace N
{
using SAction = System.Action;
class C
{
public [|List<int>|] F;
}
}
",
@"
using System;
using System.Collections.Generic;
namespace N
{
using SAction = System.Action;
class C
{
public List<int> F;
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithExistingUsing_WhenUsingAliasInInnerNestedNamespace(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
using System;
namespace M
{
using SAction = System.Action;
class C
{
public [|List<int>|] F;
}
}
}
",
@"
namespace N
{
using System;
using System.Collections.Generic;
namespace M
{
using SAction = System.Action;
class C
{
public [|List<int>|] F;
}
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithExistingUsing_WhenUsingAliasInOuterNestedNamespace(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
using SAction = System.Action;
namespace M
{
using System;
class C
{
public [|List<int>|] F;
}
}
}
",
@"
namespace N
{
using SAction = System.Action;
namespace M
{
using System;
using System.Collections.Generic;
class C
{
public [|List<int>|] F;
}
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")]
public async Task KeepUsingsGrouped1(TestHost testHost)
{
await TestAsync(
@"
using System;
class Program
{
static void Main(string[] args)
{
[|Goo|]
}
}
namespace Microsoft
{
public class Goo
{
}
}",
@"
using System;
using Microsoft;
class Program
{
static void Main(string[] args)
{
Goo
}
}
namespace Microsoft
{
public class Goo
{
}
}", testHost);
}
[WorkItem(1239, @"https://github.com/dotnet/roslyn/issues/1239")]
[Fact]
public async Task TestIncompleteLambda1()
{
await TestInRegularAndScriptAsync(
@"using System.Linq;
class C
{
C()
{
"""".Select(() => {
new [|Byte|]",
@"using System;
using System.Linq;
class C
{
C()
{
"""".Select(() => {
new Byte");
}
[WorkItem(1239, @"https://github.com/dotnet/roslyn/issues/1239")]
[Fact]
public async Task TestIncompleteLambda2()
{
await TestInRegularAndScriptAsync(
@"using System.Linq;
class C
{
C()
{
"""".Select(() => {
new [|Byte|]() }",
@"using System;
using System.Linq;
class C
{
C()
{
"""".Select(() => {
new Byte() }");
}
[WorkItem(860648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/860648")]
[WorkItem(902014, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/902014")]
[Fact]
public async Task TestIncompleteSimpleLambdaExpression()
{
await TestInRegularAndScriptAsync(
@"using System.Linq;
class Program
{
static void Main(string[] args)
{
args[0].Any(x => [|IBindCtx|]
string a;
}
}",
@"using System.Linq;
using System.Runtime.InteropServices.ComTypes;
class Program
{
static void Main(string[] args)
{
args[0].Any(x => IBindCtx
string a;
}
}");
}
[Theory]
[CombinatorialData]
[WorkItem(1266354, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1266354")]
public async Task TestAddUsingsEditorBrowsableNeverSameProject(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.cs"">
using System.ComponentModel;
namespace ProjectLib
{
[EditorBrowsable(EditorBrowsableState.Never)]
public class Project
{
}
}
</Document>
<Document FilePath=""Program.cs"">
class Program
{
static void Main(string[] args)
{
Project p = new [|Project()|];
}
}
</Document>
</Project>
</Workspace>";
const string ExpectedDocumentText = @"
using ProjectLib;
class Program
{
static void Main(string[] args)
{
Project p = new [|Project()|];
}
}
";
await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1266354, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1266354")]
public async Task TestAddUsingsEditorBrowsableNeverDifferentProject(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""Visual Basic"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.vb"">
imports System.ComponentModel
namespace ProjectLib
<EditorBrowsable(EditorBrowsableState.Never)>
public class Project
end class
end namespace
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference>lib</ProjectReference>
<Document FilePath=""Program.cs"">
class Program
{
static void Main(string[] args)
{
[|Project|] p = new Project();
}
}
</Document>
</Project>
</Workspace>";
await TestMissingAsync(InitialWorkspace, new TestParameters(testHost: testHost));
}
[Theory]
[CombinatorialData]
[WorkItem(1266354, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1266354")]
public async Task TestAddUsingsEditorBrowsableAdvancedDifferentProjectOptionOn(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""Visual Basic"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.vb"">
imports System.ComponentModel
namespace ProjectLib
<EditorBrowsable(EditorBrowsableState.Advanced)>
public class Project
end class
end namespace
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference>lib</ProjectReference>
<Document FilePath=""Program.cs"">
class Program
{
static void Main(string[] args)
{
[|Project|] p = new Project();
}
}
</Document>
</Project>
</Workspace>";
const string ExpectedDocumentText = @"
using ProjectLib;
class Program
{
static void Main(string[] args)
{
Project p = new [|Project()|];
}
}
";
await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1266354, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1266354")]
public async Task TestAddUsingsEditorBrowsableAdvancedDifferentProjectOptionOff(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""Visual Basic"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.vb"">
imports System.ComponentModel
namespace ProjectLib
<EditorBrowsable(EditorBrowsableState.Advanced)>
public class Project
end class
end namespace
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference>lib</ProjectReference>
<Document FilePath=""Program.cs"">
class Program
{
static void Main(string[] args)
{
[|Project|] p = new Project();
}
}
</Document>
</Project>
</Workspace>";
await TestMissingAsync(InitialWorkspace, new TestParameters(
options: Option(CompletionOptions.HideAdvancedMembers, true),
testHost: testHost));
}
}
}
| 1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SymbolCompletionProviderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Completion.Providers;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion;
using Microsoft.CodeAnalysis.Experiments;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionSetSources
{
[UseExportProvider]
public partial class SymbolCompletionProviderTests : AbstractCSharpCompletionProviderTests
{
internal override Type GetCompletionProviderType()
=> typeof(SymbolCompletionProvider);
protected override TestComposition GetComposition()
=> base.GetComposition().AddParts(typeof(TestExperimentationService));
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData(SourceCodeKind.Regular)]
[InlineData(SourceCodeKind.Script)]
public async Task EmptyFile(SourceCodeKind sourceCodeKind)
{
await VerifyItemIsAbsentAsync(@"$$", @"String", expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind);
await VerifyItemExistsAsync(@"$$", @"System", expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind);
}
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData(SourceCodeKind.Regular)]
[InlineData(SourceCodeKind.Script)]
public async Task EmptyFileWithUsing(SourceCodeKind sourceCodeKind)
{
await VerifyItemExistsAsync(@"using System;
$$", @"String", expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind);
await VerifyItemExistsAsync(@"using System;
$$", @"System", expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterHashR()
=> await VerifyItemIsAbsentAsync(@"#r $$", "@System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterHashLoad()
=> await VerifyItemIsAbsentAsync(@"#load $$", "@System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingDirective()
{
await VerifyItemIsAbsentAsync(@"using $$", @"String");
await VerifyItemIsAbsentAsync(@"using $$ = System", @"System");
await VerifyItemExistsAsync(@"using $$", @"System");
await VerifyItemExistsAsync(@"using T = $$", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InactiveRegion()
{
await VerifyItemIsAbsentAsync(@"class C {
#if false
$$
#endif", @"String");
await VerifyItemIsAbsentAsync(@"class C {
#if false
$$
#endif", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ActiveRegion()
{
await VerifyItemIsAbsentAsync(@"class C {
#if true
$$
#endif", @"String");
await VerifyItemExistsAsync(@"class C {
#if true
$$
#endif", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InactiveRegionWithUsing()
{
await VerifyItemIsAbsentAsync(@"using System;
class C {
#if false
$$
#endif", @"String");
await VerifyItemIsAbsentAsync(@"using System;
class C {
#if false
$$
#endif", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ActiveRegionWithUsing()
{
await VerifyItemExistsAsync(@"using System;
class C {
#if true
$$
#endif", @"String");
await VerifyItemExistsAsync(@"using System;
class C {
#if true
$$
#endif", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SingleLineComment1()
{
await VerifyItemIsAbsentAsync(@"using System;
class C {
// $$", @"String");
await VerifyItemIsAbsentAsync(@"using System;
class C {
// $$", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SingleLineComment2()
{
await VerifyItemIsAbsentAsync(@"using System;
class C {
// $$
", @"String");
await VerifyItemIsAbsentAsync(@"using System;
class C {
// $$
", @"System");
await VerifyItemIsAbsentAsync(@"using System;
class C {
// $$
", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MultiLineComment()
{
await VerifyItemIsAbsentAsync(@"using System;
class C {
/* $$", @"String");
await VerifyItemIsAbsentAsync(@"using System;
class C {
/* $$", @"System");
await VerifyItemIsAbsentAsync(@"using System;
class C {
/* $$ */", @"String");
await VerifyItemIsAbsentAsync(@"using System;
class C {
/* $$ */", @"System");
await VerifyItemExistsAsync(@"using System;
class C {
/* */$$", @"System");
await VerifyItemExistsAsync(@"using System;
class C {
/* */$$
", @"System");
await VerifyItemExistsAsync(@"using System;
class C {
/* */$$
", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SingleLineXmlComment1()
{
await VerifyItemIsAbsentAsync(@"using System;
class C {
/// $$", @"String");
await VerifyItemIsAbsentAsync(@"using System;
class C {
/// $$", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SingleLineXmlComment2()
{
await VerifyItemIsAbsentAsync(@"using System;
class C {
/// $$
", @"String");
await VerifyItemIsAbsentAsync(@"using System;
class C {
/// $$
", @"System");
await VerifyItemIsAbsentAsync(@"using System;
class C {
/// $$
", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MultiLineXmlComment()
{
await VerifyItemIsAbsentAsync(@"using System;
class C {
/** $$ */", @"String");
await VerifyItemIsAbsentAsync(@"using System;
class C {
/** $$ */", @"System");
await VerifyItemExistsAsync(@"using System;
class C {
/** */$$", @"System");
await VerifyItemExistsAsync(@"using System;
class C {
/** */$$
", @"System");
await VerifyItemExistsAsync(@"using System;
class C {
/** */$$
", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OpenStringLiteral()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$")), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OpenStringLiteralInDirective()
{
await VerifyItemIsAbsentAsync("#r \"$$", "String", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
await VerifyItemIsAbsentAsync("#r \"$$", "System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StringLiteral()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$\";")), @"System");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$\";")), @"String");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StringLiteralInDirective()
{
await VerifyItemIsAbsentAsync("#r \"$$\"", "String", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
await VerifyItemIsAbsentAsync("#r \"$$\"", "System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OpenCharLiteral()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("char c = '$$")), @"System");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("char c = '$$")), @"String");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AssemblyAttribute1()
{
await VerifyItemExistsAsync(@"[assembly: $$]", @"System");
await VerifyItemIsAbsentAsync(@"[assembly: $$]", @"String");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AssemblyAttribute2()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"[assembly: $$]"), @"System");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"[assembly: $$]"), @"AttributeUsage");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SystemAttributeIsNotAnAttribute()
{
var content = @"[$$]
class CL {}";
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"Attribute");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeAttribute()
{
var content = @"[$$]
class CL {}";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeParamAttribute()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<[A$$]T> {}"), @"AttributeUsage");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<[A$$]T> {}"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodAttribute()
{
var content = @"class CL {
[$$]
void Method() {}
}";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodTypeParamAttribute()
{
var content = @"class CL{
void Method<[A$$]T> () {}
}";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodParamAttribute()
{
var content = @"class CL{
void Method ([$$]int i) {}
}";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_EmptyNameSpan_TopLevel()
{
var source = @"namespace $$ { }";
await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_EmptyNameSpan_Nested()
{
var source = @";
namespace System
{
namespace $$ { }
}";
await VerifyItemExistsAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_TopLevelNoPeers()
{
var source = @"using System;
namespace $$";
await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "String", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_TopLevelNoPeers_FileScopedNamespace()
{
var source = @"using System;
namespace $$;";
await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "String", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_TopLevelWithPeer()
{
var source = @"
namespace A { }
namespace $$";
await VerifyItemExistsAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_NestedWithNoPeers()
{
var source = @"
namespace A
{
namespace $$
}";
await VerifyNoItemsExistAsync(source, sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_NestedWithPeer()
{
var source = @"
namespace A
{
namespace B { }
namespace $$
}";
await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_ExcludesCurrentDeclaration()
{
var source = @"namespace N$$S";
await VerifyItemIsAbsentAsync(source, "NS", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_WithNested()
{
var source = @"
namespace A
{
namespace $$
{
namespace B { }
}
}";
await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_WithNestedAndMatchingPeer()
{
var source = @"
namespace A.B { }
namespace A
{
namespace $$
{
namespace B { }
}
}";
await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_InnerCompletionPosition()
{
var source = @"namespace Sys$$tem { }";
await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_IncompleteDeclaration()
{
var source = @"
namespace A
{
namespace B
{
namespace $$
namespace C1 { }
}
namespace B.C2 { }
}
namespace A.B.C3 { }";
// Ideally, all the C* namespaces would be recommended but, because of how the parser
// recovers from the missing braces, they end up with the following qualified names...
//
// C1 => A.B.?.C1
// C2 => A.B.B.C2
// C3 => A.A.B.C3
//
// ...none of which are found by the current algorithm.
await VerifyItemIsAbsentAsync(source, "C1", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "C2", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "C3", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
// Because of the above, B does end up in the completion list
// since A.B.B appears to be a peer of the new declaration
await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Qualified_NoPeers()
{
var source = @"namespace A.$$";
await VerifyNoItemsExistAsync(source, sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Qualified_TopLevelWithPeer()
{
var source = @"
namespace A.B { }
namespace A.$$";
await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Qualified_TopLevelWithPeer_FileScopedNamespace()
{
var source = @"
namespace A.B { }
namespace A.$$;";
await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Qualified_NestedWithPeer()
{
var source = @"
namespace A
{
namespace B.C { }
namespace B.$$
}";
await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemExistsAsync(source, "C", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Qualified_WithNested()
{
var source = @"
namespace A.$$
{
namespace B { }
}
";
await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Qualified_WithNestedAndMatchingPeer()
{
var source = @"
namespace A.B { }
namespace A.$$
{
namespace B { }
}
";
await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Qualified_InnerCompletionPosition()
{
var source = @"namespace Sys$$tem.Runtime { }";
await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_OnKeyword()
{
var source = @"name$$space System { }";
await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_OnNestedKeyword()
{
var source = @"
namespace System
{
name$$space Runtime { }
}";
await VerifyItemIsAbsentAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Qualified_IncompleteDeclaration()
{
var source = @"
namespace A
{
namespace B
{
namespace C.$$
namespace C.D1 { }
}
namespace B.C.D2 { }
}
namespace A.B.C.D3 { }";
await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "C", sourceCodeKind: SourceCodeKind.Regular);
// Ideally, all the D* namespaces would be recommended but, because of how the parser
// recovers from the missing braces, they end up with the following qualified names...
//
// D1 => A.B.C.C.?.D1
// D2 => A.B.B.C.D2
// D3 => A.A.B.C.D3
//
// ...none of which are found by the current algorithm.
await VerifyItemIsAbsentAsync(source, "D1", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "D2", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "D3", sourceCodeKind: SourceCodeKind.Regular);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UnderNamespace()
{
await VerifyItemIsAbsentAsync(@"namespace NS { $$", @"String");
await VerifyItemIsAbsentAsync(@"namespace NS { $$", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OutsideOfType1()
{
await VerifyItemIsAbsentAsync(@"namespace NS {
class CL {}
$$", @"String");
await VerifyItemIsAbsentAsync(@"namespace NS {
class CL {}
$$", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OutsideOfType2()
{
var content = @"namespace NS {
class CL {}
$$";
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionInsideProperty()
{
var content = @"class C
{
private string name;
public string Name
{
set
{
name = $$";
await VerifyItemExistsAsync(content, @"value");
await VerifyItemExistsAsync(content, @"C");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterDot()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"[assembly: A.$$"), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"[assembly: A.$$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingAlias()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"using MyType = $$"), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"using MyType = $$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task IncompleteMember()
{
var content = @"class CL {
$$
";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task IncompleteMemberAccessibility()
{
var content = @"class CL {
public $$
";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BadStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = $$)c")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = $$)c")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeTypeParameter()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<$$"), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<$$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeTypeParameterList()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T, $$"), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T, $$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CastExpressionTypePart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = ($$)c")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = ($$)c")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ObjectCreationExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ArrayCreationExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$ [")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$ [")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StackAllocArrayCreationExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = stackalloc $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = stackalloc $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FromClauseTypeOptPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from $$ c")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from $$ c")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task JoinClause()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join $$ j")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join $$ j")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DeclarationStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ i =")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ i =")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task VariableDeclaration()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"fixed($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"fixed($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForEachStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForEachStatementNoToken()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach $$")), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CatchDeclaration()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"try {} catch($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"try {} catch($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FieldDeclaration()
{
var content = @"class CL {
$$ i";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EventFieldDeclaration()
{
var content = @"class CL {
event $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConversionOperatorDeclaration()
{
var content = @"class CL {
explicit operator $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConversionOperatorDeclarationNoToken()
{
var content = @"class CL {
explicit $$";
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task PropertyDeclaration()
{
var content = @"class CL {
$$ Prop {";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EventDeclaration()
{
var content = @"class CL {
event $$ Event {";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task IndexerDeclaration()
{
var content = @"class CL {
$$ this";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Parameter()
{
var content = @"class CL {
void Method($$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ArrayType()
{
var content = @"class CL {
$$ [";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task PointerType()
{
var content = @"class CL {
$$ *";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NullableType()
{
var content = @"class CL {
$$ ?";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DelegateDeclaration()
{
var content = @"class CL {
delegate $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodDeclaration()
{
var content = @"class CL {
$$ M(";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OperatorDeclaration()
{
var content = @"class CL {
$$ operator";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ParenthesizedExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InvocationExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$(")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$(")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ElementAccessExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$[")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$[")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Argument()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"i[$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"i[$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CastExpressionExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"(c)$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"(c)$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FromClauseInPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LetClauseExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C let n = $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C let n = $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OrderingExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C orderby $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C orderby $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SelectClauseExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C select $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C select $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExpressionStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ReturnStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"return $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"return $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThrowStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"throw $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"throw $$")), @"System");
}
[WorkItem(760097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/760097")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task YieldReturnStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"yield return $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"yield return $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForEachStatementExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach(T t in $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach(T t in $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStatementExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"using($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"using($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LockStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"lock($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"lock($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EqualsValueClause()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var i = $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var i = $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForStatementInitializersPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForStatementConditionOptPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForStatementIncrementorsPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;i>10;$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;i>10;$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DoStatementConditionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"do {} while($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"do {} while($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WhileStatementConditionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"while($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"while($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ArrayRankSpecifierSizesPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"int [$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"int [$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task PrefixUnaryExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"+$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"+$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task PostfixUnaryExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$++")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$++")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BinaryExpressionLeftPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ + 1")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ + 1")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BinaryExpressionRightPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 + $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 + $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AssignmentExpressionLeftPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ = 1")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ = 1")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AssignmentExpressionRightPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 = $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 = $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConditionalExpressionConditionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$? 1:")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$? 1:")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConditionalExpressionWhenTruePart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? $$:")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? $$:")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConditionalExpressionWhenFalsePart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? 1:$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? 1:$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task JoinClauseInExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task JoinClauseLeftExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task JoinClauseRightExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on id equals $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on id equals $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WhereClauseConditionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C where $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C where $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task GroupClauseGroupExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task GroupClauseByExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group g by $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group g by $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task IfStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"if ($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"if ($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SwitchStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"switch($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"switch($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SwitchLabelCase()
{
var content = @"switch(i) { case $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SwitchPatternLabelCase()
{
var content = @"switch(i) { case $$ when";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")]
public async Task SwitchExpressionFirstBranch()
{
var content = @"i switch { $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")]
public async Task SwitchExpressionSecondBranch()
{
var content = @"i switch { 1 => true, $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")]
public async Task PositionalPatternFirstPosition()
{
var content = @"i is ($$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")]
public async Task PositionalPatternSecondPosition()
{
var content = @"i is (1, $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")]
public async Task PropertyPatternFirstPosition()
{
var content = @"i is { P: $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")]
public async Task PropertyPatternSecondPosition()
{
var content = @"i is { P1: 1, P2: $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InitializerExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new [] { $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new [] { $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeParameterConstraintClause()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : $$"), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : $$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeParameterConstraintClauseList()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A, $$"), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A, $$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeParameterConstraintClauseAnotherWhere()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A where$$"), @"System");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A where$$"), @"String");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeSymbolOfTypeParameterConstraintClause1()
{
await VerifyItemExistsAsync(@"class CL<T> where $$", @"T");
await VerifyItemExistsAsync(@"class CL{ delegate void F<T>() where $$} ", @"T");
await VerifyItemExistsAsync(@"class CL{ void F<T>() where $$", @"T");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeSymbolOfTypeParameterConstraintClause2()
{
await VerifyItemIsAbsentAsync(@"class CL<T> where $$", @"System");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> where $$"), @"String");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeSymbolOfTypeParameterConstraintClause3()
{
await VerifyItemIsAbsentAsync(@"class CL<T1> { void M<T2> where $$", @"T1");
await VerifyItemExistsAsync(@"class CL<T1> { void M<T2>() where $$", @"T2");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BaseList1()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : $$"), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : $$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BaseList2()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : B, $$"), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : B, $$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BaseListWhere()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> : B where$$"), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> : B where$$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AliasedName()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod(@"global::$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"global::$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AliasedNamespace()
=> await VerifyItemExistsAsync(AddUsingDirectives("using S = System;", AddInsideMethod(@"S.$$")), @"String");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AliasedType()
=> await VerifyItemExistsAsync(AddUsingDirectives("using S = System.String;", AddInsideMethod(@"S.$$")), @"Empty");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstructorInitializer()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class C { C() : $$"), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class C { C() : $$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Typeof1()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"typeof($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"typeof($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Typeof2()
=> await VerifyItemIsAbsentAsync(AddInsideMethod(@"var x = 0; typeof($$"), @"x");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Sizeof1()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"sizeof($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"sizeof($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Sizeof2()
=> await VerifyItemIsAbsentAsync(AddInsideMethod(@"var x = 0; sizeof($$"), @"x");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Default1()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"default($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"default($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Default2()
=> await VerifyItemIsAbsentAsync(AddInsideMethod(@"var x = 0; default($$"), @"x");
[WorkItem(543819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543819")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Checked()
=> await VerifyItemExistsAsync(AddInsideMethod(@"var x = 0; checked($$"), @"x");
[WorkItem(543819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543819")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Unchecked()
=> await VerifyItemExistsAsync(AddInsideMethod(@"var x = 0; unchecked($$"), @"x");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Locals()
=> await VerifyItemExistsAsync(@"class c { void M() { string goo; $$", "goo");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Parameters()
=> await VerifyItemExistsAsync(@"class c { void M(string args) { $$", "args");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LambdaDiscardParameters()
=> await VerifyItemIsAbsentAsync(@"class C { void M() { System.Func<int, string, int> f = (int _, string _) => 1 + $$", "_");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AnonymousMethodDiscardParameters()
=> await VerifyItemIsAbsentAsync(@"class C { void M() { System.Func<int, string, int> f = delegate(int _, string _) { return 1 + $$ }; } }", "_");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CommonTypesInNewExpressionContext()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class c { void M() { new $$"), "Exception");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoCompletionForUnboundTypes()
=> await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class c { void M() { goo.$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoParametersInTypeOf()
=> await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class c { void M(int x) { typeof($$"), "x");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoParametersInDefault()
=> await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class c { void M(int x) { default($$"), "x");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoParametersInSizeOf()
=> await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class C { void M(int x) { unsafe { sizeof($$"), "x");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoParametersInGenericParameterList()
=> await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class Generic<T> { void M(int x) { Generic<$$"), "x");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoMembersAfterNullLiteral()
=> await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class C { void M() { null.$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterTrueLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { true.$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterFalseLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { false.$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterCharLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { 'c'.$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterStringLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { """".$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterVerbatimStringLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { @"""".$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterNumericLiteral()
{
// NOTE: the Completion command handler will suppress this case if the user types '.',
// but we still need to show members if the user specifically invokes statement completion here.
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { 2.$$"), "Equals");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoMembersAfterParenthesizedNullLiteral()
=> await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class C { void M() { (null).$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterParenthesizedTrueLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (true).$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterParenthesizedFalseLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (false).$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterParenthesizedCharLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { ('c').$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterParenthesizedStringLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { ("""").$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterParenthesizedVerbatimStringLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (@"""").$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterParenthesizedNumericLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (2).$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterArithmeticExpression()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (1 + 1).$$"), "Equals");
[WorkItem(539332, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539332")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceTypesAvailableInUsingAlias()
=> await VerifyItemExistsAsync(@"using S = System.$$", "String");
[WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InheritedMember1()
{
var markup = @"
class A
{
private void Hidden() { }
protected void Goo() { }
}
class B : A
{
void Bar()
{
$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Hidden");
await VerifyItemExistsAsync(markup, "Goo");
}
[WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InheritedMember2()
{
var markup = @"
class A
{
private void Hidden() { }
protected void Goo() { }
}
class B : A
{
void Bar()
{
this.$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Hidden");
await VerifyItemExistsAsync(markup, "Goo");
}
[WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InheritedMember3()
{
var markup = @"
class A
{
private void Hidden() { }
protected void Goo() { }
}
class B : A
{
void Bar()
{
base.$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Hidden");
await VerifyItemExistsAsync(markup, "Goo");
await VerifyItemIsAbsentAsync(markup, "Bar");
}
[WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InheritedStaticMember1()
{
var markup = @"
class A
{
private static void Hidden() { }
protected static void Goo() { }
}
class B : A
{
void Bar()
{
$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Hidden");
await VerifyItemExistsAsync(markup, "Goo");
}
[WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InheritedStaticMember2()
{
var markup = @"
class A
{
private static void Hidden() { }
protected static void Goo() { }
}
class B : A
{
void Bar()
{
B.$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Hidden");
await VerifyItemExistsAsync(markup, "Goo");
}
[WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InheritedStaticMember3()
{
var markup = @"
class A
{
private static void Hidden() { }
protected static void Goo() { }
}
class B : A
{
void Bar()
{
A.$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Hidden");
await VerifyItemExistsAsync(markup, "Goo");
}
[WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InheritedInstanceAndStaticMembers()
{
var markup = @"
class A
{
private static void HiddenStatic() { }
protected static void GooStatic() { }
private void HiddenInstance() { }
protected void GooInstance() { }
}
class B : A
{
void Bar()
{
$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "HiddenStatic");
await VerifyItemExistsAsync(markup, "GooStatic");
await VerifyItemIsAbsentAsync(markup, "HiddenInstance");
await VerifyItemExistsAsync(markup, "GooInstance");
}
[WorkItem(540155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540155")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForLoopIndexer1()
{
var markup = @"
class C
{
void M()
{
for (int i = 0; $$
";
await VerifyItemExistsAsync(markup, "i");
}
[WorkItem(540155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540155")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForLoopIndexer2()
{
var markup = @"
class C
{
void M()
{
for (int i = 0; i < 10; $$
";
await VerifyItemExistsAsync(markup, "i");
}
[WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceMembersAfterType1()
{
var markup = @"
class C
{
void M()
{
System.IDisposable.$$
";
await VerifyItemIsAbsentAsync(markup, "Dispose");
}
[WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceMembersAfterType2()
{
var markup = @"
class C
{
void M()
{
(System.IDisposable).$$
";
await VerifyItemIsAbsentAsync(markup, "Dispose");
}
[WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceMembersAfterType3()
{
var markup = @"
using System;
class C
{
void M()
{
IDisposable.$$
";
await VerifyItemIsAbsentAsync(markup, "Dispose");
}
[WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceMembersAfterType4()
{
var markup = @"
using System;
class C
{
void M()
{
(IDisposable).$$
";
await VerifyItemIsAbsentAsync(markup, "Dispose");
}
[WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticMembersAfterType1()
{
var markup = @"
class C
{
void M()
{
System.IDisposable.$$
";
await VerifyItemExistsAsync(markup, "ReferenceEquals");
}
[WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticMembersAfterType2()
{
var markup = @"
class C
{
void M()
{
(System.IDisposable).$$
";
await VerifyItemIsAbsentAsync(markup, "ReferenceEquals");
}
[WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticMembersAfterType3()
{
var markup = @"
using System;
class C
{
void M()
{
IDisposable.$$
";
await VerifyItemExistsAsync(markup, "ReferenceEquals");
}
[WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticMembersAfterType4()
{
var markup = @"
using System;
class C
{
void M()
{
(IDisposable).$$
";
await VerifyItemIsAbsentAsync(markup, "ReferenceEquals");
}
[WorkItem(540197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540197")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeParametersInClass()
{
var markup = @"
class C<T, R>
{
$$
}
";
await VerifyItemExistsAsync(markup, "T");
}
[WorkItem(540212, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540212")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterRefInLambda_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
Func<int, int> f = (ref $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[WorkItem(540212, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540212")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterOutInLambda_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
Func<int, int> f = (out $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(24326, "https://github.com/dotnet/roslyn/issues/24326")]
public async Task AfterInInLambda_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
Func<int, int> f = (in $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterRefInMethodDeclaration_TypeOnly()
{
var markup = @"
using System;
class C
{
String field;
void M(ref $$)
{
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "field");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterOutInMethodDeclaration_TypeOnly()
{
var markup = @"
using System;
class C
{
String field;
void M(out $$)
{
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "field");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(24326, "https://github.com/dotnet/roslyn/issues/24326")]
public async Task AfterInInMethodDeclaration_TypeOnly()
{
var markup = @"
using System;
class C
{
String field;
void M(in $$)
{
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "field");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterRefInInvocation_TypeAndVariable()
{
var markup = @"
using System;
class C
{
void M(ref String parameter)
{
M(ref $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemExistsAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterOutInInvocation_TypeAndVariable()
{
var markup = @"
using System;
class C
{
void M(out String parameter)
{
M(out $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemExistsAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(24326, "https://github.com/dotnet/roslyn/issues/24326")]
public async Task AfterInInInvocation_TypeAndVariable()
{
var markup = @"
using System;
class C
{
void M(in String parameter)
{
M(in $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemExistsAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")]
public async Task AfterRefExpression_TypeAndVariable()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
ref var x = ref $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemExistsAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")]
public async Task AfterRefInStatementContext_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
ref $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")]
public async Task AfterRefReadonlyInStatementContext_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
ref readonly $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterRefLocalDeclaration_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
ref $$ int local;
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterRefReadonlyLocalDeclaration_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
ref readonly $$ int local;
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterRefLocalFunction_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
ref $$ int Function();
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterRefReadonlyLocalFunction_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
ref readonly $$ int Function();
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")]
public async Task AfterRefInMemberContext_TypeOnly()
{
var markup = @"
using System;
class C
{
String field;
ref $$
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "field");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")]
public async Task AfterRefReadonlyInMemberContext_TypeOnly()
{
var markup = @"
using System;
class C
{
String field;
ref readonly $$
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "field");
}
[WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedType1()
{
var markup = @"
class Q
{
$$
class R
{
}
}
";
await VerifyItemExistsAsync(markup, "Q");
await VerifyItemExistsAsync(markup, "R");
}
[WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedType2()
{
var markup = @"
class Q
{
class R
{
$$
}
}
";
await VerifyItemExistsAsync(markup, "Q");
await VerifyItemExistsAsync(markup, "R");
}
[WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedType3()
{
var markup = @"
class Q
{
class R
{
}
$$
}
";
await VerifyItemExistsAsync(markup, "Q");
await VerifyItemExistsAsync(markup, "R");
}
[WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedType4_Regular()
{
var markup = @"
class Q
{
class R
{
}
}
$$"; // At EOF
// Top-level statements are not allowed to follow classes, but we still offer it in completion for a few
// reasons:
//
// 1. The code is simpler
// 2. It's a relatively rare coding practice to define types outside of namespaces
// 3. It allows the compiler to produce a better error message when users type things in the wrong order
await VerifyItemExistsAsync(markup, "Q", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(markup, "R", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedType4_Script()
{
var markup = @"
class Q
{
class R
{
}
}
$$"; // At EOF
await VerifyItemExistsAsync(markup, "Q", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
await VerifyItemIsAbsentAsync(markup, "R", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedType5()
{
var markup = @"
class Q
{
class R
{
}
$$"; // At EOF
await VerifyItemExistsAsync(markup, "Q");
await VerifyItemExistsAsync(markup, "R");
}
[WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedType6()
{
var markup = @"
class Q
{
class R
{
$$"; // At EOF
await VerifyItemExistsAsync(markup, "Q");
await VerifyItemExistsAsync(markup, "R");
}
[WorkItem(540574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540574")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AmbiguityBetweenTypeAndLocal()
{
var markup = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public void goo() {
int i = 5;
i.$$
List<string> ml = new List<string>();
}
}";
await VerifyItemExistsAsync(markup, "CompareTo");
}
[WorkItem(21596, "https://github.com/dotnet/roslyn/issues/21596")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AmbiguityBetweenExpressionAndLocalFunctionReturnType()
{
var markup = @"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
AwaitTest test = new AwaitTest();
test.Test1().Wait();
}
}
class AwaitTest
{
List<string> stringList = new List<string>();
public async Task<bool> Test1()
{
stringList.$$
await Test2();
return true;
}
public async Task<bool> Test2()
{
return true;
}
}";
await VerifyItemExistsAsync(markup, "Add");
}
[WorkItem(540750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540750")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionAfterNewInScript()
{
var markup = @"
using System;
new $$";
await VerifyItemExistsAsync(markup, "String", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[WorkItem(540933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540933")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExtensionMethodsInScript()
{
var markup = @"
using System.Linq;
var a = new int[] { 1, 2 };
a.$$";
await VerifyItemExistsAsync(markup, "ElementAt", displayTextSuffix: "<>", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[WorkItem(541019, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541019")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExpressionsInForLoopInitializer()
{
var markup = @"
public class C
{
public void M()
{
int count = 0;
for ($$
";
await VerifyItemExistsAsync(markup, "count");
}
[WorkItem(541108, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541108")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterLambdaExpression1()
{
var markup = @"
public class C
{
public void M()
{
System.Func<int, int> f = arg => { arg = 2; return arg; }.$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "ToString");
}
[WorkItem(541108, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541108")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterLambdaExpression2()
{
var markup = @"
public class C
{
public void M()
{
((System.Func<int, int>)(arg => { arg = 2; return arg; })).$$
}
}
";
await VerifyItemExistsAsync(markup, "ToString");
await VerifyItemExistsAsync(markup, "Invoke");
}
[WorkItem(541216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541216")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InMultiLineCommentAtEndOfFile()
{
var markup = @"
using System;
/*$$";
await VerifyItemIsAbsentAsync(markup, "Console", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[WorkItem(541218, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541218")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeParametersAtEndOfFile()
{
var markup = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Outer<T>
{
class Inner<U>
{
static void F(T t, U u)
{
return;
}
public static void F(T t)
{
Outer<$$";
await VerifyItemExistsAsync(markup, "T");
}
[WorkItem(552717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552717")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LabelInCaseSwitchAbsentForCase()
{
var markup = @"
class Program
{
static void Main()
{
int x;
switch (x)
{
case 0:
goto $$";
await VerifyItemIsAbsentAsync(markup, "case 0:");
}
[WorkItem(552717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552717")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LabelInCaseSwitchAbsentForDefaultWhenAbsent()
{
var markup = @"
class Program
{
static void Main()
{
int x;
switch (x)
{
case 0:
goto $$";
await VerifyItemIsAbsentAsync(markup, "default:");
}
[WorkItem(552717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552717")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LabelInCaseSwitchPresentForDefault()
{
var markup = @"
class Program
{
static void Main()
{
int x;
switch (x)
{
default:
goto $$";
await VerifyItemExistsAsync(markup, "default");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LabelAfterGoto1()
{
var markup = @"
class Program
{
static void Main()
{
Goo:
int Goo;
goto $$";
await VerifyItemExistsAsync(markup, "Goo");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LabelAfterGoto2()
{
var markup = @"
class Program
{
static void Main()
{
Goo:
int Goo;
goto Goo $$";
await VerifyItemIsAbsentAsync(markup, "Goo");
}
[WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeName()
{
var markup = @"
using System;
[$$";
await VerifyItemExistsAsync(markup, "CLSCompliant");
await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute");
}
[WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameAfterSpecifier()
{
var markup = @"
using System;
[assembly:$$
";
await VerifyItemExistsAsync(markup, "CLSCompliant");
await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute");
}
[WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameInAttributeList()
{
var markup = @"
using System;
[CLSCompliant, $$";
await VerifyItemExistsAsync(markup, "CLSCompliant");
await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute");
}
[WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameBeforeClass()
{
var markup = @"
using System;
[$$
class C { }";
await VerifyItemExistsAsync(markup, "CLSCompliant");
await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute");
}
[WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameAfterSpecifierBeforeClass()
{
var markup = @"
using System;
[assembly:$$
class C { }";
await VerifyItemExistsAsync(markup, "CLSCompliant");
await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute");
}
[WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameInAttributeArgumentList()
{
var markup = @"
using System;
[CLSCompliant($$
class C { }";
await VerifyItemExistsAsync(markup, "CLSCompliantAttribute");
await VerifyItemIsAbsentAsync(markup, "CLSCompliant");
}
[WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameInsideClass()
{
var markup = @"
using System;
class C { $$ }";
await VerifyItemExistsAsync(markup, "CLSCompliantAttribute");
await VerifyItemIsAbsentAsync(markup, "CLSCompliant");
}
[WorkItem(542954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542954")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceAliasInAttributeName1()
{
var markup = @"
using Alias = System;
[$$
class C { }";
await VerifyItemExistsAsync(markup, "Alias");
}
[WorkItem(542954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542954")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceAliasInAttributeName2()
{
var markup = @"
using Alias = Goo;
namespace Goo { }
[$$
class C { }";
await VerifyItemIsAbsentAsync(markup, "Alias");
}
[WorkItem(542954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542954")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceAliasInAttributeName3()
{
var markup = @"
using Alias = Goo;
namespace Goo { class A : System.Attribute { } }
[$$
class C { }";
await VerifyItemExistsAsync(markup, "Alias");
}
[Fact]
[WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameAfterNamespace()
{
var markup = @"
namespace Test
{
class MyAttribute : System.Attribute { }
[Test.$$
class Program { }
}";
await VerifyItemExistsAsync(markup, "My");
await VerifyItemIsAbsentAsync(markup, "MyAttribute");
}
[Fact]
[WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameAfterNamespace2()
{
var markup = @"
namespace Test
{
namespace Two
{
class MyAttribute : System.Attribute { }
[Test.Two.$$
class Program { }
}
}";
await VerifyItemExistsAsync(markup, "My");
await VerifyItemIsAbsentAsync(markup, "MyAttribute");
}
[Fact]
[WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameWhenSuffixlessFormIsKeyword()
{
var markup = @"
namespace Test
{
class namespaceAttribute : System.Attribute { }
[$$
class Program { }
}";
await VerifyItemExistsAsync(markup, "namespaceAttribute");
await VerifyItemIsAbsentAsync(markup, "namespace");
await VerifyItemIsAbsentAsync(markup, "@namespace");
}
[Fact]
[WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameAfterNamespaceWhenSuffixlessFormIsKeyword()
{
var markup = @"
namespace Test
{
class namespaceAttribute : System.Attribute { }
[Test.$$
class Program { }
}";
await VerifyItemExistsAsync(markup, "namespaceAttribute");
await VerifyItemIsAbsentAsync(markup, "namespace");
await VerifyItemIsAbsentAsync(markup, "@namespace");
}
[Fact]
[WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task KeywordsUsedAsLocals()
{
var markup = @"
class C
{
void M()
{
var error = 0;
var method = 0;
var @int = 0;
Console.Write($$
}
}";
// preprocessor keyword
await VerifyItemExistsAsync(markup, "error");
await VerifyItemIsAbsentAsync(markup, "@error");
// contextual keyword
await VerifyItemExistsAsync(markup, "method");
await VerifyItemIsAbsentAsync(markup, "@method");
// full keyword
await VerifyItemExistsAsync(markup, "@int");
await VerifyItemIsAbsentAsync(markup, "int");
}
[Fact]
[WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task QueryContextualKeywords1()
{
var markup = @"
class C
{
void M()
{
var from = new[]{1,2,3};
var r = from x in $$
}
}";
await VerifyItemExistsAsync(markup, "@from");
await VerifyItemIsAbsentAsync(markup, "from");
}
[Fact]
[WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task QueryContextualKeywords2()
{
var markup = @"
class C
{
void M()
{
var where = new[] { 1, 2, 3 };
var x = from @from in @where
where $$ == @where.Length
select @from;
}
}";
await VerifyItemExistsAsync(markup, "@from");
await VerifyItemIsAbsentAsync(markup, "from");
await VerifyItemExistsAsync(markup, "@where");
await VerifyItemIsAbsentAsync(markup, "where");
}
[Fact]
[WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task QueryContextualKeywords3()
{
var markup = @"
class C
{
void M()
{
var where = new[] { 1, 2, 3 };
var x = from @from in @where
where @from == @where.Length
select $$;
}
}";
await VerifyItemExistsAsync(markup, "@from");
await VerifyItemIsAbsentAsync(markup, "from");
await VerifyItemExistsAsync(markup, "@where");
await VerifyItemIsAbsentAsync(markup, "where");
}
[Fact]
[WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameAfterGlobalAlias()
{
var markup = @"
class MyAttribute : System.Attribute { }
[global::$$
class Program { }";
await VerifyItemExistsAsync(markup, "My", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(markup, "MyAttribute", sourceCodeKind: SourceCodeKind.Regular);
}
[Fact]
[WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameAfterGlobalAliasWhenSuffixlessFormIsKeyword()
{
var markup = @"
class namespaceAttribute : System.Attribute { }
[global::$$
class Program { }";
await VerifyItemExistsAsync(markup, "namespaceAttribute", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(markup, "namespace", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(markup, "@namespace", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(25589, "https://github.com/dotnet/roslyn/issues/25589")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeSearch_NamespaceWithNestedAttribute1()
{
var markup = @"
namespace Namespace1
{
namespace Namespace2 { class NonAttribute { } }
namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } }
}
[$$]";
await VerifyItemExistsAsync(markup, "Namespace1");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeSearch_NamespaceWithNestedAttribute2()
{
var markup = @"
namespace Namespace1
{
namespace Namespace2 { class NonAttribute { } }
namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } }
}
[Namespace1.$$]";
await VerifyItemIsAbsentAsync(markup, "Namespace2");
await VerifyItemExistsAsync(markup, "Namespace3");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeSearch_NamespaceWithNestedAttribute3()
{
var markup = @"
namespace Namespace1
{
namespace Namespace2 { class NonAttribute { } }
namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } }
}
[Namespace1.Namespace3.$$]";
await VerifyItemExistsAsync(markup, "Namespace4");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeSearch_NamespaceWithNestedAttribute4()
{
var markup = @"
namespace Namespace1
{
namespace Namespace2 { class NonAttribute { } }
namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } }
}
[Namespace1.Namespace3.Namespace4.$$]";
await VerifyItemExistsAsync(markup, "Custom");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeSearch_NamespaceWithNestedAttribute_NamespaceAlias()
{
var markup = @"
using Namespace1Alias = Namespace1;
using Namespace2Alias = Namespace1.Namespace2;
using Namespace3Alias = Namespace1.Namespace3;
using Namespace4Alias = Namespace1.Namespace3.Namespace4;
namespace Namespace1
{
namespace Namespace2 { class NonAttribute { } }
namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } }
}
[$$]";
await VerifyItemExistsAsync(markup, "Namespace1Alias");
await VerifyItemIsAbsentAsync(markup, "Namespace2Alias");
await VerifyItemExistsAsync(markup, "Namespace3Alias");
await VerifyItemExistsAsync(markup, "Namespace4Alias");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeSearch_NamespaceWithoutNestedAttribute()
{
var markup = @"
namespace Namespace1
{
namespace Namespace2 { class NonAttribute { } }
namespace Namespace3.Namespace4 { class NonAttribute : System.NonAttribute { } }
}
[$$]";
await VerifyItemIsAbsentAsync(markup, "Namespace1");
}
[WorkItem(542230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542230")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task RangeVariableInQuerySelect()
{
var markup = @"
using System.Linq;
class P
{
void M()
{
var src = new string[] { ""Goo"", ""Bar"" };
var q = from x in src
select x.$$";
await VerifyItemExistsAsync(markup, "Length");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInIsExpression()
{
var markup = @"
class C
{
public const int MAX_SIZE = 10;
void M()
{
int i = 10;
if (i is $$ int"; // 'int' to force this to be parsed as an IsExpression rather than IsPatternExpression
await VerifyItemExistsAsync(markup, "MAX_SIZE");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInIsPatternExpression()
{
var markup = @"
class C
{
public const int MAX_SIZE = 10;
void M()
{
int i = 10;
if (i is $$ 1";
await VerifyItemExistsAsync(markup, "MAX_SIZE");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInSwitchCase()
{
var markup = @"
class C
{
public const int MAX_SIZE = 10;
void M()
{
int i = 10;
switch (i)
{
case $$";
await VerifyItemExistsAsync(markup, "MAX_SIZE");
}
[WorkItem(25084, "https://github.com/dotnet/roslyn/issues/25084#issuecomment-370148553")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInSwitchPatternCase()
{
var markup = @"
class C
{
public const int MAX_SIZE = 10;
void M()
{
int i = 10;
switch (i)
{
case $$ when";
await VerifyItemExistsAsync(markup, "MAX_SIZE");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInSwitchGotoCase()
{
var markup = @"
class C
{
public const int MAX_SIZE = 10;
void M()
{
int i = 10;
switch (i)
{
case MAX_SIZE:
break;
case GOO:
goto case $$";
await VerifyItemExistsAsync(markup, "MAX_SIZE");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInEnumMember()
{
var markup = @"
class C
{
public const int GOO = 0;
enum E
{
A = $$";
await VerifyItemExistsAsync(markup, "GOO");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInAttribute1()
{
var markup = @"
class C
{
public const int GOO = 0;
[System.AttributeUsage($$";
await VerifyItemExistsAsync(markup, "GOO");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInAttribute2()
{
var markup = @"
class C
{
public const int GOO = 0;
[System.AttributeUsage(GOO, $$";
await VerifyItemExistsAsync(markup, "GOO");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInAttribute3()
{
var markup = @"
class C
{
public const int GOO = 0;
[System.AttributeUsage(validOn: $$";
await VerifyItemExistsAsync(markup, "GOO");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInAttribute4()
{
var markup = @"
class C
{
public const int GOO = 0;
[System.AttributeUsage(AllowMultiple = $$";
await VerifyItemExistsAsync(markup, "GOO");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInParameterDefaultValue()
{
var markup = @"
class C
{
public const int GOO = 0;
void M(int x = $$";
await VerifyItemExistsAsync(markup, "GOO");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInConstField()
{
var markup = @"
class C
{
public const int GOO = 0;
const int BAR = $$";
await VerifyItemExistsAsync(markup, "GOO");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInConstLocal()
{
var markup = @"
class C
{
public const int GOO = 0;
void M()
{
const int BAR = $$";
await VerifyItemExistsAsync(markup, "GOO");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionWith1Overload()
{
var markup = @"
class C
{
void M(int i) { }
void M()
{
$$";
await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M(int i) (+ 1 {FeaturesResources.overload})");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionWith2Overloads()
{
var markup = @"
class C
{
void M(int i) { }
void M(out int i) { }
void M()
{
$$";
await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M(int i) (+ 2 {FeaturesResources.overloads_})");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionWith1GenericOverload()
{
var markup = @"
class C
{
void M<T>(T i) { }
void M<T>()
{
$$";
await VerifyItemExistsAsync(markup, "M", displayTextSuffix: "<>", expectedDescriptionOrNull: $"void C.M<T>(T i) (+ 1 {FeaturesResources.generic_overload})");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionWith2GenericOverloads()
{
var markup = @"
class C
{
void M<T>(int i) { }
void M<T>(out int i) { }
void M<T>()
{
$$";
await VerifyItemExistsAsync(markup, "M", displayTextSuffix: "<>", expectedDescriptionOrNull: $"void C.M<T>(int i) (+ 2 {FeaturesResources.generic_overloads})");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionNamedGenericType()
{
var markup = @"
class C<T>
{
void M()
{
$$";
await VerifyItemExistsAsync(markup, "C", displayTextSuffix: "<>", expectedDescriptionOrNull: "class C<T>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionParameter()
{
var markup = @"
class C<T>
{
void M(T goo)
{
$$";
await VerifyItemExistsAsync(markup, "goo", expectedDescriptionOrNull: $"({FeaturesResources.parameter}) T goo");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionGenericTypeParameter()
{
var markup = @"
class C<T>
{
void M()
{
$$";
await VerifyItemExistsAsync(markup, "T", expectedDescriptionOrNull: $"T {FeaturesResources.in_} C<T>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionAnonymousType()
{
var markup = @"
class C
{
void M()
{
var a = new { };
$$
";
var expectedDescription =
$@"({FeaturesResources.local_variable}) 'a a
{FeaturesResources.Anonymous_Types_colon}
'a {FeaturesResources.is_} new {{ }}";
await VerifyItemExistsAsync(markup, "a", expectedDescription);
}
[WorkItem(543288, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543288")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterNewInAnonymousType()
{
var markup = @"
class Program {
string field = 0;
static void Main() {
var an = new { new $$ };
}
}
";
await VerifyItemExistsAsync(markup, "Program");
}
[WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceFieldsInStaticMethod()
{
var markup = @"
class C
{
int x = 0;
static void M()
{
$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "x");
}
[WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceFieldsInStaticFieldInitializer()
{
var markup = @"
class C
{
int x = 0;
static int y = $$
}
";
await VerifyItemIsAbsentAsync(markup, "x");
}
[WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticFieldsInStaticMethod()
{
var markup = @"
class C
{
static int x = 0;
static void M()
{
$$
}
}
";
await VerifyItemExistsAsync(markup, "x");
}
[WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticFieldsInStaticFieldInitializer()
{
var markup = @"
class C
{
static int x = 0;
static int y = $$
}
";
await VerifyItemExistsAsync(markup, "x");
}
[WorkItem(543680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543680")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceFieldsFromOuterClassInInstanceMethod()
{
var markup = @"
class outer
{
int i;
class inner
{
void M()
{
$$
}
}
}
";
await VerifyItemIsAbsentAsync(markup, "i");
}
[WorkItem(543680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543680")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticFieldsFromOuterClassInInstanceMethod()
{
var markup = @"
class outer
{
static int i;
class inner
{
void M()
{
$$
}
}
}
";
await VerifyItemExistsAsync(markup, "i");
}
[WorkItem(543104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543104")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OnlyEnumMembersInEnumMemberAccess()
{
var markup = @"
class C
{
enum x {a,b,c}
void M()
{
x.$$
}
}
";
await VerifyItemExistsAsync(markup, "a");
await VerifyItemExistsAsync(markup, "b");
await VerifyItemExistsAsync(markup, "c");
await VerifyItemIsAbsentAsync(markup, "Equals");
}
[WorkItem(543104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543104")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoEnumMembersInEnumLocalAccess()
{
var markup = @"
class C
{
enum x {a,b,c}
void M()
{
var y = x.a;
y.$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "a");
await VerifyItemIsAbsentAsync(markup, "b");
await VerifyItemIsAbsentAsync(markup, "c");
await VerifyItemExistsAsync(markup, "Equals");
}
[WorkItem(529138, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529138")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterLambdaParameterDot()
{
var markup = @"
using System;
using System.Linq;
class A
{
public event Func<String, String> E;
}
class Program
{
static void Main(string[] args)
{
new A().E += ss => ss.$$
}
}
";
await VerifyItemExistsAsync(markup, "Substring");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotAtRoot_Interactive()
{
await VerifyItemIsAbsentAsync(
@"$$",
"value",
expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotAfterClass_Interactive()
{
await VerifyItemIsAbsentAsync(
@"class C { }
$$",
"value",
expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotAfterGlobalStatement_Interactive()
{
await VerifyItemIsAbsentAsync(
@"System.Console.WriteLine();
$$",
"value",
expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotAfterGlobalVariableDeclaration_Interactive()
{
await VerifyItemIsAbsentAsync(
@"int i = 0;
$$",
"value",
expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotInUsingAlias()
{
await VerifyItemIsAbsentAsync(
@"using Goo = $$",
"value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotInEmptyStatement()
{
await VerifyItemIsAbsentAsync(AddInsideMethod(
@"$$"),
"value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueInsideSetter()
{
await VerifyItemExistsAsync(
@"class C {
int Goo {
set {
$$",
"value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueInsideAdder()
{
await VerifyItemExistsAsync(
@"class C {
event int Goo {
add {
$$",
"value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueInsideRemover()
{
await VerifyItemExistsAsync(
@"class C {
event int Goo {
remove {
$$",
"value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotAfterDot()
{
await VerifyItemIsAbsentAsync(
@"class C {
int Goo {
set {
this.$$",
"value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotAfterArrow()
{
await VerifyItemIsAbsentAsync(
@"class C {
int Goo {
set {
a->$$",
"value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotAfterColonColon()
{
await VerifyItemIsAbsentAsync(
@"class C {
int Goo {
set {
a::$$",
"value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotInGetter()
{
await VerifyItemIsAbsentAsync(
@"class C {
int Goo {
get {
$$",
"value");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterNullableType()
{
await VerifyItemIsAbsentAsync(
@"class C {
void M() {
int goo = 0;
C? $$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterNullableTypeAlias()
{
await VerifyItemIsAbsentAsync(
@"using A = System.Int32;
class C {
void M() {
int goo = 0;
A? $$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotAfterNullableTypeAndPartialIdentifier()
{
await VerifyItemIsAbsentAsync(
@"class C {
void M() {
int goo = 0;
C? f$$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterQuestionMarkInConditional()
{
await VerifyItemExistsAsync(
@"class C {
void M() {
bool b = false;
int goo = 0;
b? $$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterQuestionMarkAndPartialIdentifierInConditional()
{
await VerifyItemExistsAsync(
@"class C {
void M() {
bool b = false;
int goo = 0;
b? f$$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterPointerType()
{
await VerifyItemIsAbsentAsync(
@"class C {
void M() {
int goo = 0;
C* $$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterPointerTypeAlias()
{
await VerifyItemIsAbsentAsync(
@"using A = System.Int32;
class C {
void M() {
int goo = 0;
A* $$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterPointerTypeAndPartialIdentifier()
{
await VerifyItemIsAbsentAsync(
@"class C {
void M() {
int goo = 0;
C* f$$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterAsteriskInMultiplication()
{
await VerifyItemExistsAsync(
@"class C {
void M() {
int i = 0;
int goo = 0;
i* $$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterAsteriskAndPartialIdentifierInMultiplication()
{
await VerifyItemExistsAsync(
@"class C {
void M() {
int i = 0;
int goo = 0;
i* f$$",
"goo");
}
[WorkItem(543868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543868")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterEventFieldDeclaredInSameType()
{
await VerifyItemExistsAsync(
@"class C {
public event System.EventHandler E;
void M() {
E.$$",
"Invoke");
}
[WorkItem(543868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543868")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterFullEventDeclaredInSameType()
{
await VerifyItemIsAbsentAsync(
@"class C {
public event System.EventHandler E { add { } remove { } }
void M() {
E.$$",
"Invoke");
}
[WorkItem(543868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543868")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterEventDeclaredInDifferentType()
{
await VerifyItemIsAbsentAsync(
@"class C {
void M() {
System.Console.CancelKeyPress.$$",
"Invoke");
}
[WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInObjectInitializerMemberContext()
{
await VerifyItemIsAbsentAsync(@"
class C
{
public int x, y;
void M()
{
var c = new C { x = 2, y = 3, $$",
"x");
}
[WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task AfterPointerMemberAccess()
{
await VerifyItemExistsAsync(@"
struct MyStruct
{
public int MyField;
}
class Program
{
static unsafe void Main(string[] args)
{
MyStruct s = new MyStruct();
MyStruct* ptr = &s;
ptr->$$
}}",
"MyField");
}
// After @ both X and XAttribute are legal. We think this is an edge case in the language and
// are not fixing the bug 11931. This test captures that XAttribute doesn't show up indeed.
[WorkItem(11931, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task VerbatimAttributes()
{
var code = @"
using System;
public class X : Attribute
{ }
public class XAttribute : Attribute
{ }
[@X$$]
class Class3 { }
";
await VerifyItemExistsAsync(code, "X");
await Assert.ThrowsAsync<Xunit.Sdk.TrueException>(() => VerifyItemExistsAsync(code, "XAttribute"));
}
[WorkItem(544928, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544928")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task InForLoopIncrementor1()
{
await VerifyItemExistsAsync(@"
using System;
class Program
{
static void Main()
{
for (; ; $$
}
}
", "Console");
}
[WorkItem(544928, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544928")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task InForLoopIncrementor2()
{
await VerifyItemExistsAsync(@"
using System;
class Program
{
static void Main()
{
for (; ; Console.WriteLine(), $$
}
}
", "Console");
}
[WorkItem(544931, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544931")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task InForLoopInitializer1()
{
await VerifyItemExistsAsync(@"
using System;
class Program
{
static void Main()
{
for ($$
}
}
", "Console");
}
[WorkItem(544931, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544931")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task InForLoopInitializer2()
{
await VerifyItemExistsAsync(@"
using System;
class Program
{
static void Main()
{
for (Console.WriteLine(), $$
}
}
", "Console");
}
[WorkItem(10572, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LocalVariableInItsDeclaration()
{
// "int goo = goo = 1" is a legal declaration
await VerifyItemExistsAsync(@"
class Program
{
void M()
{
int goo = $$
}
}", "goo");
}
[WorkItem(10572, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LocalVariableInItsDeclarator()
{
// "int bar = bar = 1" is legal in a declarator
await VerifyItemExistsAsync(@"
class Program
{
void M()
{
int goo = 0, int bar = $$, int baz = 0;
}
}", "bar");
}
[WorkItem(10572, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LocalVariableNotBeforeDeclaration()
{
await VerifyItemIsAbsentAsync(@"
class Program
{
void M()
{
$$
int goo = 0;
}
}", "goo");
}
[WorkItem(10572, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LocalVariableNotBeforeDeclarator()
{
await VerifyItemIsAbsentAsync(@"
class Program
{
void M()
{
int goo = $$, bar = 0;
}
}", "bar");
}
[WorkItem(10572, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LocalVariableAfterDeclarator()
{
await VerifyItemExistsAsync(@"
class Program
{
void M()
{
int goo = 0, int bar = $$
}
}", "goo");
}
[WorkItem(10572, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LocalVariableAsOutArgumentInInitializerExpression()
{
await VerifyItemExistsAsync(@"
class Program
{
void M()
{
int goo = Bar(out $$
}
int Bar(out int x)
{
x = 3;
return 5;
}
}", "goo");
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Method_BrowsableStateAlways()
{
var markup = @"
class Program
{
void M()
{
Goo.$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Method_BrowsableStateNever()
{
var markup = @"
class Program
{
void M()
{
Goo.$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Method_BrowsableStateAdvanced()
{
var markup = @"
class Program
{
void M()
{
Goo.$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public static void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Method_Overloads_BothBrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
Goo.$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar()
{
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar(int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 2,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Method_Overloads_OneBrowsableAlways_OneBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
Goo.$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar()
{
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static void Bar(int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Method_Overloads_BothBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
Goo.$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static void Bar()
{
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static void Bar(int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_ExtensionMethod_BrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
}
public static class GooExtensions
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar(this Goo goo, int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_ExtensionMethod_BrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
}
public static class GooExtensions
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static void Bar(this Goo goo, int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_ExtensionMethod_BrowsableAdvanced()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
}
public static class GooExtensions
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public static void Bar(this Goo goo, int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_ExtensionMethod_BrowsableMixed()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
}
public static class GooExtensions
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar(this Goo goo, int x)
{
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static void Bar(this Goo goo, int x, int y)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_OverloadExtensionMethodAndMethod_BrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public void Bar(int x)
{
}
}
public static class GooExtensions
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar(this Goo goo, int x, int y)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 2,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_OverloadExtensionMethodAndMethod_BrowsableMixed()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Bar(int x)
{
}
}
public static class GooExtensions
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar(this Goo goo, int x, int y)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_SameSigExtensionMethodAndMethod_InstanceMethodBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Bar(int x)
{
}
}
public static class GooExtensions
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar(this Goo goo, int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OverriddenSymbolsFilteredFromCompletionList()
{
var markup = @"
class Program
{
void M()
{
D d = new D();
d.$$
}
}";
var referencedCode = @"
public class B
{
public virtual void Goo(int original)
{
}
}
public class D : B
{
public override void Goo(int derived)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverClass()
{
var markup = @"
class Program
{
void M()
{
C c = new C();
c.$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public class C
{
public void Goo()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverBaseClass()
{
var markup = @"
class Program
{
void M()
{
D d = new D();
d.$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public class B
{
public void Goo()
{
}
}
public class D : B
{
public void Goo(int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 2,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_BrowsableStateNeverMethodsInBaseClass()
{
var markup = @"
class Program : B
{
void M()
{
$$
}
}";
var referencedCode = @"
public class B
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
var ci = new C<int>();
ci.$$
}
}";
var referencedCode = @"
public class C<T>
{
public void Goo(T t) { }
public void Goo(int i) { }
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 2,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed1()
{
var markup = @"
class Program
{
void M()
{
var ci = new C<int>();
ci.$$
}
}";
var referencedCode = @"
public class C<T>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo(T t) { }
public void Goo(int i) { }
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed2()
{
var markup = @"
class Program
{
void M()
{
var ci = new C<int>();
ci.$$
}
}";
var referencedCode = @"
public class C<T>
{
public void Goo(T t) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo(int i) { }
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
var ci = new C<int>();
ci.$$
}
}";
var referencedCode = @"
public class C<T>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo(T t) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo(int i) { }
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
var cii = new C<int, int>();
cii.$$
}
}";
var referencedCode = @"
public class C<T, U>
{
public void Goo(T t) { }
public void Goo(U u) { }
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 2,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_GenericType2CausingMethodSignatureEquality_BrowsableMixed()
{
var markup = @"
class Program
{
void M()
{
var cii = new C<int, int>();
cii.$$
}
}";
var referencedCode = @"
public class C<T, U>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo(T t) { }
public void Goo(U u) { }
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
var cii = new C<int, int>();
cii.$$
}
}";
var referencedCode = @"
public class C<T, U>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo(T t) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo(U u) { }
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Field_BrowsableStateNever()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Field_BrowsableStateAlways()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Field_BrowsableStateAdvanced()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
}
[WorkItem(522440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/522440")]
[WorkItem(674611, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/674611")]
[WpfFact(Skip = "674611"), Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Property_BrowsableStateNever()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public int Bar {get; set;}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Property_IgnoreBrowsabilityOfGetSetMethods()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
public int Bar {
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
get { return 5; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
set { }
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Property_BrowsableStateAlways()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public int Bar {get; set;}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Property_BrowsableStateAdvanced()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public int Bar {get; set;}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Constructor_BrowsableStateNever()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public Goo()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Constructor_BrowsableStateAlways()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public Goo()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Constructor_BrowsableStateAdvanced()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public Goo()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Constructor_MixedOverloads1()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public Goo()
{
}
public Goo(int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Constructor_MixedOverloads2()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public Goo()
{
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public Goo(int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Event_BrowsableStateNever()
{
var markup = @"
class Program
{
void M()
{
new C().$$
}
}";
var referencedCode = @"
public delegate void Handler();
public class C
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public event Handler Changed;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Changed",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Event_BrowsableStateAlways()
{
var markup = @"
class Program
{
void M()
{
new C().$$
}
}";
var referencedCode = @"
public delegate void Handler();
public class C
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public event Handler Changed;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Changed",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Event_BrowsableStateAdvanced()
{
var markup = @"
class Program
{
void M()
{
new C().$$
}
}";
var referencedCode = @"
public delegate void Handler();
public class C
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public event Handler Changed;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Changed",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Changed",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Delegate_BrowsableStateNever()
{
var markup = @"
class Program
{
public event $$
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public delegate void Handler();";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Handler",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Delegate_BrowsableStateAlways()
{
var markup = @"
class Program
{
public event $$
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public delegate void Handler();";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Handler",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Delegate_BrowsableStateAdvanced()
{
var markup = @"
class Program
{
public event $$
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public delegate void Handler();";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Handler",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Handler",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateNever_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateNever_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateNever_FullyQualifiedInUsing()
{
var markup = @"
class Program
{
void M()
{
using (var x = new NS.$$
}
}";
var referencedCode = @"
namespace NS
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public class Goo : System.IDisposable
{
public void Dispose()
{
}
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateAlways_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateAlways_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateAlways_FullyQualifiedInUsing()
{
var markup = @"
class Program
{
void M()
{
using (var x = new NS.$$
}
}";
var referencedCode = @"
namespace NS
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public class Goo : System.IDisposable
{
public void Dispose()
{
}
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateAdvanced_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateAdvanced_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateAdvanced_FullyQualifiedInUsing()
{
var markup = @"
class Program
{
void M()
{
using (var x = new NS.$$
}
}";
var referencedCode = @"
namespace NS
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public class Goo : System.IDisposable
{
public void Dispose()
{
}
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_IgnoreBaseClassBrowsableNever()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
public class Goo : Bar
{
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public class Bar
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Struct_BrowsableStateNever_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public struct Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Struct_BrowsableStateNever_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public struct Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Struct_BrowsableStateAlways_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public struct Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Struct_BrowsableStateAlways_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public struct Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Struct_BrowsableStateAdvanced_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public struct Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Struct_BrowsableStateAdvanced_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public struct Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Enum_BrowsableStateNever()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public enum Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Enum_BrowsableStateAlways()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public enum Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Enum_BrowsableStateAdvanced()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public enum Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Interface_BrowsableStateNever_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public interface Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Interface_BrowsableStateNever_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public interface Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Interface_BrowsableStateAlways_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public interface Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Interface_BrowsableStateAlways_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public interface Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Interface_BrowsableStateAdvanced_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public interface Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Interface_BrowsableStateAdvanced_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public interface Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_CrossLanguage_CStoVB_Always()
{
var markup = @"
class Program
{
void M()
{
$$
}
}";
var referencedCode = @"
<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)>
Public Class Goo
End Class";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.VisualBasic,
hideAdvancedMembers: false);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_CrossLanguage_CStoVB_Never()
{
var markup = @"
class Program
{
void M()
{
$$
}
}";
var referencedCode = @"
<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)>
Public Class Goo
End Class";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 0,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.VisualBasic,
hideAdvancedMembers: false);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibType_NotHidden()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
[System.Runtime.InteropServices.TypeLibType(System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibType_Hidden()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
[System.Runtime.InteropServices.TypeLibType(System.Runtime.InteropServices.TypeLibTypeFlags.FHidden)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibType_HiddenAndOtherFlags()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
[System.Runtime.InteropServices.TypeLibType(System.Runtime.InteropServices.TypeLibTypeFlags.FHidden | System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibType_NotHidden_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
[System.Runtime.InteropServices.TypeLibType((short)System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibType_Hidden_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
[System.Runtime.InteropServices.TypeLibType((short)System.Runtime.InteropServices.TypeLibTypeFlags.FHidden)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibType_HiddenAndOtherFlags_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
[System.Runtime.InteropServices.TypeLibType((short)(System.Runtime.InteropServices.TypeLibTypeFlags.FHidden | System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed))]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibFunc_NotHidden()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibFunc(System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable)]
public void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibFunc_Hidden()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibFunc(System.Runtime.InteropServices.TypeLibFuncFlags.FHidden)]
public void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibFunc_HiddenAndOtherFlags()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibFunc(System.Runtime.InteropServices.TypeLibFuncFlags.FHidden | System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable)]
public void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibFunc_NotHidden_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibFunc((short)System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable)]
public void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibFunc_Hidden_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibFunc((short)System.Runtime.InteropServices.TypeLibFuncFlags.FHidden)]
public void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibFunc_HiddenAndOtherFlags_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibFunc((short)(System.Runtime.InteropServices.TypeLibFuncFlags.FHidden | System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable))]
public void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibVar_NotHidden()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibVar(System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable)]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibVar_Hidden()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibVar(System.Runtime.InteropServices.TypeLibVarFlags.FHidden)]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibVar_HiddenAndOtherFlags()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibVar(System.Runtime.InteropServices.TypeLibVarFlags.FHidden | System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable)]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibVar_NotHidden_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibVar((short)System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable)]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibVar_Hidden_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibVar((short)System.Runtime.InteropServices.TypeLibVarFlags.FHidden)]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibVar_HiddenAndOtherFlags_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibVar((short)(System.Runtime.InteropServices.TypeLibVarFlags.FHidden | System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable))]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(545557, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545557")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestColorColor1()
{
var markup = @"
class A
{
static void Goo() { }
void Bar() { }
static void Main()
{
A A = new A();
A.$$
}
}";
await VerifyItemExistsAsync(markup, "Goo");
await VerifyItemExistsAsync(markup, "Bar");
}
[WorkItem(545647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545647")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestLaterLocalHidesType1()
{
var markup = @"
using System;
class C
{
public static void Main()
{
$$
Console.WriteLine();
}
}";
await VerifyItemExistsAsync(markup, "Console");
}
[WorkItem(545647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545647")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestLaterLocalHidesType2()
{
var markup = @"
using System;
class C
{
public static void Main()
{
C$$
Console.WriteLine();
}
}";
await VerifyItemExistsAsync(markup, "Console");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestIndexedProperty()
{
var markup = @"class Program
{
void M()
{
CCC c = new CCC();
c.$$
}
}";
// Note that <COMImport> is required by compiler. Bug 17013 tracks enabling indexed property for non-COM types.
var referencedCode = @"Imports System.Runtime.InteropServices
<ComImport()>
<GuidAttribute(CCC.ClassId)>
Public Class CCC
#Region ""COM GUIDs""
Public Const ClassId As String = ""9d965fd2-1514-44f6-accd-257ce77c46b0""
Public Const InterfaceId As String = ""a9415060-fdf0-47e3-bc80-9c18f7f39cf6""
Public Const EventsId As String = ""c6a866a5-5f97-4b53-a5df-3739dc8ff1bb""
# End Region
''' <summary>
''' An index property from VB
''' </summary>
''' <param name=""p1"">p1 is an integer index</param>
''' <returns>A string</returns>
Public Property IndexProp(ByVal p1 As Integer, Optional ByVal p2 As Integer = 0) As String
Get
Return Nothing
End Get
Set(ByVal value As String)
End Set
End Property
End Class";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "IndexProp",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.VisualBasic);
}
[WorkItem(546841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546841")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestDeclarationAmbiguity()
{
var markup = @"
using System;
class Program
{
void Main()
{
Environment.$$
var v;
}
}";
await VerifyItemExistsAsync(markup, "CommandLine");
}
[WorkItem(12781, "https://github.com/dotnet/roslyn/issues/12781")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestFieldDeclarationAmbiguity()
{
var markup = @"
using System;
Environment.$$
var v;
}";
await VerifyItemExistsAsync(markup, "CommandLine", sourceCodeKind: SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestCursorOnClassCloseBrace()
{
var markup = @"
using System;
class Outer
{
class Inner { }
$$}";
await VerifyItemExistsAsync(markup, "Inner");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterAsync1()
{
var markup = @"
using System.Threading.Tasks;
class Program
{
async $$
}";
await VerifyItemExistsAsync(markup, "Task");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterAsync2()
{
var markup = @"
using System.Threading.Tasks;
class Program
{
public async T$$
}";
await VerifyItemExistsAsync(markup, "Task");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterAsyncInMethodBody()
{
var markup = @"
using System.Threading.Tasks;
class Program
{
void goo()
{
var x = async $$
}
}";
await VerifyItemIsAbsentAsync(markup, "Task");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAwaitable1()
{
var markup = @"
class Program
{
void goo()
{
$$
}
}";
await VerifyItemWithMscorlib45Async(markup, "goo", "void Program.goo()", "C#");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAwaitable2()
{
var markup = @"
class Program
{
async void goo()
{
$$
}
}";
await VerifyItemWithMscorlib45Async(markup, "goo", "void Program.goo()", "C#");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Awaitable1()
{
var markup = @"
using System.Threading;
using System.Threading.Tasks;
class Program
{
async Task goo()
{
$$
}
}";
var description = $@"({CSharpFeaturesResources.awaitable}) Task Program.goo()";
await VerifyItemWithMscorlib45Async(markup, "goo", description, "C#");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Awaitable2()
{
var markup = @"
using System.Threading.Tasks;
class Program
{
async Task<int> goo()
{
$$
}
}";
var description = $@"({CSharpFeaturesResources.awaitable}) Task<int> Program.goo()";
await VerifyItemWithMscorlib45Async(markup, "goo", description, "C#");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AwaitableDotsLikeRangeExpression()
{
var markup = @"
using System.IO;
using System.Threading.Tasks;
namespace N
{
class C
{
async Task M()
{
var request = new Request();
var m = await request.$$.ReadAsStreamAsync();
}
}
class Request
{
public Task<Stream> ReadAsStreamAsync() => null;
}
}";
await VerifyItemExistsAsync(markup, "ReadAsStreamAsync");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AwaitableDotsLikeRangeExpressionWithParentheses()
{
var markup = @"
using System.IO;
using System.Threading.Tasks;
namespace N
{
class C
{
async Task M()
{
var request = new Request();
var m = (await request).$$.ReadAsStreamAsync();
}
}
class Request
{
public Task<Stream> ReadAsStreamAsync() => null;
}
}";
// Nothing should be found: no awaiter for request.
await VerifyItemIsAbsentAsync(markup, "Result");
await VerifyItemIsAbsentAsync(markup, "ReadAsStreamAsync");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AwaitableDotsLikeRangeExpressionWithTaskAndParentheses()
{
var markup = @"
using System.IO;
using System.Threading.Tasks;
namespace N
{
class C
{
async Task M()
{
var request = new Task<Request>();
var m = (await request).$$.ReadAsStreamAsync();
}
}
class Request
{
public Task<Stream> ReadAsStreamAsync() => null;
}
}";
await VerifyItemIsAbsentAsync(markup, "Result");
await VerifyItemExistsAsync(markup, "ReadAsStreamAsync");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ObsoleteItem()
{
var markup = @"
using System;
class Program
{
[Obsolete]
public void goo()
{
$$
}
}";
await VerifyItemExistsAsync(markup, "goo", $"[{CSharpFeaturesResources.deprecated}] void Program.goo()");
}
[WorkItem(568986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568986")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoMembersOnDottingIntoUnboundType()
{
var markup = @"
class Program
{
RegistryKey goo;
static void Main(string[] args)
{
goo.$$
}
}";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(550717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/550717")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeArgumentsInConstraintAfterBaselist()
{
var markup = @"
public class Goo<T> : System.Object where $$
{
}";
await VerifyItemExistsAsync(markup, "T");
}
[WorkItem(647175, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/647175")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoDestructor()
{
var markup = @"
class C
{
~C()
{
$$
";
await VerifyItemIsAbsentAsync(markup, "Finalize");
}
[WorkItem(669624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/669624")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExtensionMethodOnCovariantInterface()
{
var markup = @"
class Schema<T> { }
interface ISet<out T> { }
static class SetMethods
{
public static void ForSchemaSet<T>(this ISet<Schema<T>> set) { }
}
class Context
{
public ISet<T> Set<T>() { return null; }
}
class CustomSchema : Schema<int> { }
class Program
{
static void Main(string[] args)
{
var set = new Context().Set<CustomSchema>();
set.$$
";
await VerifyItemExistsAsync(markup, "ForSchemaSet", displayTextSuffix: "<>", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(667752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667752")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForEachInsideParentheses()
{
var markup = @"
using System;
class C
{
void M()
{
foreach($$)
";
await VerifyItemExistsAsync(markup, "String");
}
[WorkItem(766869, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766869")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestFieldInitializerInP2P()
{
var markup = @"
class Class
{
int i = Consts.$$;
}";
var referencedCode = @"
public static class Consts
{
public const int C = 1;
}";
await VerifyItemWithProjectReferenceAsync(markup, referencedCode, "C", 1, LanguageNames.CSharp, LanguageNames.CSharp, false);
}
[WorkItem(834605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834605")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ShowWithEqualsSign()
{
var markup = @"
class c { public int value {set; get; }}
class d
{
void goo()
{
c goo = new c { value$$=
}
}";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(825661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825661")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NothingAfterThisDotInStaticContext()
{
var markup = @"
class C
{
void M1() { }
static void M2()
{
this.$$
}
}";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(825661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825661")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NothingAfterBaseDotInStaticContext()
{
var markup = @"
class C
{
void M1() { }
static void M2()
{
base.$$
}
}";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(7648, "http://github.com/dotnet/roslyn/issues/7648")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NothingAfterBaseDotInScriptContext()
=> await VerifyItemIsAbsentAsync(@"base.$$", @"ToString", sourceCodeKind: SourceCodeKind.Script);
[WorkItem(858086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858086")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoNestedTypeWhenDisplayingInstance()
{
var markup = @"
class C
{
class D
{
}
void M2()
{
new C().$$
}
}";
await VerifyItemIsAbsentAsync(markup, "D");
}
[WorkItem(876031, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/876031")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CatchVariableInExceptionFilter()
{
var markup = @"
class C
{
void M()
{
try
{
}
catch (System.Exception myExn) when ($$";
await VerifyItemExistsAsync(markup, "myExn");
}
[WorkItem(849698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849698")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionAfterExternAlias()
{
var markup = @"
class C
{
void goo()
{
global::$$
}
}";
await VerifyItemExistsAsync(markup, "System", usePreviousCharAsTrigger: true);
}
[WorkItem(849698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849698")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExternAliasSuggested()
{
var markup = @"
extern alias Bar;
class C
{
void goo()
{
$$
}
}";
await VerifyItemWithAliasedMetadataReferencesAsync(markup, "Bar", "Bar", 1, "C#", "C#", false);
}
[WorkItem(635957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635957")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ClassDestructor()
{
var markup = @"
class C
{
class N
{
~$$
}
}";
await VerifyItemExistsAsync(markup, "N");
await VerifyItemIsAbsentAsync(markup, "C");
}
[WorkItem(635957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635957")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")]
public async Task TildeOutsideClass()
{
var markup = @"
class C
{
class N
{
}
}
~$$";
await VerifyItemExistsAsync(markup, "C");
await VerifyItemIsAbsentAsync(markup, "N");
}
[WorkItem(635957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635957")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StructDestructor()
{
var markup = @"
struct C
{
~$$
}";
await VerifyItemIsAbsentAsync(markup, "C");
}
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData("record")]
[InlineData("record class")]
public async Task RecordDestructor(string record)
{
var markup = $@"
{record} C
{{
~$$
}}";
await VerifyItemExistsAsync(markup, "C");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task RecordStructDestructor()
{
var markup = $@"
record struct C
{{
~$$
}}";
await VerifyItemIsAbsentAsync(markup, "C");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FieldAvailableInBothLinkedFiles()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
int x;
void goo()
{
$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
await VerifyItemInLinkedFilesAsync(markup, "x", $"({FeaturesResources.field}) int C.x");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FieldUnavailableInOneLinkedFile()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if GOO
int x;
#endif
void goo()
{
$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({FeaturesResources.field}) int C.x\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}";
await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FieldUnavailableInTwoLinkedFiles()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if GOO
int x;
#endif
void goo()
{
$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({FeaturesResources.field}) int C.x\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}";
await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExcludeFilesWithInactiveRegions()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO,BAR"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if GOO
int x;
#endif
#if BAR
void goo()
{
$$
}
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs"" />
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({FeaturesResources.field}) int C.x\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}";
await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UnionOfItemsFromBothContexts()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if GOO
int x;
#endif
#if BAR
class G
{
public void DoGStuff() {}
}
#endif
void goo()
{
new G().$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""BAR"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"void G.DoGStuff()\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}";
await VerifyItemInLinkedFilesAsync(markup, "DoGStuff", expectedDescription);
}
[WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LocalsValidInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
void M()
{
int xyz;
$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({FeaturesResources.local_variable}) int xyz";
await VerifyItemInLinkedFilesAsync(markup, "xyz", expectedDescription);
}
[WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LocalWarningInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""PROJ1"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
void M()
{
#if PROJ1
int xyz;
#endif
$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({FeaturesResources.local_variable}) int xyz\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}";
await VerifyItemInLinkedFilesAsync(markup, "xyz", expectedDescription);
}
[WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LabelsValidInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
void M()
{
LABEL: int xyz;
goto $$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({FeaturesResources.label}) LABEL";
await VerifyItemInLinkedFilesAsync(markup, "LABEL", expectedDescription);
}
[WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task RangeVariablesValidInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
using System.Linq;
class C
{
void M()
{
var x = from y in new[] { 1, 2, 3 } select $$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({FeaturesResources.range_variable}) ? y";
await VerifyItemInLinkedFilesAsync(markup, "y", expectedDescription);
}
[WorkItem(1063403, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1063403")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodOverloadDifferencesIgnored()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if ONE
void Do(int x){}
#endif
#if TWO
void Do(string x){}
#endif
void Shared()
{
$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"void C.Do(int x)";
await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodOverloadDifferencesIgnored_ExtensionMethod()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if ONE
void Do(int x){}
#endif
void Shared()
{
this.$$
}
}
public static class Extensions
{
#if TWO
public static void Do (this C c, string x)
{
}
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"void C.Do(int x)";
await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodOverloadDifferencesIgnored_ExtensionMethod2()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""TWO"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if ONE
void Do(int x){}
#endif
void Shared()
{
this.$$
}
}
public static class Extensions
{
#if TWO
public static void Do (this C c, string x)
{
}
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""ONE"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({CSharpFeaturesResources.extension}) void C.Do(string x)";
await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodOverloadDifferencesIgnored_ContainingType()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
void Shared()
{
var x = GetThing();
x.$$
}
#if ONE
private Methods1 GetThing()
{
return new Methods1();
}
#endif
#if TWO
private Methods2 GetThing()
{
return new Methods2();
}
#endif
}
#if ONE
public class Methods1
{
public void Do(string x) { }
}
#endif
#if TWO
public class Methods2
{
public void Do(string x) { }
}
#endif
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"void Methods1.Do(string x)";
await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SharedProjectFieldAndPropertiesTreatedAsIdentical()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if ONE
public int x;
#endif
#if TWO
public int x {get; set;}
#endif
void goo()
{
x$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({ FeaturesResources.field }) int C.x";
await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SharedProjectFieldAndPropertiesTreatedAsIdentical2()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if TWO
public int x;
#endif
#if ONE
public int x {get; set;}
#endif
void goo()
{
x$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = "int C.x { get; set; }";
await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConditionalAccessWalkUp()
{
var markup = @"
public class B
{
public A BA;
public B BB;
}
class A
{
public A AA;
public A AB;
public int? x;
public void goo()
{
A a = null;
var q = a?.$$AB.BA.AB.BA;
}
}";
await VerifyItemExistsAsync(markup, "AA");
await VerifyItemExistsAsync(markup, "AB");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConditionalAccessNullableIsUnwrapped()
{
var markup = @"
public struct S
{
public int? i;
}
class A
{
public S? s;
public void goo()
{
A a = null;
var q = a?.s?.$$;
}
}";
await VerifyItemExistsAsync(markup, "i");
await VerifyItemIsAbsentAsync(markup, "value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConditionalAccessNullableIsUnwrapped2()
{
var markup = @"
public struct S
{
public int? i;
}
class A
{
public S? s;
public void goo()
{
var q = s?.$$i?.ToString();
}
}";
await VerifyItemExistsAsync(markup, "i");
await VerifyItemIsAbsentAsync(markup, "value");
}
[WorkItem(54361, "https://github.com/dotnet/roslyn/issues/54361")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConditionalAccessNullableIsUnwrappedOnParameter()
{
var markup = @"
class A
{
void M(System.DateTime? dt)
{
dt?.$$
}
}
";
await VerifyItemExistsAsync(markup, "Day");
await VerifyItemIsAbsentAsync(markup, "Value");
}
[WorkItem(54361, "https://github.com/dotnet/roslyn/issues/54361")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NullableIsNotUnwrappedOnParameter()
{
var markup = @"
class A
{
void M(System.DateTime? dt)
{
dt.$$
}
}
";
await VerifyItemExistsAsync(markup, "Value");
await VerifyItemIsAbsentAsync(markup, "Day");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionAfterConditionalIndexing()
{
var markup = @"
public struct S
{
public int? i;
}
class A
{
public S[] s;
public void goo()
{
A a = null;
var q = a?.s?[$$;
}
}";
await VerifyItemExistsAsync(markup, "System");
}
[WorkItem(1109319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109319")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WithinChainOfConditionalAccesses1()
{
var markup = @"
class Program
{
static void Main(string[] args)
{
A a;
var x = a?.$$b?.c?.d.e;
}
}
class A { public B b; }
class B { public C c; }
class C { public D d; }
class D { public int e; }";
await VerifyItemExistsAsync(markup, "b");
}
[WorkItem(1109319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109319")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WithinChainOfConditionalAccesses2()
{
var markup = @"
class Program
{
static void Main(string[] args)
{
A a;
var x = a?.b?.$$c?.d.e;
}
}
class A { public B b; }
class B { public C c; }
class C { public D d; }
class D { public int e; }";
await VerifyItemExistsAsync(markup, "c");
}
[WorkItem(1109319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109319")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WithinChainOfConditionalAccesses3()
{
var markup = @"
class Program
{
static void Main(string[] args)
{
A a;
var x = a?.b?.c?.$$d.e;
}
}
class A { public B b; }
class B { public C c; }
class C { public D d; }
class D { public int e; }";
await VerifyItemExistsAsync(markup, "d");
}
[WorkItem(843466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843466")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedAttributeAccessibleOnSelf()
{
var markup = @"using System;
[My]
class X
{
[My$$]
class MyAttribute : Attribute
{
}
}";
await VerifyItemExistsAsync(markup, "My");
}
[WorkItem(843466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843466")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedAttributeAccessibleOnOuterType()
{
var markup = @"using System;
[My]
class Y
{
}
[$$]
class X
{
[My]
class MyAttribute : Attribute
{
}
}";
await VerifyItemExistsAsync(markup, "My");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMembersFromBaseOuterType()
{
var markup = @"abstract class Test
{
private int _field;
public sealed class InnerTest : Test
{
public void SomeTest()
{
$$
}
}
}";
await VerifyItemExistsAsync(markup, "_field");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMembersFromBaseOuterType2()
{
var markup = @"class C<T>
{
void M() { }
class N : C<int>
{
void Test()
{
$$ // M recommended and accessible
}
class NN
{
void Test2()
{
// M inaccessible and not recommended
}
}
}
}";
await VerifyItemExistsAsync(markup, "M");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMembersFromBaseOuterType3()
{
var markup = @"class C<T>
{
void M() { }
class N : C<int>
{
void Test()
{
M(); // M recommended and accessible
}
class NN
{
void Test2()
{
$$ // M inaccessible and not recommended
}
}
}
}";
await VerifyItemIsAbsentAsync(markup, "M");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMembersFromBaseOuterType4()
{
var markup = @"class C<T>
{
void M() { }
class N : C<int>
{
void Test()
{
M(); // M recommended and accessible
}
class NN : N
{
void Test2()
{
$$ // M accessible and recommended.
}
}
}
}";
await VerifyItemExistsAsync(markup, "M");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMembersFromBaseOuterType5()
{
var markup = @"
class D
{
public void Q() { }
}
class C<T> : D
{
class N
{
void Test()
{
$$
}
}
}";
await VerifyItemIsAbsentAsync(markup, "Q");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMembersFromBaseOuterType6()
{
var markup = @"
class Base<T>
{
public int X;
}
class Derived : Base<int>
{
class Nested
{
void Test()
{
$$
}
}
}";
await VerifyItemIsAbsentAsync(markup, "X");
}
[WorkItem(983367, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/983367")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoTypeParametersDefinedInCrefs()
{
var markup = @"using System;
/// <see cref=""Program{T$$}""/>
class Program<T> { }";
await VerifyItemIsAbsentAsync(markup, "T");
}
[WorkItem(988025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/988025")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ShowTypesInGenericMethodTypeParameterList1()
{
var markup = @"
class Class1<T, D>
{
public static Class1<T, D> Create() { return null; }
}
static class Class2
{
public static void Test<T,D>(this Class1<T, D> arg)
{
}
}
class Program
{
static void Main(string[] args)
{
Class1<string, int>.Create().Test<$$
}
}
";
await VerifyItemExistsAsync(markup, "Class1", displayTextSuffix: "<>", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(988025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/988025")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ShowTypesInGenericMethodTypeParameterList2()
{
var markup = @"
class Class1<T, D>
{
public static Class1<T, D> Create() { return null; }
}
static class Class2
{
public static void Test<T,D>(this Class1<T, D> arg)
{
}
}
class Program
{
static void Main(string[] args)
{
Class1<string, int>.Create().Test<string,$$
}
}
";
await VerifyItemExistsAsync(markup, "Class1", displayTextSuffix: "<>", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionInAliasedType()
{
var markup = @"
using IAlias = IGoo;
///<summary>summary for interface IGoo</summary>
interface IGoo { }
class C
{
I$$
}
";
await VerifyItemExistsAsync(markup, "IAlias", expectedDescriptionOrNull: "interface IGoo\r\nsummary for interface IGoo");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WithinNameOf()
{
var markup = @"
class C
{
void goo()
{
var x = nameof($$)
}
}
";
await VerifyAnyItemExistsAsync(markup);
}
[WorkItem(997410, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/997410")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMemberInNameOfInStaticContext()
{
var markup = @"
class C
{
int y1 = 15;
static int y2 = 1;
static string x = nameof($$
";
await VerifyItemExistsAsync(markup, "y1");
}
[WorkItem(997410, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/997410")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticMemberInNameOfInStaticContext()
{
var markup = @"
class C
{
int y1 = 15;
static int y2 = 1;
static string x = nameof($$
";
await VerifyItemExistsAsync(markup, "y2");
}
[WorkItem(883293, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/883293")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task IncompleteDeclarationExpressionType()
{
var markup = @"
using System;
class C
{
void goo()
{
var x = Console.$$
var y = 3;
}
}
";
await VerifyItemExistsAsync(markup, "WriteLine");
}
[WorkItem(1024380, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024380")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticAndInstanceInNameOf()
{
var markup = @"
using System;
class C
{
class D
{
public int x;
public static int y;
}
void goo()
{
var z = nameof(C.D.$$
}
}
";
await VerifyItemExistsAsync(markup, "x");
await VerifyItemExistsAsync(markup, "y");
}
[WorkItem(1663, "https://github.com/dotnet/roslyn/issues/1663")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NameOfMembersListedForLocals()
{
var markup = @"class C
{
void M()
{
var x = nameof(T.z.$$)
}
}
public class T
{
public U z;
}
public class U
{
public int nope;
}
";
await VerifyItemExistsAsync(markup, "nope");
}
[WorkItem(1029522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029522")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NameOfMembersListedForNamespacesAndTypes2()
{
var markup = @"class C
{
void M()
{
var x = nameof(U.$$)
}
}
public class T
{
public U z;
}
public class U
{
public int nope;
}
";
await VerifyItemExistsAsync(markup, "nope");
}
[WorkItem(1029522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029522")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NameOfMembersListedForNamespacesAndTypes3()
{
var markup = @"class C
{
void M()
{
var x = nameof(N.$$)
}
}
namespace N
{
public class U
{
public int nope;
}
} ";
await VerifyItemExistsAsync(markup, "U");
}
[WorkItem(1029522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029522")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NameOfMembersListedForNamespacesAndTypes4()
{
var markup = @"
using z = System;
class C
{
void M()
{
var x = nameof(z.$$)
}
}
";
await VerifyItemExistsAsync(markup, "Console");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InterpolatedStrings1()
{
var markup = @"
class C
{
void M()
{
var a = ""Hello"";
var b = ""World"";
var c = $""{$$
";
await VerifyItemExistsAsync(markup, "a");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InterpolatedStrings2()
{
var markup = @"
class C
{
void M()
{
var a = ""Hello"";
var b = ""World"";
var c = $""{$$}"";
}
}";
await VerifyItemExistsAsync(markup, "a");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InterpolatedStrings3()
{
var markup = @"
class C
{
void M()
{
var a = ""Hello"";
var b = ""World"";
var c = $""{a}, {$$
";
await VerifyItemExistsAsync(markup, "b");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InterpolatedStrings4()
{
var markup = @"
class C
{
void M()
{
var a = ""Hello"";
var b = ""World"";
var c = $""{a}, {$$}"";
}
}";
await VerifyItemExistsAsync(markup, "b");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InterpolatedStrings5()
{
var markup = @"
class C
{
void M()
{
var a = ""Hello"";
var b = ""World"";
var c = $@""{a}, {$$
";
await VerifyItemExistsAsync(markup, "b");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InterpolatedStrings6()
{
var markup = @"
class C
{
void M()
{
var a = ""Hello"";
var b = ""World"";
var c = $@""{a}, {$$}"";
}
}";
await VerifyItemExistsAsync(markup, "b");
}
[WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotBeforeFirstStringHole()
{
await VerifyNoItemsExistAsync(AddInsideMethod(
@"var x = ""\{0}$$\{1}\{2}"""));
}
[WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotBetweenStringHoles()
{
await VerifyNoItemsExistAsync(AddInsideMethod(
@"var x = ""\{0}\{1}$$\{2}"""));
}
[WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotAfterStringHoles()
{
await VerifyNoItemsExistAsync(AddInsideMethod(
@"var x = ""\{0}\{1}\{2}$$"""));
}
[WorkItem(1087171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087171")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task CompletionAfterTypeOfGetType()
{
await VerifyItemExistsAsync(AddInsideMethod(
"typeof(int).GetType().$$"), "GUID");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingDirectives1()
{
var markup = @"
using $$
class A { }
static class B { }
namespace N
{
class C { }
static class D { }
namespace M { }
}";
await VerifyItemIsAbsentAsync(markup, "A");
await VerifyItemIsAbsentAsync(markup, "B");
await VerifyItemExistsAsync(markup, "N");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingDirectives2()
{
var markup = @"
using N.$$
class A { }
static class B { }
namespace N
{
class C { }
static class D { }
namespace M { }
}";
await VerifyItemIsAbsentAsync(markup, "C");
await VerifyItemIsAbsentAsync(markup, "D");
await VerifyItemExistsAsync(markup, "M");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingDirectives3()
{
var markup = @"
using G = $$
class A { }
static class B { }
namespace N
{
class C { }
static class D { }
namespace M { }
}";
await VerifyItemExistsAsync(markup, "A");
await VerifyItemExistsAsync(markup, "B");
await VerifyItemExistsAsync(markup, "N");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingDirectives4()
{
var markup = @"
using G = N.$$
class A { }
static class B { }
namespace N
{
class C { }
static class D { }
namespace M { }
}";
await VerifyItemExistsAsync(markup, "C");
await VerifyItemExistsAsync(markup, "D");
await VerifyItemExistsAsync(markup, "M");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingDirectives5()
{
var markup = @"
using static $$
class A { }
static class B { }
namespace N
{
class C { }
static class D { }
namespace M { }
}";
await VerifyItemExistsAsync(markup, "A");
await VerifyItemExistsAsync(markup, "B");
await VerifyItemExistsAsync(markup, "N");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingDirectives6()
{
var markup = @"
using static N.$$
class A { }
static class B { }
namespace N
{
class C { }
static class D { }
namespace M { }
}";
await VerifyItemExistsAsync(markup, "C");
await VerifyItemExistsAsync(markup, "D");
await VerifyItemExistsAsync(markup, "M");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticDoesNotShowDelegates1()
{
var markup = @"
using static $$
class A { }
delegate void B();
namespace N
{
class C { }
static class D { }
namespace M { }
}";
await VerifyItemExistsAsync(markup, "A");
await VerifyItemIsAbsentAsync(markup, "B");
await VerifyItemExistsAsync(markup, "N");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticDoesNotShowDelegates2()
{
var markup = @"
using static N.$$
class A { }
static class B { }
namespace N
{
class C { }
delegate void D();
namespace M { }
}";
await VerifyItemExistsAsync(markup, "C");
await VerifyItemIsAbsentAsync(markup, "D");
await VerifyItemExistsAsync(markup, "M");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticDoesNotShowInterfaces1()
{
var markup = @"
using static N.$$
class A { }
static class B { }
namespace N
{
class C { }
interface I { }
namespace M { }
}";
await VerifyItemExistsAsync(markup, "C");
await VerifyItemIsAbsentAsync(markup, "I");
await VerifyItemExistsAsync(markup, "M");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticDoesNotShowInterfaces2()
{
var markup = @"
using static $$
class A { }
interface I { }
namespace N
{
class C { }
static class D { }
namespace M { }
}";
await VerifyItemExistsAsync(markup, "A");
await VerifyItemIsAbsentAsync(markup, "I");
await VerifyItemExistsAsync(markup, "N");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticAndExtensionMethods1()
{
var markup = @"
using static A;
using static B;
static class A
{
public static void Goo(this string s) { }
}
static class B
{
public static void Bar(this string s) { }
}
class C
{
void M()
{
$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Goo");
await VerifyItemIsAbsentAsync(markup, "Bar");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticAndExtensionMethods2()
{
var markup = @"
using N;
namespace N
{
static class A
{
public static void Goo(this string s) { }
}
static class B
{
public static void Bar(this string s) { }
}
}
class C
{
void M()
{
$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Goo");
await VerifyItemIsAbsentAsync(markup, "Bar");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticAndExtensionMethods3()
{
var markup = @"
using N;
namespace N
{
static class A
{
public static void Goo(this string s) { }
}
static class B
{
public static void Bar(this string s) { }
}
}
class C
{
void M()
{
string s;
s.$$
}
}
";
await VerifyItemExistsAsync(markup, "Goo");
await VerifyItemExistsAsync(markup, "Bar");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticAndExtensionMethods4()
{
var markup = @"
using static N.A;
using static N.B;
namespace N
{
static class A
{
public static void Goo(this string s) { }
}
static class B
{
public static void Bar(this string s) { }
}
}
class C
{
void M()
{
string s;
s.$$
}
}
";
await VerifyItemExistsAsync(markup, "Goo");
await VerifyItemExistsAsync(markup, "Bar");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticAndExtensionMethods5()
{
var markup = @"
using static N.A;
namespace N
{
static class A
{
public static void Goo(this string s) { }
}
static class B
{
public static void Bar(this string s) { }
}
}
class C
{
void M()
{
string s;
s.$$
}
}
";
await VerifyItemExistsAsync(markup, "Goo");
await VerifyItemIsAbsentAsync(markup, "Bar");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticAndExtensionMethods6()
{
var markup = @"
using static N.B;
namespace N
{
static class A
{
public static void Goo(this string s) { }
}
static class B
{
public static void Bar(this string s) { }
}
}
class C
{
void M()
{
string s;
s.$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Goo");
await VerifyItemExistsAsync(markup, "Bar");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticAndExtensionMethods7()
{
var markup = @"
using N;
using static N.B;
namespace N
{
static class A
{
public static void Goo(this string s) { }
}
static class B
{
public static void Bar(this string s) { }
}
}
class C
{
void M()
{
string s;
s.$$;
}
}
";
await VerifyItemExistsAsync(markup, "Goo");
await VerifyItemExistsAsync(markup, "Bar");
}
[WorkItem(7932, "https://github.com/dotnet/roslyn/issues/7932")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExtensionMethodWithinSameClassOfferedForCompletion()
{
var markup = @"
public static class Test
{
static void TestB()
{
$$
}
static void TestA(this string s) { }
}
";
await VerifyItemExistsAsync(markup, "TestA");
}
[WorkItem(7932, "https://github.com/dotnet/roslyn/issues/7932")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExtensionMethodWithinParentClassOfferedForCompletion()
{
var markup = @"
public static class Parent
{
static void TestA(this string s) { }
static void TestC(string s) { }
public static class Test
{
static void TestB()
{
$$
}
}
}
";
await VerifyItemExistsAsync(markup, "TestA");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExceptionFilter1()
{
var markup = @"
using System;
class C
{
void M(bool x)
{
try
{
}
catch when ($$
";
await VerifyItemExistsAsync(markup, "x");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExceptionFilter1_NotBeforeOpenParen()
{
var markup = @"
using System;
class C
{
void M(bool x)
{
try
{
}
catch when $$
";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExceptionFilter2()
{
var markup = @"
using System;
class C
{
void M(bool x)
{
try
{
}
catch (Exception ex) when ($$
";
await VerifyItemExistsAsync(markup, "x");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExceptionFilter2_NotBeforeOpenParen()
{
var markup = @"
using System;
class C
{
void M(bool x)
{
try
{
}
catch (Exception ex) when $$
";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(25084, "https://github.com/dotnet/roslyn/issues/25084")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SwitchCaseWhenClause1()
{
var markup = @"
class C
{
void M(bool x)
{
switch (1)
{
case 1 when $$
";
await VerifyItemExistsAsync(markup, "x");
}
[WorkItem(25084, "https://github.com/dotnet/roslyn/issues/25084")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SwitchCaseWhenClause2()
{
var markup = @"
class C
{
void M(bool x)
{
switch (1)
{
case int i when $$
";
await VerifyItemExistsAsync(markup, "x");
}
[WorkItem(717, "https://github.com/dotnet/roslyn/issues/717")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExpressionContextCompletionWithinCast()
{
var markup = @"
class Program
{
void M()
{
for (int i = 0; i < 5; i++)
{
var x = ($$)
var y = 1;
}
}
}
";
await VerifyItemExistsAsync(markup, "i");
}
[WorkItem(1277, "https://github.com/dotnet/roslyn/issues/1277")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceMembersInPropertyInitializer()
{
var markup = @"
class A {
int abc;
int B { get; } = $$
}
";
await VerifyItemIsAbsentAsync(markup, "abc");
}
[WorkItem(1277, "https://github.com/dotnet/roslyn/issues/1277")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticMembersInPropertyInitializer()
{
var markup = @"
class A {
static Action s_abc;
event Action B = $$
}
";
await VerifyItemExistsAsync(markup, "s_abc");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceMembersInFieldLikeEventInitializer()
{
var markup = @"
class A {
Action abc;
event Action B = $$
}
";
await VerifyItemIsAbsentAsync(markup, "abc");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticMembersInFieldLikeEventInitializer()
{
var markup = @"
class A {
static Action s_abc;
event Action B = $$
}
";
await VerifyItemExistsAsync(markup, "s_abc");
}
[WorkItem(5069, "https://github.com/dotnet/roslyn/issues/5069")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMembersInTopLevelFieldInitializer()
{
var markup = @"
int aaa = 1;
int bbb = $$
";
await VerifyItemExistsAsync(markup, "aaa", sourceCodeKind: SourceCodeKind.Script);
}
[WorkItem(5069, "https://github.com/dotnet/roslyn/issues/5069")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMembersInTopLevelFieldLikeEventInitializer()
{
var markup = @"
Action aaa = null;
event Action bbb = $$
";
await VerifyItemExistsAsync(markup, "aaa", sourceCodeKind: SourceCodeKind.Script);
}
[WorkItem(33, "https://github.com/dotnet/roslyn/issues/33")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoConditionalAccessCompletionOnTypes1()
{
var markup = @"
using A = System
class C
{
A?.$$
}
";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(33, "https://github.com/dotnet/roslyn/issues/33")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoConditionalAccessCompletionOnTypes2()
{
var markup = @"
class C
{
System?.$$
}
";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(33, "https://github.com/dotnet/roslyn/issues/33")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoConditionalAccessCompletionOnTypes3()
{
var markup = @"
class C
{
System.Console?.$$
}
";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionInIncompletePropertyDeclaration()
{
var markup = @"
class Class1
{
public string Property1 { get; set; }
}
class Class2
{
public string Property { get { return this.Source.$$
public Class1 Source { get; set; }
}";
await VerifyItemExistsAsync(markup, "Property1");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoCompletionInShebangComments()
{
await VerifyNoItemsExistAsync("#!$$", sourceCodeKind: SourceCodeKind.Script);
await VerifyNoItemsExistAsync("#! S$$", sourceCodeKind: SourceCodeKind.Script, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompoundNameTargetTypePreselection()
{
var markup = @"
class Class1
{
void goo()
{
int x = 3;
string y = x.$$
}
}";
await VerifyItemExistsAsync(markup, "ToString", matchPriority: SymbolMatchPriority.PreferEventOrMethod);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TargetTypeInCollectionInitializer1()
{
var markup = @"
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
int z;
string q;
List<int> x = new List<int>() { $$ }
}
}";
await VerifyItemExistsAsync(markup, "z", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TargetTypeInCollectionInitializer2()
{
var markup = @"
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
int z;
string q;
List<int> x = new List<int>() { 1, $$ }
}
}";
await VerifyItemExistsAsync(markup, "z", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TargeTypeInObjectInitializer1()
{
var markup = @"
class C
{
public int X { get; set; }
public int Y { get; set; }
void goo()
{
int i;
var c = new C() { X = $$ }
}
}";
await VerifyItemExistsAsync(markup, "i", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TargeTypeInObjectInitializer2()
{
var markup = @"
class C
{
public int X { get; set; }
public int Y { get; set; }
void goo()
{
int i;
var c = new C() { X = 1, Y = $$ }
}
}";
await VerifyItemExistsAsync(markup, "i", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleElements()
{
var markup = @"
class C
{
void goo()
{
var t = (Alice: 1, Item2: 2, ITEM3: 3, 4, 5, 6, 7, 8, Bob: 9);
t.$$
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs;
await VerifyItemExistsAsync(markup, "Alice");
await VerifyItemExistsAsync(markup, "Bob");
await VerifyItemExistsAsync(markup, "CompareTo");
await VerifyItemExistsAsync(markup, "Equals");
await VerifyItemExistsAsync(markup, "GetHashCode");
await VerifyItemExistsAsync(markup, "GetType");
await VerifyItemExistsAsync(markup, "Item2");
await VerifyItemExistsAsync(markup, "ITEM3");
for (var i = 4; i <= 8; i++)
{
await VerifyItemExistsAsync(markup, "Item" + i);
}
await VerifyItemExistsAsync(markup, "ToString");
await VerifyItemIsAbsentAsync(markup, "Item1");
await VerifyItemIsAbsentAsync(markup, "Item9");
await VerifyItemIsAbsentAsync(markup, "Rest");
await VerifyItemIsAbsentAsync(markup, "Item3");
}
[WorkItem(14546, "https://github.com/dotnet/roslyn/issues/14546")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleElementsCompletionOffMethodGroup()
{
var markup = @"
class C
{
void goo()
{
new object().ToString.$$
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs;
// should not crash
await VerifyNoItemsExistAsync(markup);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.Completion)]
[CompilerTrait(CompilerFeature.LocalFunctions)]
[WorkItem(13480, "https://github.com/dotnet/roslyn/issues/13480")]
public async Task NoCompletionInLocalFuncGenericParamList()
{
var markup = @"
class C
{
void M()
{
int Local<$$";
await VerifyNoItemsExistAsync(markup);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.Completion)]
[CompilerTrait(CompilerFeature.LocalFunctions)]
[WorkItem(13480, "https://github.com/dotnet/roslyn/issues/13480")]
public async Task CompletionForAwaitWithoutAsync()
{
var markup = @"
class C
{
void M()
{
await Local<$$";
await VerifyAnyItemExistsAsync(markup);
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleTypeAtMemberLevel1()
{
await VerifyItemExistsAsync(@"
class C
{
($$
}", "C");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleTypeAtMemberLevel2()
{
await VerifyItemExistsAsync(@"
class C
{
($$)
}", "C");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleTypeAtMemberLevel3()
{
await VerifyItemExistsAsync(@"
class C
{
(C, $$
}", "C");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleTypeAtMemberLevel4()
{
await VerifyItemExistsAsync(@"
class C
{
(C, $$)
}", "C");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleTypeInForeach()
{
await VerifyItemExistsAsync(@"
class C
{
void M()
{
foreach ((C, $$
}
}", "C");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleTypeInParameterList()
{
await VerifyItemExistsAsync(@"
class C
{
void M((C, $$)
{
}
}", "C");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleTypeInNameOf()
{
await VerifyItemExistsAsync(@"
class C
{
void M()
{
var x = nameof((C, $$
}
}", "C");
}
[WorkItem(14163, "https://github.com/dotnet/roslyn/issues/14163")]
[Fact]
[Trait(Traits.Feature, Traits.Features.Completion)]
[CompilerTrait(CompilerFeature.LocalFunctions)]
public async Task LocalFunctionDescription()
{
await VerifyItemExistsAsync(@"
class C
{
void M()
{
void Local() { }
$$
}
}", "Local", "void Local()");
}
[WorkItem(14163, "https://github.com/dotnet/roslyn/issues/14163")]
[Fact]
[Trait(Traits.Feature, Traits.Features.Completion)]
[CompilerTrait(CompilerFeature.LocalFunctions)]
public async Task LocalFunctionDescription2()
{
await VerifyItemExistsAsync(@"
using System;
class C
{
class var { }
void M()
{
Action<int> Local(string x, ref var @class, params Func<int, string> f)
{
return () => 0;
}
$$
}
}", "Local", "Action<int> Local(string x, ref var @class, params Func<int, string> f)");
}
[WorkItem(18359, "https://github.com/dotnet/roslyn/issues/18359")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EnumMemberAfterDot()
{
var markup =
@"namespace ConsoleApplication253
{
class Program
{
static void Main(string[] args)
{
M(E.$$)
}
static void M(E e) { }
}
enum E
{
A,
B,
}
}
";
// VerifyItemExistsAsync also tests with the item typed.
await VerifyItemExistsAsync(markup, "A");
await VerifyItemExistsAsync(markup, "B");
}
[WorkItem(8321, "https://github.com/dotnet/roslyn/issues/8321")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotOnMethodGroup1()
{
var markup =
@"namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
Main.$$
}
}
}
";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(8321, "https://github.com/dotnet/roslyn/issues/8321")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotOnMethodGroup2()
{
var markup =
@"class C {
void M<T>() {M<C>.$$ }
}
";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(8321, "https://github.com/dotnet/roslyn/issues/8321")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotOnMethodGroup3()
{
var markup =
@"class C {
void M() {M.$$}
}
";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(420697, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=420697&_a=edit")]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/21766"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task DoNotCrashInExtensionMethoWithExpressionBodiedMember()
{
var markup =
@"public static class Extensions { public static T Get<T>(this object o) => $$}
";
await VerifyItemExistsAsync(markup, "o");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task EnumConstraint()
{
var markup =
@"public class X<T> where T : System.$$
";
await VerifyItemExistsAsync(markup, "Enum");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task DelegateConstraint()
{
var markup =
@"public class X<T> where T : System.$$
";
await VerifyItemExistsAsync(markup, "Delegate");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task MulticastDelegateConstraint()
{
var markup =
@"public class X<T> where T : System.$$
";
await VerifyItemExistsAsync(markup, "MulticastDelegate");
}
private static string CreateThenIncludeTestCode(string lambdaExpressionString, string methodDeclarationString)
{
var template = @"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace ThenIncludeIntellisenseBug
{
class Program
{
static void Main(string[] args)
{
var registrations = new List<Registration>().AsQueryable();
var reg = registrations.Include(r => r.Activities).ThenInclude([1]);
}
}
internal class Registration
{
public ICollection<Activity> Activities { get; set; }
}
public class Activity
{
public Task Task { get; set; }
}
public class Task
{
public string Name { get; set; }
}
public interface IIncludableQueryable<out TEntity, out TProperty> : IQueryable<TEntity>
{
}
public static class EntityFrameworkQuerybleExtensions
{
public static IIncludableQueryable<TEntity, TProperty> Include<TEntity, TProperty>(
this IQueryable<TEntity> source,
Expression<Func<TEntity, TProperty>> navigationPropertyPath)
where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
[2]
}
}";
return template.Replace("[1]", lambdaExpressionString).Replace("[2]", methodDeclarationString);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThenInclude()
{
var markup = CreateThenIncludeTestCode("b => b.$$",
@"
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source,
Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, TPreviousProperty> source,
Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}");
await VerifyItemExistsAsync(markup, "Task");
await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThenIncludeNoExpression()
{
var markup = CreateThenIncludeTestCode("b => b.$$",
@"
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source,
Func<TPreviousProperty, TProperty> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, TPreviousProperty> source,
Func<TPreviousProperty, TProperty> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}");
await VerifyItemExistsAsync(markup, "Task");
await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThenIncludeSecondArgument()
{
var markup = CreateThenIncludeTestCode("0, b => b.$$",
@"
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source,
int a,
Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, TPreviousProperty> source,
int a,
Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}");
await VerifyItemExistsAsync(markup, "Task");
await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThenIncludeSecondArgumentAndMultiArgumentLambda()
{
var markup = CreateThenIncludeTestCode("0, (a,b,c) => c.$$)",
@"
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source,
int a,
Expression<Func<string, string, TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, TPreviousProperty> source,
int a,
Expression<Func<string, string, TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}");
await VerifyItemExistsAsync(markup, "Task");
await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThenIncludeSecondArgumentNoOverlap()
{
var markup = CreateThenIncludeTestCode("b => b.Task, b =>b.$$",
@"
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source,
Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath,
Expression<Func<TPreviousProperty, TProperty>> anotherNavigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, TPreviousProperty> source,
Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
");
await VerifyItemExistsAsync(markup, "Task");
await VerifyItemIsAbsentAsync(markup, "FirstOrDefault", displayTextSuffix: "<>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThenIncludeSecondArgumentAndMultiArgumentLambdaWithNoLambdaOverlap()
{
var markup = CreateThenIncludeTestCode("0, (a,b,c) => c.$$",
@"
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source,
int a,
Expression<Func<string, TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, TPreviousProperty> source,
int a,
Expression<Func<string, string, TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
");
await VerifyItemIsAbsentAsync(markup, "Task");
await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>");
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/35100"), Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThenIncludeGenericAndNoGenericOverloads()
{
var markup = CreateThenIncludeTestCode("c => c.$$",
@"
public static IIncludableQueryable<Registration, Task> ThenInclude(
this IIncludableQueryable<Registration, ICollection<Activity>> source,
Func<Activity, Task> navigationPropertyPath)
{
return default(IIncludableQueryable<Registration, Task>);
}
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, TPreviousProperty> source,
Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
");
await VerifyItemExistsAsync(markup, "Task");
await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThenIncludeNoGenericOverloads()
{
var markup = CreateThenIncludeTestCode("c => c.$$",
@"
public static IIncludableQueryable<Registration, Task> ThenInclude(
this IIncludableQueryable<Registration, ICollection<Activity>> source,
Func<Activity, Task> navigationPropertyPath)
{
return default(IIncludableQueryable<Registration, Task>);
}
public static IIncludableQueryable<Registration, Activity> ThenInclude(
this IIncludableQueryable<Registration, ICollection<Activity>> source,
Func<ICollection<Activity>, Activity> navigationPropertyPath)
{
return default(IIncludableQueryable<Registration, Activity>);
}
");
await VerifyItemExistsAsync(markup, "Task");
await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionForLambdaWithOverloads()
{
var markup = @"
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace ClassLibrary1
{
class SomeItem
{
public string A;
public int B;
}
class SomeCollection<T> : List<T>
{
public virtual SomeCollection<T> Include(string path) => null;
}
static class Extensions
{
public static IList<T> Include<T, TProperty>(this IList<T> source, Expression<Func<T, TProperty>> path)
=> null;
public static IList Include(this IList source, string path) => null;
public static IList<T> Include<T>(this IList<T> source, string path) => null;
}
class Program
{
void M(SomeCollection<SomeItem> c)
{
var a = from m in c.Include(t => t.$$);
}
}
}";
await VerifyItemIsAbsentAsync(markup, "Substring");
await VerifyItemExistsAsync(markup, "A");
await VerifyItemExistsAsync(markup, "B");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(1056325, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056325")]
public async Task CompletionForLambdaWithOverloads2()
{
var markup = @"
using System;
class C
{
void M(Action<int> a) { }
void M(string s) { }
void Test()
{
M(p => p.$$);
}
}";
await VerifyItemIsAbsentAsync(markup, "Substring");
await VerifyItemExistsAsync(markup, "GetTypeCode");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(1056325, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056325")]
public async Task CompletionForLambdaWithOverloads3()
{
var markup = @"
using System;
class C
{
void M(Action<int> a) { }
void M(Action<string> a) { }
void Test()
{
M((int p) => p.$$);
}
}";
await VerifyItemIsAbsentAsync(markup, "Substring");
await VerifyItemExistsAsync(markup, "GetTypeCode");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(1056325, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056325")]
public async Task CompletionForLambdaWithOverloads4()
{
var markup = @"
using System;
class C
{
void M(Action<int> a) { }
void M(Action<string> a) { }
void Test()
{
M(p => p.$$);
}
}";
await VerifyItemExistsAsync(markup, "Substring");
await VerifyItemExistsAsync(markup, "GetTypeCode");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")]
public async Task CompletionForLambdaWithTypeParameters()
{
var markup = @"
using System;
using System.Collections.Generic;
class Program
{
static void M()
{
Create(new List<Product>(), arg => arg.$$);
}
static void Create<T>(List<T> list, Action<T> expression) { }
}
class Product { public void MyProperty() { } }";
await VerifyItemExistsAsync(markup, "MyProperty");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")]
public async Task CompletionForLambdaWithTypeParametersAndOverloads()
{
var markup = @"
using System;
using System.Collections.Generic;
class Program
{
static void M()
{
Create(new Dictionary<Product1, Product2>(), arg => arg.$$);
}
static void Create<T, U>(Dictionary<T, U> list, Action<T> expression) { }
static void Create<T, U>(Dictionary<U, T> list, Action<T> expression) { }
}
class Product1 { public void MyProperty1() { } }
class Product2 { public void MyProperty2() { } }";
await VerifyItemExistsAsync(markup, "MyProperty1");
await VerifyItemExistsAsync(markup, "MyProperty2");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")]
public async Task CompletionForLambdaWithTypeParametersAndOverloads2()
{
var markup = @"
using System;
using System.Collections.Generic;
class Program
{
static void M()
{
Create(new Dictionary<Product1,Product2>(),arg => arg.$$);
}
static void Create<T, U>(Dictionary<T, U> list, Action<T> expression) { }
static void Create<T, U>(Dictionary<U, T> list, Action<T> expression) { }
static void Create(Dictionary<Product1, Product2> list, Action<Product3> expression) { }
}
class Product1 { public void MyProperty1() { } }
class Product2 { public void MyProperty2() { } }
class Product3 { public void MyProperty3() { } }";
await VerifyItemExistsAsync(markup, "MyProperty1");
await VerifyItemExistsAsync(markup, "MyProperty2");
await VerifyItemExistsAsync(markup, "MyProperty3");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")]
public async Task CompletionForLambdaWithTypeParametersFromClass()
{
var markup = @"
using System;
class Program<T>
{
static void M()
{
Create(arg => arg.$$);
}
static void Create(Action<T> expression) { }
}
class Product { public void MyProperty() { } }";
await VerifyItemExistsAsync(markup, "GetHashCode");
await VerifyItemIsAbsentAsync(markup, "MyProperty");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")]
public async Task CompletionForLambdaWithTypeParametersFromClassWithConstraintOnType()
{
var markup = @"
using System;
class Program<T> where T : Product
{
static void M()
{
Create(arg => arg.$$);
}
static void Create(Action<T> expression) { }
}
class Product { public void MyProperty() { } }";
await VerifyItemExistsAsync(markup, "GetHashCode");
await VerifyItemExistsAsync(markup, "MyProperty");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")]
public async Task CompletionForLambdaWithTypeParametersFromClassWithConstraintOnMethod()
{
var markup = @"
using System;
class Program
{
static void M()
{
Create(arg => arg.$$);
}
static void Create<T>(Action<T> expression) where T : Product { }
}
class Product { public void MyProperty() { } }";
await VerifyItemExistsAsync(markup, "GetHashCode");
await VerifyItemExistsAsync(markup, "MyProperty");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(40216, "https://github.com/dotnet/roslyn/issues/40216")]
public async Task CompletionForLambdaPassedAsNamedArgumentAtDifferentPositionFromCorrespondingParameter1()
{
var markup = @"
using System;
class C
{
void Test()
{
X(y: t => Console.WriteLine(t.$$));
}
void X(int x = 7, Action<string> y = null) { }
}
";
await VerifyItemExistsAsync(markup, "Length");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(40216, "https://github.com/dotnet/roslyn/issues/40216")]
public async Task CompletionForLambdaPassedAsNamedArgumentAtDifferentPositionFromCorrespondingParameter2()
{
var markup = @"
using System;
class C
{
void Test()
{
X(y: t => Console.WriteLine(t.$$));
}
void X(int x, int z, Action<string> y) { }
}
";
await VerifyItemExistsAsync(markup, "Length");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionForLambdaPassedAsArgumentInReducedExtensionMethod_NonInteractive()
{
var markup = @"
using System;
static class CExtensions
{
public static void X(this C x, Action<string> y) { }
}
class C
{
void Test()
{
new C().X(t => Console.WriteLine(t.$$));
}
}
";
await VerifyItemExistsAsync(markup, "Length", sourceCodeKind: SourceCodeKind.Regular);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionForLambdaPassedAsArgumentInReducedExtensionMethod_Interactive()
{
var markup = @"
using System;
public static void X(this C x, Action<string> y) { }
public class C
{
void Test()
{
new C().X(t => Console.WriteLine(t.$$));
}
}
";
await VerifyItemExistsAsync(markup, "Length", sourceCodeKind: SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionInsideMethodsWithNonFunctionsAsArguments()
{
var markup = @"
using System;
class c
{
void M()
{
Goo(builder =>
{
builder.$$
});
}
void Goo(Action<Builder> configure)
{
var builder = new Builder();
configure(builder);
}
}
class Builder
{
public int Something { get; set; }
}";
await VerifyItemExistsAsync(markup, "Something");
await VerifyItemIsAbsentAsync(markup, "BeginInvoke");
await VerifyItemIsAbsentAsync(markup, "Clone");
await VerifyItemIsAbsentAsync(markup, "Method");
await VerifyItemIsAbsentAsync(markup, "Target");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionInsideMethodsWithDelegatesAsArguments()
{
var markup = @"
using System;
class Program
{
public delegate void Delegate1(Uri u);
public delegate void Delegate2(Guid g);
public void M(Delegate1 d) { }
public void M(Delegate2 d) { }
public void Test()
{
M(d => d.$$)
}
}";
// Guid
await VerifyItemExistsAsync(markup, "ToByteArray");
// Uri
await VerifyItemExistsAsync(markup, "AbsoluteUri");
await VerifyItemExistsAsync(markup, "Fragment");
await VerifyItemExistsAsync(markup, "Query");
// Should not appear for Delegate
await VerifyItemIsAbsentAsync(markup, "BeginInvoke");
await VerifyItemIsAbsentAsync(markup, "Clone");
await VerifyItemIsAbsentAsync(markup, "Method");
await VerifyItemIsAbsentAsync(markup, "Target");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionInsideMethodsWithDelegatesAndReversingArguments()
{
var markup = @"
using System;
class Program
{
public delegate void Delegate1<T1,T2>(T2 t2, T1 t1);
public delegate void Delegate2<T1,T2>(T2 t2, int g, T1 t1);
public void M(Delegate1<Uri,Guid> d) { }
public void M(Delegate2<Uri,Guid> d) { }
public void Test()
{
M(d => d.$$)
}
}";
// Guid
await VerifyItemExistsAsync(markup, "ToByteArray");
// Should not appear for Uri
await VerifyItemIsAbsentAsync(markup, "AbsoluteUri");
await VerifyItemIsAbsentAsync(markup, "Fragment");
await VerifyItemIsAbsentAsync(markup, "Query");
// Should not appear for Delegate
await VerifyItemIsAbsentAsync(markup, "BeginInvoke");
await VerifyItemIsAbsentAsync(markup, "Clone");
await VerifyItemIsAbsentAsync(markup, "Method");
await VerifyItemIsAbsentAsync(markup, "Target");
}
[WorkItem(36029, "https://github.com/dotnet/roslyn/issues/36029")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionInsideMethodWithParamsBeforeParams()
{
var markup = @"
using System;
class C
{
void M()
{
Goo(builder =>
{
builder.$$
});
}
void Goo(Action<Builder> action, params Action<AnotherBuilder>[] otherActions)
{
}
}
class Builder
{
public int Something { get; set; }
};
class AnotherBuilder
{
public int AnotherSomething { get; set; }
}";
await VerifyItemIsAbsentAsync(markup, "AnotherSomething");
await VerifyItemIsAbsentAsync(markup, "FirstOrDefault");
await VerifyItemExistsAsync(markup, "Something");
}
[WorkItem(36029, "https://github.com/dotnet/roslyn/issues/36029")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionInsideMethodWithParamsInParams()
{
var markup = @"
using System;
class C
{
void M()
{
Goo(b0 => { }, b1 => {}, b2 => { b2.$$ });
}
void Goo(Action<Builder> action, params Action<AnotherBuilder>[] otherActions)
{
}
}
class Builder
{
public int Something { get; set; }
};
class AnotherBuilder
{
public int AnotherSomething { get; set; }
}";
await VerifyItemIsAbsentAsync(markup, "Something");
await VerifyItemIsAbsentAsync(markup, "FirstOrDefault");
await VerifyItemExistsAsync(markup, "AnotherSomething");
}
[Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)]
public async Task TestTargetTypeFilterWithExperimentEnabled()
{
SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, true);
var markup =
@"public class C
{
int intField;
void M(int x)
{
M($$);
}
}";
await VerifyItemExistsAsync(
markup, "intField",
matchingFilters: new List<CompletionFilter> { FilterSet.FieldFilter, FilterSet.TargetTypedFilter });
}
[Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)]
public async Task TestNoTargetTypeFilterWithExperimentDisabled()
{
SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, false);
var markup =
@"public class C
{
int intField;
void M(int x)
{
M($$);
}
}";
await VerifyItemExistsAsync(
markup, "intField",
matchingFilters: new List<CompletionFilter> { FilterSet.FieldFilter });
}
[Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)]
public async Task TestTargetTypeFilter_NotOnObjectMembers()
{
SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, true);
var markup =
@"public class C
{
void M(int x)
{
M($$);
}
}";
await VerifyItemExistsAsync(
markup, "GetHashCode",
matchingFilters: new List<CompletionFilter> { FilterSet.MethodFilter });
}
[Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)]
public async Task TestTargetTypeFilter_NotNamedTypes()
{
SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, true);
var markup =
@"public class C
{
void M(C c)
{
M($$);
}
}";
await VerifyItemExistsAsync(
markup, "c",
matchingFilters: new List<CompletionFilter> { FilterSet.LocalAndParameterFilter, FilterSet.TargetTypedFilter });
await VerifyItemExistsAsync(
markup, "C",
matchingFilters: new List<CompletionFilter> { FilterSet.ClassFilter });
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionShouldNotProvideExtensionMethodsIfTypeConstraintDoesNotMatch()
{
var markup = @"
public static class Ext
{
public static void DoSomething<T>(this T thing, string s) where T : class, I
{
}
}
public interface I
{
}
public class C
{
public void M(string s)
{
this.$$
}
}";
await VerifyItemExistsAsync(markup, "M");
await VerifyItemExistsAsync(markup, "Equals");
await VerifyItemIsAbsentAsync(markup, "DoSomething", displayTextSuffix: "<>");
}
[WorkItem(38074, "https://github.com/dotnet/roslyn/issues/38074")]
[Fact]
[Trait(Traits.Feature, Traits.Features.Completion)]
[CompilerTrait(CompilerFeature.LocalFunctions)]
public async Task LocalFunctionInStaticMethod()
{
await VerifyItemExistsAsync(@"
class C
{
static void M()
{
void Local() { }
$$
}
}", "Local");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(1152109, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1152109")]
public async Task NoItemWithEmptyDisplayName()
{
var markup = @"
class C
{
static void M()
{
int$$
}
}
";
await VerifyItemIsAbsentAsync(
markup, "",
matchingFilters: new List<CompletionFilter> { FilterSet.LocalAndParameterFilter });
}
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData('.')]
[InlineData(';')]
public async Task CompletionWithCustomizedCommitCharForMethod(char commitChar)
{
var markup = @"
class Program
{
private void Bar()
{
F$$
}
private void Foo(int i)
{
}
private void Foo(int i, int c)
{
}
}";
var expected = $@"
class Program
{{
private void Bar()
{{
Foo(){commitChar}
}}
private void Foo(int i)
{{
}}
private void Foo(int i, int c)
{{
}}
}}";
await VerifyProviderCommitAsync(markup, "Foo", expected, commitChar: commitChar);
}
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData('.')]
[InlineData(';')]
public async Task CompletionWithSemicolonInNestedMethod(char commitChar)
{
var markup = @"
class Program
{
private void Bar()
{
Foo(F$$);
}
private int Foo(int i)
{
return 1;
}
}";
var expected = $@"
class Program
{{
private void Bar()
{{
Foo(Foo(){commitChar});
}}
private int Foo(int i)
{{
return 1;
}}
}}";
await VerifyProviderCommitAsync(markup, "Foo", expected, commitChar: commitChar);
}
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData('.')]
[InlineData(';')]
public async Task CompletionWithCustomizedCommitCharForDelegateInferredType(char commitChar)
{
var markup = @"
using System;
class Program
{
private void Bar()
{
Bar2(F$$);
}
private void Foo()
{
}
void Bar2(Action t) { }
}";
var expected = $@"
using System;
class Program
{{
private void Bar()
{{
Bar2(Foo{commitChar});
}}
private void Foo()
{{
}}
void Bar2(Action t) {{ }}
}}";
await VerifyProviderCommitAsync(markup, "Foo", expected, commitChar: commitChar);
}
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData('.')]
[InlineData(';')]
public async Task CompletionWithCustomizedCommitCharForConstructor(char commitChar)
{
var markup = @"
class Program
{
private static void Bar()
{
var o = new P$$
}
}";
var expected = $@"
class Program
{{
private static void Bar()
{{
var o = new Program(){commitChar}
}}
}}";
await VerifyProviderCommitAsync(markup, "Program", expected, commitChar: commitChar);
}
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData('.')]
[InlineData(';')]
public async Task CompletionWithCustomizedCharForTypeUnderNonObjectCreationContext(char commitChar)
{
var markup = @"
class Program
{
private static void Bar()
{
var o = P$$
}
}";
var expected = $@"
class Program
{{
private static void Bar()
{{
var o = Program{commitChar}
}}
}}";
await VerifyProviderCommitAsync(markup, "Program", expected, commitChar: commitChar);
}
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData('.')]
[InlineData(';')]
public async Task CompletionWithCustomizedCommitCharForAliasConstructor(char commitChar)
{
var markup = @"
using String2 = System.String;
namespace Bar1
{
class Program
{
private static void Bar()
{
var o = new S$$
}
}
}";
var expected = $@"
using String2 = System.String;
namespace Bar1
{{
class Program
{{
private static void Bar()
{{
var o = new String2(){commitChar}
}}
}}
}}";
await VerifyProviderCommitAsync(markup, "String2", expected, commitChar: commitChar);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionWithSemicolonUnderNameofContext()
{
var markup = @"
namespace Bar1
{
class Program
{
private static void Bar()
{
var o = nameof(B$$)
}
}
}";
var expected = @"
namespace Bar1
{
class Program
{
private static void Bar()
{
var o = nameof(Bar;)
}
}
}";
await VerifyProviderCommitAsync(markup, "Bar", expected, commitChar: ';');
}
[WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EnumMemberAfterPatternMatch()
{
var markup =
@"namespace N
{
enum RankedMusicians
{
BillyJoel,
EveryoneElse
}
class C
{
void M(RankedMusicians m)
{
if (m is RankedMusicians.$$
}
}
}";
// VerifyItemExistsAsync also tests with the item typed.
await VerifyItemExistsAsync(markup, "BillyJoel");
await VerifyItemExistsAsync(markup, "EveryoneElse");
await VerifyItemIsAbsentAsync(markup, "Equals");
}
[WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EnumMemberAfterPatternMatchWithDeclaration()
{
var markup =
@"namespace N
{
enum RankedMusicians
{
BillyJoel,
EveryoneElse
}
class C
{
void M(RankedMusicians m)
{
if (m is RankedMusicians.$$ r)
{
}
}
}
}";
// VerifyItemExistsAsync also tests with the item typed.
await VerifyItemExistsAsync(markup, "BillyJoel");
await VerifyItemExistsAsync(markup, "EveryoneElse");
await VerifyItemIsAbsentAsync(markup, "Equals");
}
[WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EnumMemberAfterPropertyPatternMatch()
{
var markup =
@"namespace N
{
enum RankedMusicians
{
BillyJoel,
EveryoneElse
}
class C
{
public RankedMusicians R;
void M(C m)
{
if (m is { R: RankedMusicians.$$
}
}
}";
// VerifyItemExistsAsync also tests with the item typed.
await VerifyItemExistsAsync(markup, "BillyJoel");
await VerifyItemExistsAsync(markup, "EveryoneElse");
await VerifyItemIsAbsentAsync(markup, "Equals");
}
[WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ChildClassAfterPatternMatch()
{
var markup =
@"namespace N
{
public class D { public class E { } }
class C
{
void M(object m)
{
if (m is D.$$
}
}
}";
// VerifyItemExistsAsync also tests with the item typed.
await VerifyItemExistsAsync(markup, "E");
await VerifyItemIsAbsentAsync(markup, "Equals");
}
[WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EnumMemberAfterBinaryExpression()
{
var markup =
@"namespace N
{
enum RankedMusicians
{
BillyJoel,
EveryoneElse
}
class C
{
void M(RankedMusicians m)
{
if (m == RankedMusicians.$$
}
}
}";
// VerifyItemExistsAsync also tests with the item typed.
await VerifyItemExistsAsync(markup, "BillyJoel");
await VerifyItemExistsAsync(markup, "EveryoneElse");
await VerifyItemIsAbsentAsync(markup, "Equals");
}
[WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EnumMemberAfterBinaryExpressionWithDeclaration()
{
var markup =
@"namespace N
{
enum RankedMusicians
{
BillyJoel,
EveryoneElse
}
class C
{
void M(RankedMusicians m)
{
if (m == RankedMusicians.$$ r)
{
}
}
}
}";
// VerifyItemExistsAsync also tests with the item typed.
await VerifyItemExistsAsync(markup, "BillyJoel");
await VerifyItemExistsAsync(markup, "EveryoneElse");
await VerifyItemIsAbsentAsync(markup, "Equals");
}
[WorkItem(49609, "https://github.com/dotnet/roslyn/issues/49609")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ObsoleteOverloadsAreSkippedIfNonObsoleteOverloadIsAvailable()
{
var markup =
@"
public class C
{
[System.Obsolete]
public void M() { }
public void M(int i) { }
public void Test()
{
this.$$
}
}
";
await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M(int i) (+ 1 {FeaturesResources.overload})");
}
[WorkItem(49609, "https://github.com/dotnet/roslyn/issues/49609")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FirstObsoleteOverloadIsUsedIfAllOverloadsAreObsolete()
{
var markup =
@"
public class C
{
[System.Obsolete]
public void M() { }
[System.Obsolete]
public void M(int i) { }
public void Test()
{
this.$$
}
}
";
await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"[{CSharpFeaturesResources.deprecated}] void C.M() (+ 1 {FeaturesResources.overload})");
}
[WorkItem(49609, "https://github.com/dotnet/roslyn/issues/49609")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task IgnoreCustomObsoleteAttribute()
{
var markup =
@"
public class ObsoleteAttribute: System.Attribute
{
}
public class C
{
[Obsolete]
public void M() { }
public void M(int i) { }
public void Test()
{
this.$$
}
}
";
await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M() (+ 1 {FeaturesResources.overload})");
}
[InlineData("int", "")]
[InlineData("int[]", "int a")]
[Theory, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)]
public async Task TestTargetTypeCompletionDescription(string targetType, string expectedParameterList)
{
// Check the description displayed is based on symbol matches targeted type
SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, true);
var markup =
$@"public class C
{{
bool Bar(int a, int b) => false;
int Bar() => 0;
int[] Bar(int a) => null;
bool N({targetType} x) => true;
void M(C c)
{{
N(c.$$);
}}
}}";
await VerifyItemExistsAsync(
markup, "Bar",
expectedDescriptionOrNull: $"{targetType} C.Bar({expectedParameterList}) (+{NonBreakingSpaceString}2{NonBreakingSpaceString}{FeaturesResources.overloads_})",
matchingFilters: new List<CompletionFilter> { FilterSet.MethodFilter, FilterSet.TargetTypedFilter });
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestTypesNotSuggestedInDeclarationDeconstruction()
{
await VerifyItemIsAbsentAsync(@"
class C
{
int M()
{
var (x, $$) = (0, 0);
}
}", "C");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestTypesSuggestedInMixedDeclarationAndAssignmentInDeconstruction()
{
await VerifyItemExistsAsync(@"
class C
{
int M()
{
(x, $$) = (0, 0);
}
}", "C");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestLocalDeclaredBeforeDeconstructionSuggestedInMixedDeclarationAndAssignmentInDeconstruction()
{
await VerifyItemExistsAsync(@"
class C
{
int M()
{
int y;
(var x, $$) = (0, 0);
}
}", "y");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[WorkItem(53930, "https://github.com/dotnet/roslyn/issues/53930")]
public async Task TestTypeParameterConstraintedToInterfaceWithStatics()
{
var source = @"
interface I1
{
static void M0();
static abstract void M1();
abstract static int P1 { get; set; }
abstract static event System.Action E1;
}
interface I2
{
static abstract void M2();
}
class Test
{
void M<T>(T x) where T : I1, I2
{
T.$$
}
}
";
await VerifyItemIsAbsentAsync(source, "M0");
await VerifyItemExistsAsync(source, "M1");
await VerifyItemExistsAsync(source, "M2");
await VerifyItemExistsAsync(source, "P1");
await VerifyItemExistsAsync(source, "E1");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Completion.Providers;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion;
using Microsoft.CodeAnalysis.Experiments;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionSetSources
{
[UseExportProvider]
public partial class SymbolCompletionProviderTests : AbstractCSharpCompletionProviderTests
{
internal override Type GetCompletionProviderType()
=> typeof(SymbolCompletionProvider);
protected override TestComposition GetComposition()
=> base.GetComposition().AddParts(typeof(TestExperimentationService));
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData(SourceCodeKind.Regular)]
[InlineData(SourceCodeKind.Script)]
public async Task EmptyFile(SourceCodeKind sourceCodeKind)
{
await VerifyItemIsAbsentAsync(@"$$", @"String", expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind);
await VerifyItemExistsAsync(@"$$", @"System", expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind);
}
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData(SourceCodeKind.Regular)]
[InlineData(SourceCodeKind.Script)]
public async Task EmptyFileWithUsing(SourceCodeKind sourceCodeKind)
{
await VerifyItemExistsAsync(@"using System;
$$", @"String", expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind);
await VerifyItemExistsAsync(@"using System;
$$", @"System", expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterHashR()
=> await VerifyItemIsAbsentAsync(@"#r $$", "@System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterHashLoad()
=> await VerifyItemIsAbsentAsync(@"#load $$", "@System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingDirective()
{
await VerifyItemIsAbsentAsync(@"using $$", @"String");
await VerifyItemIsAbsentAsync(@"using $$ = System", @"System");
await VerifyItemExistsAsync(@"using $$", @"System");
await VerifyItemExistsAsync(@"using T = $$", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InactiveRegion()
{
await VerifyItemIsAbsentAsync(@"class C {
#if false
$$
#endif", @"String");
await VerifyItemIsAbsentAsync(@"class C {
#if false
$$
#endif", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ActiveRegion()
{
await VerifyItemIsAbsentAsync(@"class C {
#if true
$$
#endif", @"String");
await VerifyItemExistsAsync(@"class C {
#if true
$$
#endif", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InactiveRegionWithUsing()
{
await VerifyItemIsAbsentAsync(@"using System;
class C {
#if false
$$
#endif", @"String");
await VerifyItemIsAbsentAsync(@"using System;
class C {
#if false
$$
#endif", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ActiveRegionWithUsing()
{
await VerifyItemExistsAsync(@"using System;
class C {
#if true
$$
#endif", @"String");
await VerifyItemExistsAsync(@"using System;
class C {
#if true
$$
#endif", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SingleLineComment1()
{
await VerifyItemIsAbsentAsync(@"using System;
class C {
// $$", @"String");
await VerifyItemIsAbsentAsync(@"using System;
class C {
// $$", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SingleLineComment2()
{
await VerifyItemIsAbsentAsync(@"using System;
class C {
// $$
", @"String");
await VerifyItemIsAbsentAsync(@"using System;
class C {
// $$
", @"System");
await VerifyItemIsAbsentAsync(@"using System;
class C {
// $$
", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MultiLineComment()
{
await VerifyItemIsAbsentAsync(@"using System;
class C {
/* $$", @"String");
await VerifyItemIsAbsentAsync(@"using System;
class C {
/* $$", @"System");
await VerifyItemIsAbsentAsync(@"using System;
class C {
/* $$ */", @"String");
await VerifyItemIsAbsentAsync(@"using System;
class C {
/* $$ */", @"System");
await VerifyItemExistsAsync(@"using System;
class C {
/* */$$", @"System");
await VerifyItemExistsAsync(@"using System;
class C {
/* */$$
", @"System");
await VerifyItemExistsAsync(@"using System;
class C {
/* */$$
", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SingleLineXmlComment1()
{
await VerifyItemIsAbsentAsync(@"using System;
class C {
/// $$", @"String");
await VerifyItemIsAbsentAsync(@"using System;
class C {
/// $$", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SingleLineXmlComment2()
{
await VerifyItemIsAbsentAsync(@"using System;
class C {
/// $$
", @"String");
await VerifyItemIsAbsentAsync(@"using System;
class C {
/// $$
", @"System");
await VerifyItemIsAbsentAsync(@"using System;
class C {
/// $$
", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MultiLineXmlComment()
{
await VerifyItemIsAbsentAsync(@"using System;
class C {
/** $$ */", @"String");
await VerifyItemIsAbsentAsync(@"using System;
class C {
/** $$ */", @"System");
await VerifyItemExistsAsync(@"using System;
class C {
/** */$$", @"System");
await VerifyItemExistsAsync(@"using System;
class C {
/** */$$
", @"System");
await VerifyItemExistsAsync(@"using System;
class C {
/** */$$
", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OpenStringLiteral()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$")), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OpenStringLiteralInDirective()
{
await VerifyItemIsAbsentAsync("#r \"$$", "String", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
await VerifyItemIsAbsentAsync("#r \"$$", "System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StringLiteral()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$\";")), @"System");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$\";")), @"String");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StringLiteralInDirective()
{
await VerifyItemIsAbsentAsync("#r \"$$\"", "String", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
await VerifyItemIsAbsentAsync("#r \"$$\"", "System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OpenCharLiteral()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("char c = '$$")), @"System");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("char c = '$$")), @"String");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AssemblyAttribute1()
{
await VerifyItemExistsAsync(@"[assembly: $$]", @"System");
await VerifyItemIsAbsentAsync(@"[assembly: $$]", @"String");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AssemblyAttribute2()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"[assembly: $$]"), @"System");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"[assembly: $$]"), @"AttributeUsage");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SystemAttributeIsNotAnAttribute()
{
var content = @"[$$]
class CL {}";
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"Attribute");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeAttribute()
{
var content = @"[$$]
class CL {}";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeParamAttribute()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<[A$$]T> {}"), @"AttributeUsage");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<[A$$]T> {}"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodAttribute()
{
var content = @"class CL {
[$$]
void Method() {}
}";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodTypeParamAttribute()
{
var content = @"class CL{
void Method<[A$$]T> () {}
}";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodParamAttribute()
{
var content = @"class CL{
void Method ([$$]int i) {}
}";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_EmptyNameSpan_TopLevel()
{
var source = @"namespace $$ { }";
await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_EmptyNameSpan_Nested()
{
var source = @";
namespace System
{
namespace $$ { }
}";
await VerifyItemExistsAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_TopLevelNoPeers()
{
var source = @"using System;
namespace $$";
await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "String", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_TopLevelNoPeers_FileScopedNamespace()
{
var source = @"using System;
namespace $$;";
await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "String", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_TopLevelWithPeer()
{
var source = @"
namespace A { }
namespace $$";
await VerifyItemExistsAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_NestedWithNoPeers()
{
var source = @"
namespace A
{
namespace $$
}";
await VerifyNoItemsExistAsync(source, sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_NestedWithPeer()
{
var source = @"
namespace A
{
namespace B { }
namespace $$
}";
await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_ExcludesCurrentDeclaration()
{
var source = @"namespace N$$S";
await VerifyItemIsAbsentAsync(source, "NS", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_WithNested()
{
var source = @"
namespace A
{
namespace $$
{
namespace B { }
}
}";
await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_WithNestedAndMatchingPeer()
{
var source = @"
namespace A.B { }
namespace A
{
namespace $$
{
namespace B { }
}
}";
await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_InnerCompletionPosition()
{
var source = @"namespace Sys$$tem { }";
await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_IncompleteDeclaration()
{
var source = @"
namespace A
{
namespace B
{
namespace $$
namespace C1 { }
}
namespace B.C2 { }
}
namespace A.B.C3 { }";
// Ideally, all the C* namespaces would be recommended but, because of how the parser
// recovers from the missing braces, they end up with the following qualified names...
//
// C1 => A.B.?.C1
// C2 => A.B.B.C2
// C3 => A.A.B.C3
//
// ...none of which are found by the current algorithm.
await VerifyItemIsAbsentAsync(source, "C1", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "C2", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "C3", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
// Because of the above, B does end up in the completion list
// since A.B.B appears to be a peer of the new declaration
await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Qualified_NoPeers()
{
var source = @"namespace A.$$";
await VerifyNoItemsExistAsync(source, sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Qualified_TopLevelWithPeer()
{
var source = @"
namespace A.B { }
namespace A.$$";
await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Qualified_TopLevelWithPeer_FileScopedNamespace()
{
var source = @"
namespace A.B { }
namespace A.$$;";
await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Qualified_NestedWithPeer()
{
var source = @"
namespace A
{
namespace B.C { }
namespace B.$$
}";
await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemExistsAsync(source, "C", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Qualified_WithNested()
{
var source = @"
namespace A.$$
{
namespace B { }
}
";
await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Qualified_WithNestedAndMatchingPeer()
{
var source = @"
namespace A.B { }
namespace A.$$
{
namespace B { }
}
";
await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Qualified_InnerCompletionPosition()
{
var source = @"namespace Sys$$tem.Runtime { }";
await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_OnKeyword()
{
var source = @"name$$space System { }";
await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_OnNestedKeyword()
{
var source = @"
namespace System
{
name$$space Runtime { }
}";
await VerifyItemIsAbsentAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Qualified_IncompleteDeclaration()
{
var source = @"
namespace A
{
namespace B
{
namespace C.$$
namespace C.D1 { }
}
namespace B.C.D2 { }
}
namespace A.B.C.D3 { }";
await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "C", sourceCodeKind: SourceCodeKind.Regular);
// Ideally, all the D* namespaces would be recommended but, because of how the parser
// recovers from the missing braces, they end up with the following qualified names...
//
// D1 => A.B.C.C.?.D1
// D2 => A.B.B.C.D2
// D3 => A.A.B.C.D3
//
// ...none of which are found by the current algorithm.
await VerifyItemIsAbsentAsync(source, "D1", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "D2", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "D3", sourceCodeKind: SourceCodeKind.Regular);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UnderNamespace()
{
await VerifyItemIsAbsentAsync(@"namespace NS { $$", @"String");
await VerifyItemIsAbsentAsync(@"namespace NS { $$", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OutsideOfType1()
{
await VerifyItemIsAbsentAsync(@"namespace NS {
class CL {}
$$", @"String");
await VerifyItemIsAbsentAsync(@"namespace NS {
class CL {}
$$", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OutsideOfType2()
{
var content = @"namespace NS {
class CL {}
$$";
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionInsideProperty()
{
var content = @"class C
{
private string name;
public string Name
{
set
{
name = $$";
await VerifyItemExistsAsync(content, @"value");
await VerifyItemExistsAsync(content, @"C");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterDot()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"[assembly: A.$$"), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"[assembly: A.$$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingAlias()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"using MyType = $$"), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"using MyType = $$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task IncompleteMember()
{
var content = @"class CL {
$$
";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task IncompleteMemberAccessibility()
{
var content = @"class CL {
public $$
";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BadStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = $$)c")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = $$)c")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeTypeParameter()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<$$"), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<$$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeTypeParameterList()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T, $$"), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T, $$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CastExpressionTypePart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = ($$)c")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = ($$)c")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ObjectCreationExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ArrayCreationExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$ [")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$ [")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StackAllocArrayCreationExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = stackalloc $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = stackalloc $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FromClauseTypeOptPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from $$ c")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from $$ c")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task JoinClause()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join $$ j")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join $$ j")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DeclarationStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ i =")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ i =")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task VariableDeclaration()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"fixed($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"fixed($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForEachStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForEachStatementNoToken()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach $$")), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CatchDeclaration()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"try {} catch($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"try {} catch($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FieldDeclaration()
{
var content = @"class CL {
$$ i";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EventFieldDeclaration()
{
var content = @"class CL {
event $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConversionOperatorDeclaration()
{
var content = @"class CL {
explicit operator $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConversionOperatorDeclarationNoToken()
{
var content = @"class CL {
explicit $$";
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task PropertyDeclaration()
{
var content = @"class CL {
$$ Prop {";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EventDeclaration()
{
var content = @"class CL {
event $$ Event {";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task IndexerDeclaration()
{
var content = @"class CL {
$$ this";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Parameter()
{
var content = @"class CL {
void Method($$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ArrayType()
{
var content = @"class CL {
$$ [";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task PointerType()
{
var content = @"class CL {
$$ *";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NullableType()
{
var content = @"class CL {
$$ ?";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DelegateDeclaration()
{
var content = @"class CL {
delegate $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodDeclaration()
{
var content = @"class CL {
$$ M(";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OperatorDeclaration()
{
var content = @"class CL {
$$ operator";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ParenthesizedExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InvocationExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$(")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$(")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ElementAccessExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$[")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$[")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Argument()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"i[$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"i[$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CastExpressionExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"(c)$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"(c)$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FromClauseInPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LetClauseExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C let n = $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C let n = $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OrderingExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C orderby $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C orderby $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SelectClauseExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C select $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C select $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExpressionStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ReturnStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"return $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"return $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThrowStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"throw $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"throw $$")), @"System");
}
[WorkItem(760097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/760097")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task YieldReturnStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"yield return $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"yield return $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForEachStatementExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach(T t in $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach(T t in $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStatementExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"using($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"using($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LockStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"lock($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"lock($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EqualsValueClause()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var i = $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var i = $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForStatementInitializersPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForStatementConditionOptPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForStatementIncrementorsPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;i>10;$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;i>10;$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DoStatementConditionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"do {} while($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"do {} while($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WhileStatementConditionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"while($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"while($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ArrayRankSpecifierSizesPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"int [$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"int [$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task PrefixUnaryExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"+$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"+$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task PostfixUnaryExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$++")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$++")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BinaryExpressionLeftPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ + 1")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ + 1")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BinaryExpressionRightPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 + $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 + $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AssignmentExpressionLeftPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ = 1")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ = 1")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AssignmentExpressionRightPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 = $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 = $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConditionalExpressionConditionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$? 1:")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$? 1:")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConditionalExpressionWhenTruePart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? $$:")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? $$:")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConditionalExpressionWhenFalsePart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? 1:$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? 1:$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task JoinClauseInExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task JoinClauseLeftExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task JoinClauseRightExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on id equals $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on id equals $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WhereClauseConditionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C where $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C where $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task GroupClauseGroupExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task GroupClauseByExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group g by $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group g by $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task IfStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"if ($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"if ($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SwitchStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"switch($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"switch($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SwitchLabelCase()
{
var content = @"switch(i) { case $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SwitchPatternLabelCase()
{
var content = @"switch(i) { case $$ when";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")]
public async Task SwitchExpressionFirstBranch()
{
var content = @"i switch { $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")]
public async Task SwitchExpressionSecondBranch()
{
var content = @"i switch { 1 => true, $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")]
public async Task PositionalPatternFirstPosition()
{
var content = @"i is ($$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")]
public async Task PositionalPatternSecondPosition()
{
var content = @"i is (1, $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")]
public async Task PropertyPatternFirstPosition()
{
var content = @"i is { P: $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")]
public async Task PropertyPatternSecondPosition()
{
var content = @"i is { P1: 1, P2: $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InitializerExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new [] { $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new [] { $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeParameterConstraintClause()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : $$"), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : $$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeParameterConstraintClauseList()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A, $$"), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A, $$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeParameterConstraintClauseAnotherWhere()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A where$$"), @"System");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A where$$"), @"String");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeSymbolOfTypeParameterConstraintClause1()
{
await VerifyItemExistsAsync(@"class CL<T> where $$", @"T");
await VerifyItemExistsAsync(@"class CL{ delegate void F<T>() where $$} ", @"T");
await VerifyItemExistsAsync(@"class CL{ void F<T>() where $$", @"T");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeSymbolOfTypeParameterConstraintClause2()
{
await VerifyItemIsAbsentAsync(@"class CL<T> where $$", @"System");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> where $$"), @"String");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeSymbolOfTypeParameterConstraintClause3()
{
await VerifyItemIsAbsentAsync(@"class CL<T1> { void M<T2> where $$", @"T1");
await VerifyItemExistsAsync(@"class CL<T1> { void M<T2>() where $$", @"T2");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BaseList1()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : $$"), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : $$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BaseList2()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : B, $$"), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : B, $$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BaseListWhere()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> : B where$$"), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> : B where$$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AliasedName()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod(@"global::$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"global::$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AliasedNamespace()
=> await VerifyItemExistsAsync(AddUsingDirectives("using S = System;", AddInsideMethod(@"S.$$")), @"String");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AliasedType()
=> await VerifyItemExistsAsync(AddUsingDirectives("using S = System.String;", AddInsideMethod(@"S.$$")), @"Empty");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstructorInitializer()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class C { C() : $$"), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class C { C() : $$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Typeof1()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"typeof($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"typeof($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Typeof2()
=> await VerifyItemIsAbsentAsync(AddInsideMethod(@"var x = 0; typeof($$"), @"x");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Sizeof1()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"sizeof($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"sizeof($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Sizeof2()
=> await VerifyItemIsAbsentAsync(AddInsideMethod(@"var x = 0; sizeof($$"), @"x");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Default1()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"default($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"default($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Default2()
=> await VerifyItemIsAbsentAsync(AddInsideMethod(@"var x = 0; default($$"), @"x");
[WorkItem(543819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543819")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Checked()
=> await VerifyItemExistsAsync(AddInsideMethod(@"var x = 0; checked($$"), @"x");
[WorkItem(543819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543819")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Unchecked()
=> await VerifyItemExistsAsync(AddInsideMethod(@"var x = 0; unchecked($$"), @"x");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Locals()
=> await VerifyItemExistsAsync(@"class c { void M() { string goo; $$", "goo");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Parameters()
=> await VerifyItemExistsAsync(@"class c { void M(string args) { $$", "args");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LambdaDiscardParameters()
=> await VerifyItemIsAbsentAsync(@"class C { void M() { System.Func<int, string, int> f = (int _, string _) => 1 + $$", "_");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AnonymousMethodDiscardParameters()
=> await VerifyItemIsAbsentAsync(@"class C { void M() { System.Func<int, string, int> f = delegate(int _, string _) { return 1 + $$ }; } }", "_");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CommonTypesInNewExpressionContext()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class c { void M() { new $$"), "Exception");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoCompletionForUnboundTypes()
=> await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class c { void M() { goo.$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoParametersInTypeOf()
=> await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class c { void M(int x) { typeof($$"), "x");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoParametersInDefault()
=> await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class c { void M(int x) { default($$"), "x");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoParametersInSizeOf()
=> await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class C { void M(int x) { unsafe { sizeof($$"), "x");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoParametersInGenericParameterList()
=> await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class Generic<T> { void M(int x) { Generic<$$"), "x");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoMembersAfterNullLiteral()
=> await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class C { void M() { null.$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterTrueLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { true.$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterFalseLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { false.$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterCharLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { 'c'.$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterStringLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { """".$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterVerbatimStringLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { @"""".$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterNumericLiteral()
{
// NOTE: the Completion command handler will suppress this case if the user types '.',
// but we still need to show members if the user specifically invokes statement completion here.
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { 2.$$"), "Equals");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoMembersAfterParenthesizedNullLiteral()
=> await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class C { void M() { (null).$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterParenthesizedTrueLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (true).$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterParenthesizedFalseLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (false).$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterParenthesizedCharLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { ('c').$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterParenthesizedStringLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { ("""").$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterParenthesizedVerbatimStringLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (@"""").$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterParenthesizedNumericLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (2).$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterArithmeticExpression()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (1 + 1).$$"), "Equals");
[WorkItem(539332, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539332")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceTypesAvailableInUsingAlias()
=> await VerifyItemExistsAsync(@"using S = System.$$", "String");
[WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InheritedMember1()
{
var markup = @"
class A
{
private void Hidden() { }
protected void Goo() { }
}
class B : A
{
void Bar()
{
$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Hidden");
await VerifyItemExistsAsync(markup, "Goo");
}
[WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InheritedMember2()
{
var markup = @"
class A
{
private void Hidden() { }
protected void Goo() { }
}
class B : A
{
void Bar()
{
this.$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Hidden");
await VerifyItemExistsAsync(markup, "Goo");
}
[WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InheritedMember3()
{
var markup = @"
class A
{
private void Hidden() { }
protected void Goo() { }
}
class B : A
{
void Bar()
{
base.$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Hidden");
await VerifyItemExistsAsync(markup, "Goo");
await VerifyItemIsAbsentAsync(markup, "Bar");
}
[WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InheritedStaticMember1()
{
var markup = @"
class A
{
private static void Hidden() { }
protected static void Goo() { }
}
class B : A
{
void Bar()
{
$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Hidden");
await VerifyItemExistsAsync(markup, "Goo");
}
[WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InheritedStaticMember2()
{
var markup = @"
class A
{
private static void Hidden() { }
protected static void Goo() { }
}
class B : A
{
void Bar()
{
B.$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Hidden");
await VerifyItemExistsAsync(markup, "Goo");
}
[WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InheritedStaticMember3()
{
var markup = @"
class A
{
private static void Hidden() { }
protected static void Goo() { }
}
class B : A
{
void Bar()
{
A.$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Hidden");
await VerifyItemExistsAsync(markup, "Goo");
}
[WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InheritedInstanceAndStaticMembers()
{
var markup = @"
class A
{
private static void HiddenStatic() { }
protected static void GooStatic() { }
private void HiddenInstance() { }
protected void GooInstance() { }
}
class B : A
{
void Bar()
{
$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "HiddenStatic");
await VerifyItemExistsAsync(markup, "GooStatic");
await VerifyItemIsAbsentAsync(markup, "HiddenInstance");
await VerifyItemExistsAsync(markup, "GooInstance");
}
[WorkItem(540155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540155")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForLoopIndexer1()
{
var markup = @"
class C
{
void M()
{
for (int i = 0; $$
";
await VerifyItemExistsAsync(markup, "i");
}
[WorkItem(540155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540155")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForLoopIndexer2()
{
var markup = @"
class C
{
void M()
{
for (int i = 0; i < 10; $$
";
await VerifyItemExistsAsync(markup, "i");
}
[WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceMembersAfterType1()
{
var markup = @"
class C
{
void M()
{
System.IDisposable.$$
";
await VerifyItemIsAbsentAsync(markup, "Dispose");
}
[WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceMembersAfterType2()
{
var markup = @"
class C
{
void M()
{
(System.IDisposable).$$
";
await VerifyItemIsAbsentAsync(markup, "Dispose");
}
[WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceMembersAfterType3()
{
var markup = @"
using System;
class C
{
void M()
{
IDisposable.$$
";
await VerifyItemIsAbsentAsync(markup, "Dispose");
}
[WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceMembersAfterType4()
{
var markup = @"
using System;
class C
{
void M()
{
(IDisposable).$$
";
await VerifyItemIsAbsentAsync(markup, "Dispose");
}
[WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticMembersAfterType1()
{
var markup = @"
class C
{
void M()
{
System.IDisposable.$$
";
await VerifyItemExistsAsync(markup, "ReferenceEquals");
}
[WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticMembersAfterType2()
{
var markup = @"
class C
{
void M()
{
(System.IDisposable).$$
";
await VerifyItemIsAbsentAsync(markup, "ReferenceEquals");
}
[WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticMembersAfterType3()
{
var markup = @"
using System;
class C
{
void M()
{
IDisposable.$$
";
await VerifyItemExistsAsync(markup, "ReferenceEquals");
}
[WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticMembersAfterType4()
{
var markup = @"
using System;
class C
{
void M()
{
(IDisposable).$$
";
await VerifyItemIsAbsentAsync(markup, "ReferenceEquals");
}
[WorkItem(540197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540197")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeParametersInClass()
{
var markup = @"
class C<T, R>
{
$$
}
";
await VerifyItemExistsAsync(markup, "T");
}
[WorkItem(540212, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540212")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterRefInLambda_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
Func<int, int> f = (ref $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[WorkItem(540212, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540212")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterOutInLambda_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
Func<int, int> f = (out $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(24326, "https://github.com/dotnet/roslyn/issues/24326")]
public async Task AfterInInLambda_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
Func<int, int> f = (in $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterRefInMethodDeclaration_TypeOnly()
{
var markup = @"
using System;
class C
{
String field;
void M(ref $$)
{
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "field");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterOutInMethodDeclaration_TypeOnly()
{
var markup = @"
using System;
class C
{
String field;
void M(out $$)
{
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "field");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(24326, "https://github.com/dotnet/roslyn/issues/24326")]
public async Task AfterInInMethodDeclaration_TypeOnly()
{
var markup = @"
using System;
class C
{
String field;
void M(in $$)
{
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "field");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterRefInInvocation_TypeAndVariable()
{
var markup = @"
using System;
class C
{
void M(ref String parameter)
{
M(ref $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemExistsAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterOutInInvocation_TypeAndVariable()
{
var markup = @"
using System;
class C
{
void M(out String parameter)
{
M(out $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemExistsAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(24326, "https://github.com/dotnet/roslyn/issues/24326")]
public async Task AfterInInInvocation_TypeAndVariable()
{
var markup = @"
using System;
class C
{
void M(in String parameter)
{
M(in $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemExistsAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")]
public async Task AfterRefExpression_TypeAndVariable()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
ref var x = ref $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemExistsAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")]
public async Task AfterRefInStatementContext_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
ref $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")]
public async Task AfterRefReadonlyInStatementContext_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
ref readonly $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterRefLocalDeclaration_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
ref $$ int local;
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterRefReadonlyLocalDeclaration_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
ref readonly $$ int local;
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterRefLocalFunction_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
ref $$ int Function();
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterRefReadonlyLocalFunction_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
ref readonly $$ int Function();
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")]
public async Task AfterRefInMemberContext_TypeOnly()
{
var markup = @"
using System;
class C
{
String field;
ref $$
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "field");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")]
public async Task AfterRefReadonlyInMemberContext_TypeOnly()
{
var markup = @"
using System;
class C
{
String field;
ref readonly $$
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "field");
}
[WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedType1()
{
var markup = @"
class Q
{
$$
class R
{
}
}
";
await VerifyItemExistsAsync(markup, "Q");
await VerifyItemExistsAsync(markup, "R");
}
[WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedType2()
{
var markup = @"
class Q
{
class R
{
$$
}
}
";
await VerifyItemExistsAsync(markup, "Q");
await VerifyItemExistsAsync(markup, "R");
}
[WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedType3()
{
var markup = @"
class Q
{
class R
{
}
$$
}
";
await VerifyItemExistsAsync(markup, "Q");
await VerifyItemExistsAsync(markup, "R");
}
[WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedType4_Regular()
{
var markup = @"
class Q
{
class R
{
}
}
$$"; // At EOF
// Top-level statements are not allowed to follow classes, but we still offer it in completion for a few
// reasons:
//
// 1. The code is simpler
// 2. It's a relatively rare coding practice to define types outside of namespaces
// 3. It allows the compiler to produce a better error message when users type things in the wrong order
await VerifyItemExistsAsync(markup, "Q", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(markup, "R", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedType4_Script()
{
var markup = @"
class Q
{
class R
{
}
}
$$"; // At EOF
await VerifyItemExistsAsync(markup, "Q", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
await VerifyItemIsAbsentAsync(markup, "R", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedType5()
{
var markup = @"
class Q
{
class R
{
}
$$"; // At EOF
await VerifyItemExistsAsync(markup, "Q");
await VerifyItemExistsAsync(markup, "R");
}
[WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedType6()
{
var markup = @"
class Q
{
class R
{
$$"; // At EOF
await VerifyItemExistsAsync(markup, "Q");
await VerifyItemExistsAsync(markup, "R");
}
[WorkItem(540574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540574")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AmbiguityBetweenTypeAndLocal()
{
var markup = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public void goo() {
int i = 5;
i.$$
List<string> ml = new List<string>();
}
}";
await VerifyItemExistsAsync(markup, "CompareTo");
}
[WorkItem(21596, "https://github.com/dotnet/roslyn/issues/21596")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AmbiguityBetweenExpressionAndLocalFunctionReturnType()
{
var markup = @"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
AwaitTest test = new AwaitTest();
test.Test1().Wait();
}
}
class AwaitTest
{
List<string> stringList = new List<string>();
public async Task<bool> Test1()
{
stringList.$$
await Test2();
return true;
}
public async Task<bool> Test2()
{
return true;
}
}";
await VerifyItemExistsAsync(markup, "Add");
}
[WorkItem(540750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540750")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionAfterNewInScript()
{
var markup = @"
using System;
new $$";
await VerifyItemExistsAsync(markup, "String", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[WorkItem(540933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540933")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExtensionMethodsInScript()
{
var markup = @"
using System.Linq;
var a = new int[] { 1, 2 };
a.$$";
await VerifyItemExistsAsync(markup, "ElementAt", displayTextSuffix: "<>", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[WorkItem(541019, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541019")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExpressionsInForLoopInitializer()
{
var markup = @"
public class C
{
public void M()
{
int count = 0;
for ($$
";
await VerifyItemExistsAsync(markup, "count");
}
[WorkItem(541108, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541108")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterLambdaExpression1()
{
var markup = @"
public class C
{
public void M()
{
System.Func<int, int> f = arg => { arg = 2; return arg; }.$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "ToString");
}
[WorkItem(541108, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541108")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterLambdaExpression2()
{
var markup = @"
public class C
{
public void M()
{
((System.Func<int, int>)(arg => { arg = 2; return arg; })).$$
}
}
";
await VerifyItemExistsAsync(markup, "ToString");
await VerifyItemExistsAsync(markup, "Invoke");
}
[WorkItem(541216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541216")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InMultiLineCommentAtEndOfFile()
{
var markup = @"
using System;
/*$$";
await VerifyItemIsAbsentAsync(markup, "Console", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[WorkItem(541218, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541218")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeParametersAtEndOfFile()
{
var markup = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Outer<T>
{
class Inner<U>
{
static void F(T t, U u)
{
return;
}
public static void F(T t)
{
Outer<$$";
await VerifyItemExistsAsync(markup, "T");
}
[WorkItem(552717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552717")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LabelInCaseSwitchAbsentForCase()
{
var markup = @"
class Program
{
static void Main()
{
int x;
switch (x)
{
case 0:
goto $$";
await VerifyItemIsAbsentAsync(markup, "case 0:");
}
[WorkItem(552717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552717")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LabelInCaseSwitchAbsentForDefaultWhenAbsent()
{
var markup = @"
class Program
{
static void Main()
{
int x;
switch (x)
{
case 0:
goto $$";
await VerifyItemIsAbsentAsync(markup, "default:");
}
[WorkItem(552717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552717")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LabelInCaseSwitchPresentForDefault()
{
var markup = @"
class Program
{
static void Main()
{
int x;
switch (x)
{
default:
goto $$";
await VerifyItemExistsAsync(markup, "default");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LabelAfterGoto1()
{
var markup = @"
class Program
{
static void Main()
{
Goo:
int Goo;
goto $$";
await VerifyItemExistsAsync(markup, "Goo");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LabelAfterGoto2()
{
var markup = @"
class Program
{
static void Main()
{
Goo:
int Goo;
goto Goo $$";
await VerifyItemIsAbsentAsync(markup, "Goo");
}
[WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeName()
{
var markup = @"
using System;
[$$";
await VerifyItemExistsAsync(markup, "CLSCompliant");
await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute");
}
[WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameAfterSpecifier()
{
var markup = @"
using System;
[assembly:$$
";
await VerifyItemExistsAsync(markup, "CLSCompliant");
await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute");
}
[WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameInAttributeList()
{
var markup = @"
using System;
[CLSCompliant, $$";
await VerifyItemExistsAsync(markup, "CLSCompliant");
await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute");
}
[WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameBeforeClass()
{
var markup = @"
using System;
[$$
class C { }";
await VerifyItemExistsAsync(markup, "CLSCompliant");
await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute");
}
[WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameAfterSpecifierBeforeClass()
{
var markup = @"
using System;
[assembly:$$
class C { }";
await VerifyItemExistsAsync(markup, "CLSCompliant");
await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute");
}
[WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameInAttributeArgumentList()
{
var markup = @"
using System;
[CLSCompliant($$
class C { }";
await VerifyItemExistsAsync(markup, "CLSCompliantAttribute");
await VerifyItemIsAbsentAsync(markup, "CLSCompliant");
}
[WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameInsideClass()
{
var markup = @"
using System;
class C { $$ }";
await VerifyItemExistsAsync(markup, "CLSCompliantAttribute");
await VerifyItemIsAbsentAsync(markup, "CLSCompliant");
}
[WorkItem(542954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542954")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceAliasInAttributeName1()
{
var markup = @"
using Alias = System;
[$$
class C { }";
await VerifyItemExistsAsync(markup, "Alias");
}
[WorkItem(542954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542954")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceAliasInAttributeName2()
{
var markup = @"
using Alias = Goo;
namespace Goo { }
[$$
class C { }";
await VerifyItemIsAbsentAsync(markup, "Alias");
}
[WorkItem(542954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542954")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceAliasInAttributeName3()
{
var markup = @"
using Alias = Goo;
namespace Goo { class A : System.Attribute { } }
[$$
class C { }";
await VerifyItemExistsAsync(markup, "Alias");
}
[Fact]
[WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameAfterNamespace()
{
var markup = @"
namespace Test
{
class MyAttribute : System.Attribute { }
[Test.$$
class Program { }
}";
await VerifyItemExistsAsync(markup, "My");
await VerifyItemIsAbsentAsync(markup, "MyAttribute");
}
[Fact]
[WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameAfterNamespace2()
{
var markup = @"
namespace Test
{
namespace Two
{
class MyAttribute : System.Attribute { }
[Test.Two.$$
class Program { }
}
}";
await VerifyItemExistsAsync(markup, "My");
await VerifyItemIsAbsentAsync(markup, "MyAttribute");
}
[Fact]
[WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameWhenSuffixlessFormIsKeyword()
{
var markup = @"
namespace Test
{
class namespaceAttribute : System.Attribute { }
[$$
class Program { }
}";
await VerifyItemExistsAsync(markup, "namespaceAttribute");
await VerifyItemIsAbsentAsync(markup, "namespace");
await VerifyItemIsAbsentAsync(markup, "@namespace");
}
[Fact]
[WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameAfterNamespaceWhenSuffixlessFormIsKeyword()
{
var markup = @"
namespace Test
{
class namespaceAttribute : System.Attribute { }
[Test.$$
class Program { }
}";
await VerifyItemExistsAsync(markup, "namespaceAttribute");
await VerifyItemIsAbsentAsync(markup, "namespace");
await VerifyItemIsAbsentAsync(markup, "@namespace");
}
[Fact]
[WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task KeywordsUsedAsLocals()
{
var markup = @"
class C
{
void M()
{
var error = 0;
var method = 0;
var @int = 0;
Console.Write($$
}
}";
// preprocessor keyword
await VerifyItemExistsAsync(markup, "error");
await VerifyItemIsAbsentAsync(markup, "@error");
// contextual keyword
await VerifyItemExistsAsync(markup, "method");
await VerifyItemIsAbsentAsync(markup, "@method");
// full keyword
await VerifyItemExistsAsync(markup, "@int");
await VerifyItemIsAbsentAsync(markup, "int");
}
[Fact]
[WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task QueryContextualKeywords1()
{
var markup = @"
class C
{
void M()
{
var from = new[]{1,2,3};
var r = from x in $$
}
}";
await VerifyItemExistsAsync(markup, "@from");
await VerifyItemIsAbsentAsync(markup, "from");
}
[Fact]
[WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task QueryContextualKeywords2()
{
var markup = @"
class C
{
void M()
{
var where = new[] { 1, 2, 3 };
var x = from @from in @where
where $$ == @where.Length
select @from;
}
}";
await VerifyItemExistsAsync(markup, "@from");
await VerifyItemIsAbsentAsync(markup, "from");
await VerifyItemExistsAsync(markup, "@where");
await VerifyItemIsAbsentAsync(markup, "where");
}
[Fact]
[WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task QueryContextualKeywords3()
{
var markup = @"
class C
{
void M()
{
var where = new[] { 1, 2, 3 };
var x = from @from in @where
where @from == @where.Length
select $$;
}
}";
await VerifyItemExistsAsync(markup, "@from");
await VerifyItemIsAbsentAsync(markup, "from");
await VerifyItemExistsAsync(markup, "@where");
await VerifyItemIsAbsentAsync(markup, "where");
}
[Fact]
[WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameAfterGlobalAlias()
{
var markup = @"
class MyAttribute : System.Attribute { }
[global::$$
class Program { }";
await VerifyItemExistsAsync(markup, "My", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(markup, "MyAttribute", sourceCodeKind: SourceCodeKind.Regular);
}
[Fact]
[WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameAfterGlobalAliasWhenSuffixlessFormIsKeyword()
{
var markup = @"
class namespaceAttribute : System.Attribute { }
[global::$$
class Program { }";
await VerifyItemExistsAsync(markup, "namespaceAttribute", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(markup, "namespace", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(markup, "@namespace", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(25589, "https://github.com/dotnet/roslyn/issues/25589")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeSearch_NamespaceWithNestedAttribute1()
{
var markup = @"
namespace Namespace1
{
namespace Namespace2 { class NonAttribute { } }
namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } }
}
[$$]";
await VerifyItemExistsAsync(markup, "Namespace1");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeSearch_NamespaceWithNestedAttribute2()
{
var markup = @"
namespace Namespace1
{
namespace Namespace2 { class NonAttribute { } }
namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } }
}
[Namespace1.$$]";
await VerifyItemIsAbsentAsync(markup, "Namespace2");
await VerifyItemExistsAsync(markup, "Namespace3");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeSearch_NamespaceWithNestedAttribute3()
{
var markup = @"
namespace Namespace1
{
namespace Namespace2 { class NonAttribute { } }
namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } }
}
[Namespace1.Namespace3.$$]";
await VerifyItemExistsAsync(markup, "Namespace4");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeSearch_NamespaceWithNestedAttribute4()
{
var markup = @"
namespace Namespace1
{
namespace Namespace2 { class NonAttribute { } }
namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } }
}
[Namespace1.Namespace3.Namespace4.$$]";
await VerifyItemExistsAsync(markup, "Custom");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeSearch_NamespaceWithNestedAttribute_NamespaceAlias()
{
var markup = @"
using Namespace1Alias = Namespace1;
using Namespace2Alias = Namespace1.Namespace2;
using Namespace3Alias = Namespace1.Namespace3;
using Namespace4Alias = Namespace1.Namespace3.Namespace4;
namespace Namespace1
{
namespace Namespace2 { class NonAttribute { } }
namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } }
}
[$$]";
await VerifyItemExistsAsync(markup, "Namespace1Alias");
await VerifyItemIsAbsentAsync(markup, "Namespace2Alias");
await VerifyItemExistsAsync(markup, "Namespace3Alias");
await VerifyItemExistsAsync(markup, "Namespace4Alias");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeSearch_NamespaceWithoutNestedAttribute()
{
var markup = @"
namespace Namespace1
{
namespace Namespace2 { class NonAttribute { } }
namespace Namespace3.Namespace4 { class NonAttribute : System.NonAttribute { } }
}
[$$]";
await VerifyItemIsAbsentAsync(markup, "Namespace1");
}
[WorkItem(542230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542230")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task RangeVariableInQuerySelect()
{
var markup = @"
using System.Linq;
class P
{
void M()
{
var src = new string[] { ""Goo"", ""Bar"" };
var q = from x in src
select x.$$";
await VerifyItemExistsAsync(markup, "Length");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInIsExpression()
{
var markup = @"
class C
{
public const int MAX_SIZE = 10;
void M()
{
int i = 10;
if (i is $$ int"; // 'int' to force this to be parsed as an IsExpression rather than IsPatternExpression
await VerifyItemExistsAsync(markup, "MAX_SIZE");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInIsPatternExpression()
{
var markup = @"
class C
{
public const int MAX_SIZE = 10;
void M()
{
int i = 10;
if (i is $$ 1";
await VerifyItemExistsAsync(markup, "MAX_SIZE");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInSwitchCase()
{
var markup = @"
class C
{
public const int MAX_SIZE = 10;
void M()
{
int i = 10;
switch (i)
{
case $$";
await VerifyItemExistsAsync(markup, "MAX_SIZE");
}
[WorkItem(25084, "https://github.com/dotnet/roslyn/issues/25084#issuecomment-370148553")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInSwitchPatternCase()
{
var markup = @"
class C
{
public const int MAX_SIZE = 10;
void M()
{
int i = 10;
switch (i)
{
case $$ when";
await VerifyItemExistsAsync(markup, "MAX_SIZE");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInSwitchGotoCase()
{
var markup = @"
class C
{
public const int MAX_SIZE = 10;
void M()
{
int i = 10;
switch (i)
{
case MAX_SIZE:
break;
case GOO:
goto case $$";
await VerifyItemExistsAsync(markup, "MAX_SIZE");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInEnumMember()
{
var markup = @"
class C
{
public const int GOO = 0;
enum E
{
A = $$";
await VerifyItemExistsAsync(markup, "GOO");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInAttribute1()
{
var markup = @"
class C
{
public const int GOO = 0;
[System.AttributeUsage($$";
await VerifyItemExistsAsync(markup, "GOO");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInAttribute2()
{
var markup = @"
class C
{
public const int GOO = 0;
[System.AttributeUsage(GOO, $$";
await VerifyItemExistsAsync(markup, "GOO");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInAttribute3()
{
var markup = @"
class C
{
public const int GOO = 0;
[System.AttributeUsage(validOn: $$";
await VerifyItemExistsAsync(markup, "GOO");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInAttribute4()
{
var markup = @"
class C
{
public const int GOO = 0;
[System.AttributeUsage(AllowMultiple = $$";
await VerifyItemExistsAsync(markup, "GOO");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInParameterDefaultValue()
{
var markup = @"
class C
{
public const int GOO = 0;
void M(int x = $$";
await VerifyItemExistsAsync(markup, "GOO");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInConstField()
{
var markup = @"
class C
{
public const int GOO = 0;
const int BAR = $$";
await VerifyItemExistsAsync(markup, "GOO");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInConstLocal()
{
var markup = @"
class C
{
public const int GOO = 0;
void M()
{
const int BAR = $$";
await VerifyItemExistsAsync(markup, "GOO");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionWith1Overload()
{
var markup = @"
class C
{
void M(int i) { }
void M()
{
$$";
await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M(int i) (+ 1 {FeaturesResources.overload})");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionWith2Overloads()
{
var markup = @"
class C
{
void M(int i) { }
void M(out int i) { }
void M()
{
$$";
await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M(int i) (+ 2 {FeaturesResources.overloads_})");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionWith1GenericOverload()
{
var markup = @"
class C
{
void M<T>(T i) { }
void M<T>()
{
$$";
await VerifyItemExistsAsync(markup, "M", displayTextSuffix: "<>", expectedDescriptionOrNull: $"void C.M<T>(T i) (+ 1 {FeaturesResources.generic_overload})");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionWith2GenericOverloads()
{
var markup = @"
class C
{
void M<T>(int i) { }
void M<T>(out int i) { }
void M<T>()
{
$$";
await VerifyItemExistsAsync(markup, "M", displayTextSuffix: "<>", expectedDescriptionOrNull: $"void C.M<T>(int i) (+ 2 {FeaturesResources.generic_overloads})");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionNamedGenericType()
{
var markup = @"
class C<T>
{
void M()
{
$$";
await VerifyItemExistsAsync(markup, "C", displayTextSuffix: "<>", expectedDescriptionOrNull: "class C<T>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionParameter()
{
var markup = @"
class C<T>
{
void M(T goo)
{
$$";
await VerifyItemExistsAsync(markup, "goo", expectedDescriptionOrNull: $"({FeaturesResources.parameter}) T goo");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionGenericTypeParameter()
{
var markup = @"
class C<T>
{
void M()
{
$$";
await VerifyItemExistsAsync(markup, "T", expectedDescriptionOrNull: $"T {FeaturesResources.in_} C<T>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionAnonymousType()
{
var markup = @"
class C
{
void M()
{
var a = new { };
$$
";
var expectedDescription =
$@"({FeaturesResources.local_variable}) 'a a
{FeaturesResources.Anonymous_Types_colon}
'a {FeaturesResources.is_} new {{ }}";
await VerifyItemExistsAsync(markup, "a", expectedDescription);
}
[WorkItem(543288, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543288")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterNewInAnonymousType()
{
var markup = @"
class Program {
string field = 0;
static void Main() {
var an = new { new $$ };
}
}
";
await VerifyItemExistsAsync(markup, "Program");
}
[WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceFieldsInStaticMethod()
{
var markup = @"
class C
{
int x = 0;
static void M()
{
$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "x");
}
[WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceFieldsInStaticFieldInitializer()
{
var markup = @"
class C
{
int x = 0;
static int y = $$
}
";
await VerifyItemIsAbsentAsync(markup, "x");
}
[WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticFieldsInStaticMethod()
{
var markup = @"
class C
{
static int x = 0;
static void M()
{
$$
}
}
";
await VerifyItemExistsAsync(markup, "x");
}
[WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticFieldsInStaticFieldInitializer()
{
var markup = @"
class C
{
static int x = 0;
static int y = $$
}
";
await VerifyItemExistsAsync(markup, "x");
}
[WorkItem(543680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543680")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceFieldsFromOuterClassInInstanceMethod()
{
var markup = @"
class outer
{
int i;
class inner
{
void M()
{
$$
}
}
}
";
await VerifyItemIsAbsentAsync(markup, "i");
}
[WorkItem(543680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543680")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticFieldsFromOuterClassInInstanceMethod()
{
var markup = @"
class outer
{
static int i;
class inner
{
void M()
{
$$
}
}
}
";
await VerifyItemExistsAsync(markup, "i");
}
[WorkItem(543104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543104")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OnlyEnumMembersInEnumMemberAccess()
{
var markup = @"
class C
{
enum x {a,b,c}
void M()
{
x.$$
}
}
";
await VerifyItemExistsAsync(markup, "a");
await VerifyItemExistsAsync(markup, "b");
await VerifyItemExistsAsync(markup, "c");
await VerifyItemIsAbsentAsync(markup, "Equals");
}
[WorkItem(543104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543104")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoEnumMembersInEnumLocalAccess()
{
var markup = @"
class C
{
enum x {a,b,c}
void M()
{
var y = x.a;
y.$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "a");
await VerifyItemIsAbsentAsync(markup, "b");
await VerifyItemIsAbsentAsync(markup, "c");
await VerifyItemExistsAsync(markup, "Equals");
}
[WorkItem(529138, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529138")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterLambdaParameterDot()
{
var markup = @"
using System;
using System.Linq;
class A
{
public event Func<String, String> E;
}
class Program
{
static void Main(string[] args)
{
new A().E += ss => ss.$$
}
}
";
await VerifyItemExistsAsync(markup, "Substring");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotAtRoot_Interactive()
{
await VerifyItemIsAbsentAsync(
@"$$",
"value",
expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotAfterClass_Interactive()
{
await VerifyItemIsAbsentAsync(
@"class C { }
$$",
"value",
expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotAfterGlobalStatement_Interactive()
{
await VerifyItemIsAbsentAsync(
@"System.Console.WriteLine();
$$",
"value",
expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotAfterGlobalVariableDeclaration_Interactive()
{
await VerifyItemIsAbsentAsync(
@"int i = 0;
$$",
"value",
expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotInUsingAlias()
{
await VerifyItemIsAbsentAsync(
@"using Goo = $$",
"value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotInEmptyStatement()
{
await VerifyItemIsAbsentAsync(AddInsideMethod(
@"$$"),
"value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueInsideSetter()
{
await VerifyItemExistsAsync(
@"class C {
int Goo {
set {
$$",
"value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueInsideAdder()
{
await VerifyItemExistsAsync(
@"class C {
event int Goo {
add {
$$",
"value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueInsideRemover()
{
await VerifyItemExistsAsync(
@"class C {
event int Goo {
remove {
$$",
"value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotAfterDot()
{
await VerifyItemIsAbsentAsync(
@"class C {
int Goo {
set {
this.$$",
"value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotAfterArrow()
{
await VerifyItemIsAbsentAsync(
@"class C {
int Goo {
set {
a->$$",
"value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotAfterColonColon()
{
await VerifyItemIsAbsentAsync(
@"class C {
int Goo {
set {
a::$$",
"value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotInGetter()
{
await VerifyItemIsAbsentAsync(
@"class C {
int Goo {
get {
$$",
"value");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterNullableType()
{
await VerifyItemIsAbsentAsync(
@"class C {
void M() {
int goo = 0;
C? $$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterNullableTypeAlias()
{
await VerifyItemIsAbsentAsync(
@"using A = System.Int32;
class C {
void M() {
int goo = 0;
A? $$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotAfterNullableTypeAndPartialIdentifier()
{
await VerifyItemIsAbsentAsync(
@"class C {
void M() {
int goo = 0;
C? f$$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterQuestionMarkInConditional()
{
await VerifyItemExistsAsync(
@"class C {
void M() {
bool b = false;
int goo = 0;
b? $$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterQuestionMarkAndPartialIdentifierInConditional()
{
await VerifyItemExistsAsync(
@"class C {
void M() {
bool b = false;
int goo = 0;
b? f$$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterPointerType()
{
await VerifyItemIsAbsentAsync(
@"class C {
void M() {
int goo = 0;
C* $$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterPointerTypeAlias()
{
await VerifyItemIsAbsentAsync(
@"using A = System.Int32;
class C {
void M() {
int goo = 0;
A* $$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterPointerTypeAndPartialIdentifier()
{
await VerifyItemIsAbsentAsync(
@"class C {
void M() {
int goo = 0;
C* f$$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterAsteriskInMultiplication()
{
await VerifyItemExistsAsync(
@"class C {
void M() {
int i = 0;
int goo = 0;
i* $$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterAsteriskAndPartialIdentifierInMultiplication()
{
await VerifyItemExistsAsync(
@"class C {
void M() {
int i = 0;
int goo = 0;
i* f$$",
"goo");
}
[WorkItem(543868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543868")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterEventFieldDeclaredInSameType()
{
await VerifyItemExistsAsync(
@"class C {
public event System.EventHandler E;
void M() {
E.$$",
"Invoke");
}
[WorkItem(543868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543868")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterFullEventDeclaredInSameType()
{
await VerifyItemIsAbsentAsync(
@"class C {
public event System.EventHandler E { add { } remove { } }
void M() {
E.$$",
"Invoke");
}
[WorkItem(543868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543868")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterEventDeclaredInDifferentType()
{
await VerifyItemIsAbsentAsync(
@"class C {
void M() {
System.Console.CancelKeyPress.$$",
"Invoke");
}
[WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInObjectInitializerMemberContext()
{
await VerifyItemIsAbsentAsync(@"
class C
{
public int x, y;
void M()
{
var c = new C { x = 2, y = 3, $$",
"x");
}
[WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task AfterPointerMemberAccess()
{
await VerifyItemExistsAsync(@"
struct MyStruct
{
public int MyField;
}
class Program
{
static unsafe void Main(string[] args)
{
MyStruct s = new MyStruct();
MyStruct* ptr = &s;
ptr->$$
}}",
"MyField");
}
// After @ both X and XAttribute are legal. We think this is an edge case in the language and
// are not fixing the bug 11931. This test captures that XAttribute doesn't show up indeed.
[WorkItem(11931, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task VerbatimAttributes()
{
var code = @"
using System;
public class X : Attribute
{ }
public class XAttribute : Attribute
{ }
[@X$$]
class Class3 { }
";
await VerifyItemExistsAsync(code, "X");
await Assert.ThrowsAsync<Xunit.Sdk.TrueException>(() => VerifyItemExistsAsync(code, "XAttribute"));
}
[WorkItem(544928, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544928")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task InForLoopIncrementor1()
{
await VerifyItemExistsAsync(@"
using System;
class Program
{
static void Main()
{
for (; ; $$
}
}
", "Console");
}
[WorkItem(544928, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544928")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task InForLoopIncrementor2()
{
await VerifyItemExistsAsync(@"
using System;
class Program
{
static void Main()
{
for (; ; Console.WriteLine(), $$
}
}
", "Console");
}
[WorkItem(544931, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544931")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task InForLoopInitializer1()
{
await VerifyItemExistsAsync(@"
using System;
class Program
{
static void Main()
{
for ($$
}
}
", "Console");
}
[WorkItem(544931, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544931")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task InForLoopInitializer2()
{
await VerifyItemExistsAsync(@"
using System;
class Program
{
static void Main()
{
for (Console.WriteLine(), $$
}
}
", "Console");
}
[WorkItem(10572, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LocalVariableInItsDeclaration()
{
// "int goo = goo = 1" is a legal declaration
await VerifyItemExistsAsync(@"
class Program
{
void M()
{
int goo = $$
}
}", "goo");
}
[WorkItem(10572, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LocalVariableInItsDeclarator()
{
// "int bar = bar = 1" is legal in a declarator
await VerifyItemExistsAsync(@"
class Program
{
void M()
{
int goo = 0, int bar = $$, int baz = 0;
}
}", "bar");
}
[WorkItem(10572, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LocalVariableNotBeforeDeclaration()
{
await VerifyItemIsAbsentAsync(@"
class Program
{
void M()
{
$$
int goo = 0;
}
}", "goo");
}
[WorkItem(10572, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LocalVariableNotBeforeDeclarator()
{
await VerifyItemIsAbsentAsync(@"
class Program
{
void M()
{
int goo = $$, bar = 0;
}
}", "bar");
}
[WorkItem(10572, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LocalVariableAfterDeclarator()
{
await VerifyItemExistsAsync(@"
class Program
{
void M()
{
int goo = 0, int bar = $$
}
}", "goo");
}
[WorkItem(10572, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LocalVariableAsOutArgumentInInitializerExpression()
{
await VerifyItemExistsAsync(@"
class Program
{
void M()
{
int goo = Bar(out $$
}
int Bar(out int x)
{
x = 3;
return 5;
}
}", "goo");
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Method_BrowsableStateAlways()
{
var markup = @"
class Program
{
void M()
{
Goo.$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Method_BrowsableStateNever()
{
var markup = @"
class Program
{
void M()
{
Goo.$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Method_BrowsableStateAdvanced()
{
var markup = @"
class Program
{
void M()
{
Goo.$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public static void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Method_Overloads_BothBrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
Goo.$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar()
{
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar(int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 2,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Method_Overloads_OneBrowsableAlways_OneBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
Goo.$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar()
{
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static void Bar(int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Method_Overloads_BothBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
Goo.$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static void Bar()
{
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static void Bar(int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_ExtensionMethod_BrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
}
public static class GooExtensions
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar(this Goo goo, int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_ExtensionMethod_BrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
}
public static class GooExtensions
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static void Bar(this Goo goo, int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_ExtensionMethod_BrowsableAdvanced()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
}
public static class GooExtensions
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public static void Bar(this Goo goo, int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_ExtensionMethod_BrowsableMixed()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
}
public static class GooExtensions
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar(this Goo goo, int x)
{
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static void Bar(this Goo goo, int x, int y)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_OverloadExtensionMethodAndMethod_BrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public void Bar(int x)
{
}
}
public static class GooExtensions
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar(this Goo goo, int x, int y)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 2,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_OverloadExtensionMethodAndMethod_BrowsableMixed()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Bar(int x)
{
}
}
public static class GooExtensions
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar(this Goo goo, int x, int y)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_SameSigExtensionMethodAndMethod_InstanceMethodBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Bar(int x)
{
}
}
public static class GooExtensions
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar(this Goo goo, int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OverriddenSymbolsFilteredFromCompletionList()
{
var markup = @"
class Program
{
void M()
{
D d = new D();
d.$$
}
}";
var referencedCode = @"
public class B
{
public virtual void Goo(int original)
{
}
}
public class D : B
{
public override void Goo(int derived)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverClass()
{
var markup = @"
class Program
{
void M()
{
C c = new C();
c.$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public class C
{
public void Goo()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverBaseClass()
{
var markup = @"
class Program
{
void M()
{
D d = new D();
d.$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public class B
{
public void Goo()
{
}
}
public class D : B
{
public void Goo(int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 2,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_BrowsableStateNeverMethodsInBaseClass()
{
var markup = @"
class Program : B
{
void M()
{
$$
}
}";
var referencedCode = @"
public class B
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
var ci = new C<int>();
ci.$$
}
}";
var referencedCode = @"
public class C<T>
{
public void Goo(T t) { }
public void Goo(int i) { }
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 2,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed1()
{
var markup = @"
class Program
{
void M()
{
var ci = new C<int>();
ci.$$
}
}";
var referencedCode = @"
public class C<T>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo(T t) { }
public void Goo(int i) { }
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed2()
{
var markup = @"
class Program
{
void M()
{
var ci = new C<int>();
ci.$$
}
}";
var referencedCode = @"
public class C<T>
{
public void Goo(T t) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo(int i) { }
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
var ci = new C<int>();
ci.$$
}
}";
var referencedCode = @"
public class C<T>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo(T t) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo(int i) { }
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
var cii = new C<int, int>();
cii.$$
}
}";
var referencedCode = @"
public class C<T, U>
{
public void Goo(T t) { }
public void Goo(U u) { }
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 2,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_GenericType2CausingMethodSignatureEquality_BrowsableMixed()
{
var markup = @"
class Program
{
void M()
{
var cii = new C<int, int>();
cii.$$
}
}";
var referencedCode = @"
public class C<T, U>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo(T t) { }
public void Goo(U u) { }
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
var cii = new C<int, int>();
cii.$$
}
}";
var referencedCode = @"
public class C<T, U>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo(T t) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo(U u) { }
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Field_BrowsableStateNever()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Field_BrowsableStateAlways()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Field_BrowsableStateAdvanced()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
}
[WorkItem(522440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/522440")]
[WorkItem(674611, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/674611")]
[WpfFact(Skip = "674611"), Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Property_BrowsableStateNever()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public int Bar {get; set;}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Property_IgnoreBrowsabilityOfGetSetMethods()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
public int Bar {
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
get { return 5; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
set { }
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Property_BrowsableStateAlways()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public int Bar {get; set;}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Property_BrowsableStateAdvanced()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public int Bar {get; set;}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Constructor_BrowsableStateNever()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public Goo()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Constructor_BrowsableStateAlways()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public Goo()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Constructor_BrowsableStateAdvanced()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public Goo()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Constructor_MixedOverloads1()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public Goo()
{
}
public Goo(int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Constructor_MixedOverloads2()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public Goo()
{
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public Goo(int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Event_BrowsableStateNever()
{
var markup = @"
class Program
{
void M()
{
new C().$$
}
}";
var referencedCode = @"
public delegate void Handler();
public class C
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public event Handler Changed;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Changed",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Event_BrowsableStateAlways()
{
var markup = @"
class Program
{
void M()
{
new C().$$
}
}";
var referencedCode = @"
public delegate void Handler();
public class C
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public event Handler Changed;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Changed",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Event_BrowsableStateAdvanced()
{
var markup = @"
class Program
{
void M()
{
new C().$$
}
}";
var referencedCode = @"
public delegate void Handler();
public class C
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public event Handler Changed;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Changed",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Changed",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Delegate_BrowsableStateNever()
{
var markup = @"
class Program
{
public event $$
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public delegate void Handler();";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Handler",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Delegate_BrowsableStateAlways()
{
var markup = @"
class Program
{
public event $$
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public delegate void Handler();";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Handler",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Delegate_BrowsableStateAdvanced()
{
var markup = @"
class Program
{
public event $$
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public delegate void Handler();";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Handler",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Handler",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateNever_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateNever_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateNever_FullyQualifiedInUsing()
{
var markup = @"
class Program
{
void M()
{
using (var x = new NS.$$
}
}";
var referencedCode = @"
namespace NS
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public class Goo : System.IDisposable
{
public void Dispose()
{
}
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateAlways_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateAlways_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateAlways_FullyQualifiedInUsing()
{
var markup = @"
class Program
{
void M()
{
using (var x = new NS.$$
}
}";
var referencedCode = @"
namespace NS
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public class Goo : System.IDisposable
{
public void Dispose()
{
}
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateAdvanced_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateAdvanced_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateAdvanced_FullyQualifiedInUsing()
{
var markup = @"
class Program
{
void M()
{
using (var x = new NS.$$
}
}";
var referencedCode = @"
namespace NS
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public class Goo : System.IDisposable
{
public void Dispose()
{
}
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_IgnoreBaseClassBrowsableNever()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
public class Goo : Bar
{
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public class Bar
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Struct_BrowsableStateNever_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public struct Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Struct_BrowsableStateNever_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public struct Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Struct_BrowsableStateAlways_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public struct Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Struct_BrowsableStateAlways_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public struct Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Struct_BrowsableStateAdvanced_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public struct Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Struct_BrowsableStateAdvanced_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public struct Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Enum_BrowsableStateNever()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public enum Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Enum_BrowsableStateAlways()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public enum Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Enum_BrowsableStateAdvanced()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public enum Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Interface_BrowsableStateNever_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public interface Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Interface_BrowsableStateNever_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public interface Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Interface_BrowsableStateAlways_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public interface Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Interface_BrowsableStateAlways_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public interface Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Interface_BrowsableStateAdvanced_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public interface Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Interface_BrowsableStateAdvanced_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public interface Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_CrossLanguage_CStoVB_Always()
{
var markup = @"
class Program
{
void M()
{
$$
}
}";
var referencedCode = @"
<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)>
Public Class Goo
End Class";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.VisualBasic,
hideAdvancedMembers: false);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_CrossLanguage_CStoVB_Never()
{
var markup = @"
class Program
{
void M()
{
$$
}
}";
var referencedCode = @"
<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)>
Public Class Goo
End Class";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 0,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.VisualBasic,
hideAdvancedMembers: false);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibType_NotHidden()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
[System.Runtime.InteropServices.TypeLibType(System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibType_Hidden()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
[System.Runtime.InteropServices.TypeLibType(System.Runtime.InteropServices.TypeLibTypeFlags.FHidden)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibType_HiddenAndOtherFlags()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
[System.Runtime.InteropServices.TypeLibType(System.Runtime.InteropServices.TypeLibTypeFlags.FHidden | System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibType_NotHidden_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
[System.Runtime.InteropServices.TypeLibType((short)System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibType_Hidden_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
[System.Runtime.InteropServices.TypeLibType((short)System.Runtime.InteropServices.TypeLibTypeFlags.FHidden)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibType_HiddenAndOtherFlags_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
[System.Runtime.InteropServices.TypeLibType((short)(System.Runtime.InteropServices.TypeLibTypeFlags.FHidden | System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed))]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibFunc_NotHidden()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibFunc(System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable)]
public void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibFunc_Hidden()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibFunc(System.Runtime.InteropServices.TypeLibFuncFlags.FHidden)]
public void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibFunc_HiddenAndOtherFlags()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibFunc(System.Runtime.InteropServices.TypeLibFuncFlags.FHidden | System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable)]
public void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibFunc_NotHidden_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibFunc((short)System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable)]
public void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibFunc_Hidden_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibFunc((short)System.Runtime.InteropServices.TypeLibFuncFlags.FHidden)]
public void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibFunc_HiddenAndOtherFlags_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibFunc((short)(System.Runtime.InteropServices.TypeLibFuncFlags.FHidden | System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable))]
public void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibVar_NotHidden()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibVar(System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable)]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibVar_Hidden()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibVar(System.Runtime.InteropServices.TypeLibVarFlags.FHidden)]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibVar_HiddenAndOtherFlags()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibVar(System.Runtime.InteropServices.TypeLibVarFlags.FHidden | System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable)]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibVar_NotHidden_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibVar((short)System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable)]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibVar_Hidden_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibVar((short)System.Runtime.InteropServices.TypeLibVarFlags.FHidden)]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibVar_HiddenAndOtherFlags_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibVar((short)(System.Runtime.InteropServices.TypeLibVarFlags.FHidden | System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable))]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(545557, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545557")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestColorColor1()
{
var markup = @"
class A
{
static void Goo() { }
void Bar() { }
static void Main()
{
A A = new A();
A.$$
}
}";
await VerifyItemExistsAsync(markup, "Goo");
await VerifyItemExistsAsync(markup, "Bar");
}
[WorkItem(545647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545647")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestLaterLocalHidesType1()
{
var markup = @"
using System;
class C
{
public static void Main()
{
$$
Console.WriteLine();
}
}";
await VerifyItemExistsAsync(markup, "Console");
}
[WorkItem(545647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545647")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestLaterLocalHidesType2()
{
var markup = @"
using System;
class C
{
public static void Main()
{
C$$
Console.WriteLine();
}
}";
await VerifyItemExistsAsync(markup, "Console");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestIndexedProperty()
{
var markup = @"class Program
{
void M()
{
CCC c = new CCC();
c.$$
}
}";
// Note that <COMImport> is required by compiler. Bug 17013 tracks enabling indexed property for non-COM types.
var referencedCode = @"Imports System.Runtime.InteropServices
<ComImport()>
<GuidAttribute(CCC.ClassId)>
Public Class CCC
#Region ""COM GUIDs""
Public Const ClassId As String = ""9d965fd2-1514-44f6-accd-257ce77c46b0""
Public Const InterfaceId As String = ""a9415060-fdf0-47e3-bc80-9c18f7f39cf6""
Public Const EventsId As String = ""c6a866a5-5f97-4b53-a5df-3739dc8ff1bb""
# End Region
''' <summary>
''' An index property from VB
''' </summary>
''' <param name=""p1"">p1 is an integer index</param>
''' <returns>A string</returns>
Public Property IndexProp(ByVal p1 As Integer, Optional ByVal p2 As Integer = 0) As String
Get
Return Nothing
End Get
Set(ByVal value As String)
End Set
End Property
End Class";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "IndexProp",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.VisualBasic);
}
[WorkItem(546841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546841")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestDeclarationAmbiguity()
{
var markup = @"
using System;
class Program
{
void Main()
{
Environment.$$
var v;
}
}";
await VerifyItemExistsAsync(markup, "CommandLine");
}
[WorkItem(12781, "https://github.com/dotnet/roslyn/issues/12781")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestFieldDeclarationAmbiguity()
{
var markup = @"
using System;
Environment.$$
var v;
}";
await VerifyItemExistsAsync(markup, "CommandLine", sourceCodeKind: SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestCursorOnClassCloseBrace()
{
var markup = @"
using System;
class Outer
{
class Inner { }
$$}";
await VerifyItemExistsAsync(markup, "Inner");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterAsync1()
{
var markup = @"
using System.Threading.Tasks;
class Program
{
async $$
}";
await VerifyItemExistsAsync(markup, "Task");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterAsync2()
{
var markup = @"
using System.Threading.Tasks;
class Program
{
public async T$$
}";
await VerifyItemExistsAsync(markup, "Task");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterAsyncInMethodBody()
{
var markup = @"
using System.Threading.Tasks;
class Program
{
void goo()
{
var x = async $$
}
}";
await VerifyItemIsAbsentAsync(markup, "Task");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAwaitable1()
{
var markup = @"
class Program
{
void goo()
{
$$
}
}";
await VerifyItemWithMscorlib45Async(markup, "goo", "void Program.goo()", "C#");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAwaitable2()
{
var markup = @"
class Program
{
async void goo()
{
$$
}
}";
await VerifyItemWithMscorlib45Async(markup, "goo", "void Program.goo()", "C#");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Awaitable1()
{
var markup = @"
using System.Threading;
using System.Threading.Tasks;
class Program
{
async Task goo()
{
$$
}
}";
var description = $@"({CSharpFeaturesResources.awaitable}) Task Program.goo()";
await VerifyItemWithMscorlib45Async(markup, "goo", description, "C#");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Awaitable2()
{
var markup = @"
using System.Threading.Tasks;
class Program
{
async Task<int> goo()
{
$$
}
}";
var description = $@"({CSharpFeaturesResources.awaitable}) Task<int> Program.goo()";
await VerifyItemWithMscorlib45Async(markup, "goo", description, "C#");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AwaitableDotsLikeRangeExpression()
{
var markup = @"
using System.IO;
using System.Threading.Tasks;
namespace N
{
class C
{
async Task M()
{
var request = new Request();
var m = await request.$$.ReadAsStreamAsync();
}
}
class Request
{
public Task<Stream> ReadAsStreamAsync() => null;
}
}";
await VerifyItemExistsAsync(markup, "ReadAsStreamAsync");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AwaitableDotsLikeRangeExpressionWithParentheses()
{
var markup = @"
using System.IO;
using System.Threading.Tasks;
namespace N
{
class C
{
async Task M()
{
var request = new Request();
var m = (await request).$$.ReadAsStreamAsync();
}
}
class Request
{
public Task<Stream> ReadAsStreamAsync() => null;
}
}";
// Nothing should be found: no awaiter for request.
await VerifyItemIsAbsentAsync(markup, "Result");
await VerifyItemIsAbsentAsync(markup, "ReadAsStreamAsync");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AwaitableDotsLikeRangeExpressionWithTaskAndParentheses()
{
var markup = @"
using System.IO;
using System.Threading.Tasks;
namespace N
{
class C
{
async Task M()
{
var request = new Task<Request>();
var m = (await request).$$.ReadAsStreamAsync();
}
}
class Request
{
public Task<Stream> ReadAsStreamAsync() => null;
}
}";
await VerifyItemIsAbsentAsync(markup, "Result");
await VerifyItemExistsAsync(markup, "ReadAsStreamAsync");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ObsoleteItem()
{
var markup = @"
using System;
class Program
{
[Obsolete]
public void goo()
{
$$
}
}";
await VerifyItemExistsAsync(markup, "goo", $"[{CSharpFeaturesResources.deprecated}] void Program.goo()");
}
[WorkItem(568986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568986")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoMembersOnDottingIntoUnboundType()
{
var markup = @"
class Program
{
RegistryKey goo;
static void Main(string[] args)
{
goo.$$
}
}";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(550717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/550717")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeArgumentsInConstraintAfterBaselist()
{
var markup = @"
public class Goo<T> : System.Object where $$
{
}";
await VerifyItemExistsAsync(markup, "T");
}
[WorkItem(647175, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/647175")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoDestructor()
{
var markup = @"
class C
{
~C()
{
$$
";
await VerifyItemIsAbsentAsync(markup, "Finalize");
}
[WorkItem(669624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/669624")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExtensionMethodOnCovariantInterface()
{
var markup = @"
class Schema<T> { }
interface ISet<out T> { }
static class SetMethods
{
public static void ForSchemaSet<T>(this ISet<Schema<T>> set) { }
}
class Context
{
public ISet<T> Set<T>() { return null; }
}
class CustomSchema : Schema<int> { }
class Program
{
static void Main(string[] args)
{
var set = new Context().Set<CustomSchema>();
set.$$
";
await VerifyItemExistsAsync(markup, "ForSchemaSet", displayTextSuffix: "<>", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(667752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667752")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForEachInsideParentheses()
{
var markup = @"
using System;
class C
{
void M()
{
foreach($$)
";
await VerifyItemExistsAsync(markup, "String");
}
[WorkItem(766869, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766869")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestFieldInitializerInP2P()
{
var markup = @"
class Class
{
int i = Consts.$$;
}";
var referencedCode = @"
public static class Consts
{
public const int C = 1;
}";
await VerifyItemWithProjectReferenceAsync(markup, referencedCode, "C", 1, LanguageNames.CSharp, LanguageNames.CSharp, false);
}
[WorkItem(834605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834605")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ShowWithEqualsSign()
{
var markup = @"
class c { public int value {set; get; }}
class d
{
void goo()
{
c goo = new c { value$$=
}
}";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(825661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825661")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NothingAfterThisDotInStaticContext()
{
var markup = @"
class C
{
void M1() { }
static void M2()
{
this.$$
}
}";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(825661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825661")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NothingAfterBaseDotInStaticContext()
{
var markup = @"
class C
{
void M1() { }
static void M2()
{
base.$$
}
}";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(7648, "http://github.com/dotnet/roslyn/issues/7648")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NothingAfterBaseDotInScriptContext()
=> await VerifyItemIsAbsentAsync(@"base.$$", @"ToString", sourceCodeKind: SourceCodeKind.Script);
[WorkItem(858086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858086")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoNestedTypeWhenDisplayingInstance()
{
var markup = @"
class C
{
class D
{
}
void M2()
{
new C().$$
}
}";
await VerifyItemIsAbsentAsync(markup, "D");
}
[WorkItem(876031, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/876031")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CatchVariableInExceptionFilter()
{
var markup = @"
class C
{
void M()
{
try
{
}
catch (System.Exception myExn) when ($$";
await VerifyItemExistsAsync(markup, "myExn");
}
[WorkItem(849698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849698")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionAfterExternAlias()
{
var markup = @"
class C
{
void goo()
{
global::$$
}
}";
await VerifyItemExistsAsync(markup, "System", usePreviousCharAsTrigger: true);
}
[WorkItem(849698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849698")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExternAliasSuggested()
{
var markup = @"
extern alias Bar;
class C
{
void goo()
{
$$
}
}";
await VerifyItemWithAliasedMetadataReferencesAsync(markup, "Bar", "Bar", 1, "C#", "C#", false);
}
[WorkItem(635957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635957")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ClassDestructor()
{
var markup = @"
class C
{
class N
{
~$$
}
}";
await VerifyItemExistsAsync(markup, "N");
await VerifyItemIsAbsentAsync(markup, "C");
}
[WorkItem(635957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635957")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")]
public async Task TildeOutsideClass()
{
var markup = @"
class C
{
class N
{
}
}
~$$";
await VerifyItemExistsAsync(markup, "C");
await VerifyItemIsAbsentAsync(markup, "N");
}
[WorkItem(635957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635957")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StructDestructor()
{
var markup = @"
struct C
{
~$$
}";
await VerifyItemIsAbsentAsync(markup, "C");
}
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData("record")]
[InlineData("record class")]
public async Task RecordDestructor(string record)
{
var markup = $@"
{record} C
{{
~$$
}}";
await VerifyItemExistsAsync(markup, "C");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task RecordStructDestructor()
{
var markup = $@"
record struct C
{{
~$$
}}";
await VerifyItemIsAbsentAsync(markup, "C");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FieldAvailableInBothLinkedFiles()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
int x;
void goo()
{
$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
await VerifyItemInLinkedFilesAsync(markup, "x", $"({FeaturesResources.field}) int C.x");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FieldUnavailableInOneLinkedFile()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if GOO
int x;
#endif
void goo()
{
$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({FeaturesResources.field}) int C.x\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}";
await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FieldUnavailableInTwoLinkedFiles()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if GOO
int x;
#endif
void goo()
{
$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({FeaturesResources.field}) int C.x\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}";
await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExcludeFilesWithInactiveRegions()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO,BAR"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if GOO
int x;
#endif
#if BAR
void goo()
{
$$
}
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs"" />
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({FeaturesResources.field}) int C.x\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}";
await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UnionOfItemsFromBothContexts()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if GOO
int x;
#endif
#if BAR
class G
{
public void DoGStuff() {}
}
#endif
void goo()
{
new G().$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""BAR"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"void G.DoGStuff()\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}";
await VerifyItemInLinkedFilesAsync(markup, "DoGStuff", expectedDescription);
}
[WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LocalsValidInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
void M()
{
int xyz;
$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({FeaturesResources.local_variable}) int xyz";
await VerifyItemInLinkedFilesAsync(markup, "xyz", expectedDescription);
}
[WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LocalWarningInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""PROJ1"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
void M()
{
#if PROJ1
int xyz;
#endif
$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({FeaturesResources.local_variable}) int xyz\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}";
await VerifyItemInLinkedFilesAsync(markup, "xyz", expectedDescription);
}
[WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LabelsValidInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
void M()
{
LABEL: int xyz;
goto $$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({FeaturesResources.label}) LABEL";
await VerifyItemInLinkedFilesAsync(markup, "LABEL", expectedDescription);
}
[WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task RangeVariablesValidInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
using System.Linq;
class C
{
void M()
{
var x = from y in new[] { 1, 2, 3 } select $$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({FeaturesResources.range_variable}) ? y";
await VerifyItemInLinkedFilesAsync(markup, "y", expectedDescription);
}
[WorkItem(1063403, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1063403")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodOverloadDifferencesIgnored()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if ONE
void Do(int x){}
#endif
#if TWO
void Do(string x){}
#endif
void Shared()
{
$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"void C.Do(int x)";
await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodOverloadDifferencesIgnored_ExtensionMethod()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if ONE
void Do(int x){}
#endif
void Shared()
{
this.$$
}
}
public static class Extensions
{
#if TWO
public static void Do (this C c, string x)
{
}
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"void C.Do(int x)";
await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodOverloadDifferencesIgnored_ExtensionMethod2()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""TWO"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if ONE
void Do(int x){}
#endif
void Shared()
{
this.$$
}
}
public static class Extensions
{
#if TWO
public static void Do (this C c, string x)
{
}
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""ONE"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({CSharpFeaturesResources.extension}) void C.Do(string x)";
await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodOverloadDifferencesIgnored_ContainingType()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
void Shared()
{
var x = GetThing();
x.$$
}
#if ONE
private Methods1 GetThing()
{
return new Methods1();
}
#endif
#if TWO
private Methods2 GetThing()
{
return new Methods2();
}
#endif
}
#if ONE
public class Methods1
{
public void Do(string x) { }
}
#endif
#if TWO
public class Methods2
{
public void Do(string x) { }
}
#endif
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"void Methods1.Do(string x)";
await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SharedProjectFieldAndPropertiesTreatedAsIdentical()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if ONE
public int x;
#endif
#if TWO
public int x {get; set;}
#endif
void goo()
{
x$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({ FeaturesResources.field }) int C.x";
await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SharedProjectFieldAndPropertiesTreatedAsIdentical2()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if TWO
public int x;
#endif
#if ONE
public int x {get; set;}
#endif
void goo()
{
x$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = "int C.x { get; set; }";
await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConditionalAccessWalkUp()
{
var markup = @"
public class B
{
public A BA;
public B BB;
}
class A
{
public A AA;
public A AB;
public int? x;
public void goo()
{
A a = null;
var q = a?.$$AB.BA.AB.BA;
}
}";
await VerifyItemExistsAsync(markup, "AA");
await VerifyItemExistsAsync(markup, "AB");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConditionalAccessNullableIsUnwrapped()
{
var markup = @"
public struct S
{
public int? i;
}
class A
{
public S? s;
public void goo()
{
A a = null;
var q = a?.s?.$$;
}
}";
await VerifyItemExistsAsync(markup, "i");
await VerifyItemIsAbsentAsync(markup, "value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConditionalAccessNullableIsUnwrapped2()
{
var markup = @"
public struct S
{
public int? i;
}
class A
{
public S? s;
public void goo()
{
var q = s?.$$i?.ToString();
}
}";
await VerifyItemExistsAsync(markup, "i");
await VerifyItemIsAbsentAsync(markup, "value");
}
[WorkItem(54361, "https://github.com/dotnet/roslyn/issues/54361")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConditionalAccessNullableIsUnwrappedOnParameter()
{
var markup = @"
class A
{
void M(System.DateTime? dt)
{
dt?.$$
}
}
";
await VerifyItemExistsAsync(markup, "Day");
await VerifyItemIsAbsentAsync(markup, "Value");
}
[WorkItem(54361, "https://github.com/dotnet/roslyn/issues/54361")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NullableIsNotUnwrappedOnParameter()
{
var markup = @"
class A
{
void M(System.DateTime? dt)
{
dt.$$
}
}
";
await VerifyItemExistsAsync(markup, "Value");
await VerifyItemIsAbsentAsync(markup, "Day");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionAfterConditionalIndexing()
{
var markup = @"
public struct S
{
public int? i;
}
class A
{
public S[] s;
public void goo()
{
A a = null;
var q = a?.s?[$$;
}
}";
await VerifyItemExistsAsync(markup, "System");
}
[WorkItem(1109319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109319")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WithinChainOfConditionalAccesses1()
{
var markup = @"
class Program
{
static void Main(string[] args)
{
A a;
var x = a?.$$b?.c?.d.e;
}
}
class A { public B b; }
class B { public C c; }
class C { public D d; }
class D { public int e; }";
await VerifyItemExistsAsync(markup, "b");
}
[WorkItem(1109319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109319")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WithinChainOfConditionalAccesses2()
{
var markup = @"
class Program
{
static void Main(string[] args)
{
A a;
var x = a?.b?.$$c?.d.e;
}
}
class A { public B b; }
class B { public C c; }
class C { public D d; }
class D { public int e; }";
await VerifyItemExistsAsync(markup, "c");
}
[WorkItem(1109319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109319")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WithinChainOfConditionalAccesses3()
{
var markup = @"
class Program
{
static void Main(string[] args)
{
A a;
var x = a?.b?.c?.$$d.e;
}
}
class A { public B b; }
class B { public C c; }
class C { public D d; }
class D { public int e; }";
await VerifyItemExistsAsync(markup, "d");
}
[WorkItem(843466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843466")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedAttributeAccessibleOnSelf()
{
var markup = @"using System;
[My]
class X
{
[My$$]
class MyAttribute : Attribute
{
}
}";
await VerifyItemExistsAsync(markup, "My");
}
[WorkItem(843466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843466")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedAttributeAccessibleOnOuterType()
{
var markup = @"using System;
[My]
class Y
{
}
[$$]
class X
{
[My]
class MyAttribute : Attribute
{
}
}";
await VerifyItemExistsAsync(markup, "My");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMembersFromBaseOuterType()
{
var markup = @"abstract class Test
{
private int _field;
public sealed class InnerTest : Test
{
public void SomeTest()
{
$$
}
}
}";
await VerifyItemExistsAsync(markup, "_field");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMembersFromBaseOuterType2()
{
var markup = @"class C<T>
{
void M() { }
class N : C<int>
{
void Test()
{
$$ // M recommended and accessible
}
class NN
{
void Test2()
{
// M inaccessible and not recommended
}
}
}
}";
await VerifyItemExistsAsync(markup, "M");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMembersFromBaseOuterType3()
{
var markup = @"class C<T>
{
void M() { }
class N : C<int>
{
void Test()
{
M(); // M recommended and accessible
}
class NN
{
void Test2()
{
$$ // M inaccessible and not recommended
}
}
}
}";
await VerifyItemIsAbsentAsync(markup, "M");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMembersFromBaseOuterType4()
{
var markup = @"class C<T>
{
void M() { }
class N : C<int>
{
void Test()
{
M(); // M recommended and accessible
}
class NN : N
{
void Test2()
{
$$ // M accessible and recommended.
}
}
}
}";
await VerifyItemExistsAsync(markup, "M");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMembersFromBaseOuterType5()
{
var markup = @"
class D
{
public void Q() { }
}
class C<T> : D
{
class N
{
void Test()
{
$$
}
}
}";
await VerifyItemIsAbsentAsync(markup, "Q");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMembersFromBaseOuterType6()
{
var markup = @"
class Base<T>
{
public int X;
}
class Derived : Base<int>
{
class Nested
{
void Test()
{
$$
}
}
}";
await VerifyItemIsAbsentAsync(markup, "X");
}
[WorkItem(983367, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/983367")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoTypeParametersDefinedInCrefs()
{
var markup = @"using System;
/// <see cref=""Program{T$$}""/>
class Program<T> { }";
await VerifyItemIsAbsentAsync(markup, "T");
}
[WorkItem(988025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/988025")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ShowTypesInGenericMethodTypeParameterList1()
{
var markup = @"
class Class1<T, D>
{
public static Class1<T, D> Create() { return null; }
}
static class Class2
{
public static void Test<T,D>(this Class1<T, D> arg)
{
}
}
class Program
{
static void Main(string[] args)
{
Class1<string, int>.Create().Test<$$
}
}
";
await VerifyItemExistsAsync(markup, "Class1", displayTextSuffix: "<>", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(988025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/988025")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ShowTypesInGenericMethodTypeParameterList2()
{
var markup = @"
class Class1<T, D>
{
public static Class1<T, D> Create() { return null; }
}
static class Class2
{
public static void Test<T,D>(this Class1<T, D> arg)
{
}
}
class Program
{
static void Main(string[] args)
{
Class1<string, int>.Create().Test<string,$$
}
}
";
await VerifyItemExistsAsync(markup, "Class1", displayTextSuffix: "<>", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionInAliasedType()
{
var markup = @"
using IAlias = IGoo;
///<summary>summary for interface IGoo</summary>
interface IGoo { }
class C
{
I$$
}
";
await VerifyItemExistsAsync(markup, "IAlias", expectedDescriptionOrNull: "interface IGoo\r\nsummary for interface IGoo");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WithinNameOf()
{
var markup = @"
class C
{
void goo()
{
var x = nameof($$)
}
}
";
await VerifyAnyItemExistsAsync(markup);
}
[WorkItem(997410, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/997410")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMemberInNameOfInStaticContext()
{
var markup = @"
class C
{
int y1 = 15;
static int y2 = 1;
static string x = nameof($$
";
await VerifyItemExistsAsync(markup, "y1");
}
[WorkItem(997410, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/997410")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticMemberInNameOfInStaticContext()
{
var markup = @"
class C
{
int y1 = 15;
static int y2 = 1;
static string x = nameof($$
";
await VerifyItemExistsAsync(markup, "y2");
}
[WorkItem(883293, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/883293")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task IncompleteDeclarationExpressionType()
{
var markup = @"
using System;
class C
{
void goo()
{
var x = Console.$$
var y = 3;
}
}
";
await VerifyItemExistsAsync(markup, "WriteLine");
}
[WorkItem(1024380, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024380")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticAndInstanceInNameOf()
{
var markup = @"
using System;
class C
{
class D
{
public int x;
public static int y;
}
void goo()
{
var z = nameof(C.D.$$
}
}
";
await VerifyItemExistsAsync(markup, "x");
await VerifyItemExistsAsync(markup, "y");
}
[WorkItem(1663, "https://github.com/dotnet/roslyn/issues/1663")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NameOfMembersListedForLocals()
{
var markup = @"class C
{
void M()
{
var x = nameof(T.z.$$)
}
}
public class T
{
public U z;
}
public class U
{
public int nope;
}
";
await VerifyItemExistsAsync(markup, "nope");
}
[WorkItem(1029522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029522")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NameOfMembersListedForNamespacesAndTypes2()
{
var markup = @"class C
{
void M()
{
var x = nameof(U.$$)
}
}
public class T
{
public U z;
}
public class U
{
public int nope;
}
";
await VerifyItemExistsAsync(markup, "nope");
}
[WorkItem(1029522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029522")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NameOfMembersListedForNamespacesAndTypes3()
{
var markup = @"class C
{
void M()
{
var x = nameof(N.$$)
}
}
namespace N
{
public class U
{
public int nope;
}
} ";
await VerifyItemExistsAsync(markup, "U");
}
[WorkItem(1029522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029522")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NameOfMembersListedForNamespacesAndTypes4()
{
var markup = @"
using z = System;
class C
{
void M()
{
var x = nameof(z.$$)
}
}
";
await VerifyItemExistsAsync(markup, "Console");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InterpolatedStrings1()
{
var markup = @"
class C
{
void M()
{
var a = ""Hello"";
var b = ""World"";
var c = $""{$$
";
await VerifyItemExistsAsync(markup, "a");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InterpolatedStrings2()
{
var markup = @"
class C
{
void M()
{
var a = ""Hello"";
var b = ""World"";
var c = $""{$$}"";
}
}";
await VerifyItemExistsAsync(markup, "a");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InterpolatedStrings3()
{
var markup = @"
class C
{
void M()
{
var a = ""Hello"";
var b = ""World"";
var c = $""{a}, {$$
";
await VerifyItemExistsAsync(markup, "b");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InterpolatedStrings4()
{
var markup = @"
class C
{
void M()
{
var a = ""Hello"";
var b = ""World"";
var c = $""{a}, {$$}"";
}
}";
await VerifyItemExistsAsync(markup, "b");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InterpolatedStrings5()
{
var markup = @"
class C
{
void M()
{
var a = ""Hello"";
var b = ""World"";
var c = $@""{a}, {$$
";
await VerifyItemExistsAsync(markup, "b");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InterpolatedStrings6()
{
var markup = @"
class C
{
void M()
{
var a = ""Hello"";
var b = ""World"";
var c = $@""{a}, {$$}"";
}
}";
await VerifyItemExistsAsync(markup, "b");
}
[WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotBeforeFirstStringHole()
{
await VerifyNoItemsExistAsync(AddInsideMethod(
@"var x = ""\{0}$$\{1}\{2}"""));
}
[WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotBetweenStringHoles()
{
await VerifyNoItemsExistAsync(AddInsideMethod(
@"var x = ""\{0}\{1}$$\{2}"""));
}
[WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotAfterStringHoles()
{
await VerifyNoItemsExistAsync(AddInsideMethod(
@"var x = ""\{0}\{1}\{2}$$"""));
}
[WorkItem(1087171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087171")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task CompletionAfterTypeOfGetType()
{
await VerifyItemExistsAsync(AddInsideMethod(
"typeof(int).GetType().$$"), "GUID");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingDirectives1()
{
var markup = @"
using $$
class A { }
static class B { }
namespace N
{
class C { }
static class D { }
namespace M { }
}";
await VerifyItemIsAbsentAsync(markup, "A");
await VerifyItemIsAbsentAsync(markup, "B");
await VerifyItemExistsAsync(markup, "N");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingDirectives2()
{
var markup = @"
using N.$$
class A { }
static class B { }
namespace N
{
class C { }
static class D { }
namespace M { }
}";
await VerifyItemIsAbsentAsync(markup, "C");
await VerifyItemIsAbsentAsync(markup, "D");
await VerifyItemExistsAsync(markup, "M");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingDirectives3()
{
var markup = @"
using G = $$
class A { }
static class B { }
namespace N
{
class C { }
static class D { }
namespace M { }
}";
await VerifyItemExistsAsync(markup, "A");
await VerifyItemExistsAsync(markup, "B");
await VerifyItemExistsAsync(markup, "N");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingDirectives4()
{
var markup = @"
using G = N.$$
class A { }
static class B { }
namespace N
{
class C { }
static class D { }
namespace M { }
}";
await VerifyItemExistsAsync(markup, "C");
await VerifyItemExistsAsync(markup, "D");
await VerifyItemExistsAsync(markup, "M");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingDirectives5()
{
var markup = @"
using static $$
class A { }
static class B { }
namespace N
{
class C { }
static class D { }
namespace M { }
}";
await VerifyItemExistsAsync(markup, "A");
await VerifyItemExistsAsync(markup, "B");
await VerifyItemExistsAsync(markup, "N");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingDirectives6()
{
var markup = @"
using static N.$$
class A { }
static class B { }
namespace N
{
class C { }
static class D { }
namespace M { }
}";
await VerifyItemExistsAsync(markup, "C");
await VerifyItemExistsAsync(markup, "D");
await VerifyItemExistsAsync(markup, "M");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticDoesNotShowDelegates1()
{
var markup = @"
using static $$
class A { }
delegate void B();
namespace N
{
class C { }
static class D { }
namespace M { }
}";
await VerifyItemExistsAsync(markup, "A");
await VerifyItemIsAbsentAsync(markup, "B");
await VerifyItemExistsAsync(markup, "N");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticDoesNotShowDelegates2()
{
var markup = @"
using static N.$$
class A { }
static class B { }
namespace N
{
class C { }
delegate void D();
namespace M { }
}";
await VerifyItemExistsAsync(markup, "C");
await VerifyItemIsAbsentAsync(markup, "D");
await VerifyItemExistsAsync(markup, "M");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticDoesNotShowInterfaces1()
{
var markup = @"
using static N.$$
class A { }
static class B { }
namespace N
{
class C { }
interface I { }
namespace M { }
}";
await VerifyItemExistsAsync(markup, "C");
await VerifyItemIsAbsentAsync(markup, "I");
await VerifyItemExistsAsync(markup, "M");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticDoesNotShowInterfaces2()
{
var markup = @"
using static $$
class A { }
interface I { }
namespace N
{
class C { }
static class D { }
namespace M { }
}";
await VerifyItemExistsAsync(markup, "A");
await VerifyItemIsAbsentAsync(markup, "I");
await VerifyItemExistsAsync(markup, "N");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticAndExtensionMethods1()
{
var markup = @"
using static A;
using static B;
static class A
{
public static void Goo(this string s) { }
}
static class B
{
public static void Bar(this string s) { }
}
class C
{
void M()
{
$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Goo");
await VerifyItemIsAbsentAsync(markup, "Bar");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticAndExtensionMethods2()
{
var markup = @"
using N;
namespace N
{
static class A
{
public static void Goo(this string s) { }
}
static class B
{
public static void Bar(this string s) { }
}
}
class C
{
void M()
{
$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Goo");
await VerifyItemIsAbsentAsync(markup, "Bar");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticAndExtensionMethods3()
{
var markup = @"
using N;
namespace N
{
static class A
{
public static void Goo(this string s) { }
}
static class B
{
public static void Bar(this string s) { }
}
}
class C
{
void M()
{
string s;
s.$$
}
}
";
await VerifyItemExistsAsync(markup, "Goo");
await VerifyItemExistsAsync(markup, "Bar");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticAndExtensionMethods4()
{
var markup = @"
using static N.A;
using static N.B;
namespace N
{
static class A
{
public static void Goo(this string s) { }
}
static class B
{
public static void Bar(this string s) { }
}
}
class C
{
void M()
{
string s;
s.$$
}
}
";
await VerifyItemExistsAsync(markup, "Goo");
await VerifyItemExistsAsync(markup, "Bar");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticAndExtensionMethods5()
{
var markup = @"
using static N.A;
namespace N
{
static class A
{
public static void Goo(this string s) { }
}
static class B
{
public static void Bar(this string s) { }
}
}
class C
{
void M()
{
string s;
s.$$
}
}
";
await VerifyItemExistsAsync(markup, "Goo");
await VerifyItemIsAbsentAsync(markup, "Bar");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticAndExtensionMethods6()
{
var markup = @"
using static N.B;
namespace N
{
static class A
{
public static void Goo(this string s) { }
}
static class B
{
public static void Bar(this string s) { }
}
}
class C
{
void M()
{
string s;
s.$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Goo");
await VerifyItemExistsAsync(markup, "Bar");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticAndExtensionMethods7()
{
var markup = @"
using N;
using static N.B;
namespace N
{
static class A
{
public static void Goo(this string s) { }
}
static class B
{
public static void Bar(this string s) { }
}
}
class C
{
void M()
{
string s;
s.$$;
}
}
";
await VerifyItemExistsAsync(markup, "Goo");
await VerifyItemExistsAsync(markup, "Bar");
}
[WorkItem(7932, "https://github.com/dotnet/roslyn/issues/7932")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExtensionMethodWithinSameClassOfferedForCompletion()
{
var markup = @"
public static class Test
{
static void TestB()
{
$$
}
static void TestA(this string s) { }
}
";
await VerifyItemExistsAsync(markup, "TestA");
}
[WorkItem(7932, "https://github.com/dotnet/roslyn/issues/7932")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExtensionMethodWithinParentClassOfferedForCompletion()
{
var markup = @"
public static class Parent
{
static void TestA(this string s) { }
static void TestC(string s) { }
public static class Test
{
static void TestB()
{
$$
}
}
}
";
await VerifyItemExistsAsync(markup, "TestA");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExceptionFilter1()
{
var markup = @"
using System;
class C
{
void M(bool x)
{
try
{
}
catch when ($$
";
await VerifyItemExistsAsync(markup, "x");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExceptionFilter1_NotBeforeOpenParen()
{
var markup = @"
using System;
class C
{
void M(bool x)
{
try
{
}
catch when $$
";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExceptionFilter2()
{
var markup = @"
using System;
class C
{
void M(bool x)
{
try
{
}
catch (Exception ex) when ($$
";
await VerifyItemExistsAsync(markup, "x");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExceptionFilter2_NotBeforeOpenParen()
{
var markup = @"
using System;
class C
{
void M(bool x)
{
try
{
}
catch (Exception ex) when $$
";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(25084, "https://github.com/dotnet/roslyn/issues/25084")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SwitchCaseWhenClause1()
{
var markup = @"
class C
{
void M(bool x)
{
switch (1)
{
case 1 when $$
";
await VerifyItemExistsAsync(markup, "x");
}
[WorkItem(25084, "https://github.com/dotnet/roslyn/issues/25084")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SwitchCaseWhenClause2()
{
var markup = @"
class C
{
void M(bool x)
{
switch (1)
{
case int i when $$
";
await VerifyItemExistsAsync(markup, "x");
}
[WorkItem(717, "https://github.com/dotnet/roslyn/issues/717")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExpressionContextCompletionWithinCast()
{
var markup = @"
class Program
{
void M()
{
for (int i = 0; i < 5; i++)
{
var x = ($$)
var y = 1;
}
}
}
";
await VerifyItemExistsAsync(markup, "i");
}
[WorkItem(1277, "https://github.com/dotnet/roslyn/issues/1277")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceMembersInPropertyInitializer()
{
var markup = @"
class A {
int abc;
int B { get; } = $$
}
";
await VerifyItemIsAbsentAsync(markup, "abc");
}
[WorkItem(1277, "https://github.com/dotnet/roslyn/issues/1277")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticMembersInPropertyInitializer()
{
var markup = @"
class A {
static Action s_abc;
event Action B = $$
}
";
await VerifyItemExistsAsync(markup, "s_abc");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceMembersInFieldLikeEventInitializer()
{
var markup = @"
class A {
Action abc;
event Action B = $$
}
";
await VerifyItemIsAbsentAsync(markup, "abc");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticMembersInFieldLikeEventInitializer()
{
var markup = @"
class A {
static Action s_abc;
event Action B = $$
}
";
await VerifyItemExistsAsync(markup, "s_abc");
}
[WorkItem(5069, "https://github.com/dotnet/roslyn/issues/5069")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMembersInTopLevelFieldInitializer()
{
var markup = @"
int aaa = 1;
int bbb = $$
";
await VerifyItemExistsAsync(markup, "aaa", sourceCodeKind: SourceCodeKind.Script);
}
[WorkItem(5069, "https://github.com/dotnet/roslyn/issues/5069")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMembersInTopLevelFieldLikeEventInitializer()
{
var markup = @"
Action aaa = null;
event Action bbb = $$
";
await VerifyItemExistsAsync(markup, "aaa", sourceCodeKind: SourceCodeKind.Script);
}
[WorkItem(33, "https://github.com/dotnet/roslyn/issues/33")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoConditionalAccessCompletionOnTypes1()
{
var markup = @"
using A = System
class C
{
A?.$$
}
";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(33, "https://github.com/dotnet/roslyn/issues/33")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoConditionalAccessCompletionOnTypes2()
{
var markup = @"
class C
{
System?.$$
}
";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(33, "https://github.com/dotnet/roslyn/issues/33")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoConditionalAccessCompletionOnTypes3()
{
var markup = @"
class C
{
System.Console?.$$
}
";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionInIncompletePropertyDeclaration()
{
var markup = @"
class Class1
{
public string Property1 { get; set; }
}
class Class2
{
public string Property { get { return this.Source.$$
public Class1 Source { get; set; }
}";
await VerifyItemExistsAsync(markup, "Property1");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoCompletionInShebangComments()
{
await VerifyNoItemsExistAsync("#!$$", sourceCodeKind: SourceCodeKind.Script);
await VerifyNoItemsExistAsync("#! S$$", sourceCodeKind: SourceCodeKind.Script, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompoundNameTargetTypePreselection()
{
var markup = @"
class Class1
{
void goo()
{
int x = 3;
string y = x.$$
}
}";
await VerifyItemExistsAsync(markup, "ToString", matchPriority: SymbolMatchPriority.PreferEventOrMethod);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TargetTypeInCollectionInitializer1()
{
var markup = @"
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
int z;
string q;
List<int> x = new List<int>() { $$ }
}
}";
await VerifyItemExistsAsync(markup, "z", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TargetTypeInCollectionInitializer2()
{
var markup = @"
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
int z;
string q;
List<int> x = new List<int>() { 1, $$ }
}
}";
await VerifyItemExistsAsync(markup, "z", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TargeTypeInObjectInitializer1()
{
var markup = @"
class C
{
public int X { get; set; }
public int Y { get; set; }
void goo()
{
int i;
var c = new C() { X = $$ }
}
}";
await VerifyItemExistsAsync(markup, "i", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TargeTypeInObjectInitializer2()
{
var markup = @"
class C
{
public int X { get; set; }
public int Y { get; set; }
void goo()
{
int i;
var c = new C() { X = 1, Y = $$ }
}
}";
await VerifyItemExistsAsync(markup, "i", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleElements()
{
var markup = @"
class C
{
void goo()
{
var t = (Alice: 1, Item2: 2, ITEM3: 3, 4, 5, 6, 7, 8, Bob: 9);
t.$$
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs;
await VerifyItemExistsAsync(markup, "Alice");
await VerifyItemExistsAsync(markup, "Bob");
await VerifyItemExistsAsync(markup, "CompareTo");
await VerifyItemExistsAsync(markup, "Equals");
await VerifyItemExistsAsync(markup, "GetHashCode");
await VerifyItemExistsAsync(markup, "GetType");
await VerifyItemExistsAsync(markup, "Item2");
await VerifyItemExistsAsync(markup, "ITEM3");
for (var i = 4; i <= 8; i++)
{
await VerifyItemExistsAsync(markup, "Item" + i);
}
await VerifyItemExistsAsync(markup, "ToString");
await VerifyItemIsAbsentAsync(markup, "Item1");
await VerifyItemIsAbsentAsync(markup, "Item9");
await VerifyItemIsAbsentAsync(markup, "Rest");
await VerifyItemIsAbsentAsync(markup, "Item3");
}
[WorkItem(14546, "https://github.com/dotnet/roslyn/issues/14546")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleElementsCompletionOffMethodGroup()
{
var markup = @"
class C
{
void goo()
{
new object().ToString.$$
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs;
// should not crash
await VerifyNoItemsExistAsync(markup);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.Completion)]
[CompilerTrait(CompilerFeature.LocalFunctions)]
[WorkItem(13480, "https://github.com/dotnet/roslyn/issues/13480")]
public async Task NoCompletionInLocalFuncGenericParamList()
{
var markup = @"
class C
{
void M()
{
int Local<$$";
await VerifyNoItemsExistAsync(markup);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.Completion)]
[CompilerTrait(CompilerFeature.LocalFunctions)]
[WorkItem(13480, "https://github.com/dotnet/roslyn/issues/13480")]
public async Task CompletionForAwaitWithoutAsync()
{
var markup = @"
class C
{
void M()
{
await Local<$$";
await VerifyAnyItemExistsAsync(markup);
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleTypeAtMemberLevel1()
{
await VerifyItemExistsAsync(@"
class C
{
($$
}", "C");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleTypeAtMemberLevel2()
{
await VerifyItemExistsAsync(@"
class C
{
($$)
}", "C");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleTypeAtMemberLevel3()
{
await VerifyItemExistsAsync(@"
class C
{
(C, $$
}", "C");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleTypeAtMemberLevel4()
{
await VerifyItemExistsAsync(@"
class C
{
(C, $$)
}", "C");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleTypeInForeach()
{
await VerifyItemExistsAsync(@"
class C
{
void M()
{
foreach ((C, $$
}
}", "C");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleTypeInParameterList()
{
await VerifyItemExistsAsync(@"
class C
{
void M((C, $$)
{
}
}", "C");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleTypeInNameOf()
{
await VerifyItemExistsAsync(@"
class C
{
void M()
{
var x = nameof((C, $$
}
}", "C");
}
[WorkItem(14163, "https://github.com/dotnet/roslyn/issues/14163")]
[Fact]
[Trait(Traits.Feature, Traits.Features.Completion)]
[CompilerTrait(CompilerFeature.LocalFunctions)]
public async Task LocalFunctionDescription()
{
await VerifyItemExistsAsync(@"
class C
{
void M()
{
void Local() { }
$$
}
}", "Local", "void Local()");
}
[WorkItem(14163, "https://github.com/dotnet/roslyn/issues/14163")]
[Fact]
[Trait(Traits.Feature, Traits.Features.Completion)]
[CompilerTrait(CompilerFeature.LocalFunctions)]
public async Task LocalFunctionDescription2()
{
await VerifyItemExistsAsync(@"
using System;
class C
{
class var { }
void M()
{
Action<int> Local(string x, ref var @class, params Func<int, string> f)
{
return () => 0;
}
$$
}
}", "Local", "Action<int> Local(string x, ref var @class, params Func<int, string> f)");
}
[WorkItem(18359, "https://github.com/dotnet/roslyn/issues/18359")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EnumMemberAfterDot()
{
var markup =
@"namespace ConsoleApplication253
{
class Program
{
static void Main(string[] args)
{
M(E.$$)
}
static void M(E e) { }
}
enum E
{
A,
B,
}
}
";
// VerifyItemExistsAsync also tests with the item typed.
await VerifyItemExistsAsync(markup, "A");
await VerifyItemExistsAsync(markup, "B");
}
[WorkItem(8321, "https://github.com/dotnet/roslyn/issues/8321")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotOnMethodGroup1()
{
var markup =
@"namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
Main.$$
}
}
}
";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(8321, "https://github.com/dotnet/roslyn/issues/8321")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotOnMethodGroup2()
{
var markup =
@"class C {
void M<T>() {M<C>.$$ }
}
";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(8321, "https://github.com/dotnet/roslyn/issues/8321")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotOnMethodGroup3()
{
var markup =
@"class C {
void M() {M.$$}
}
";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(420697, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=420697&_a=edit")]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/21766"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task DoNotCrashInExtensionMethoWithExpressionBodiedMember()
{
var markup =
@"public static class Extensions { public static T Get<T>(this object o) => $$}
";
await VerifyItemExistsAsync(markup, "o");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task EnumConstraint()
{
var markup =
@"public class X<T> where T : System.$$
";
await VerifyItemExistsAsync(markup, "Enum");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task DelegateConstraint()
{
var markup =
@"public class X<T> where T : System.$$
";
await VerifyItemExistsAsync(markup, "Delegate");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task MulticastDelegateConstraint()
{
var markup =
@"public class X<T> where T : System.$$
";
await VerifyItemExistsAsync(markup, "MulticastDelegate");
}
private static string CreateThenIncludeTestCode(string lambdaExpressionString, string methodDeclarationString)
{
var template = @"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace ThenIncludeIntellisenseBug
{
class Program
{
static void Main(string[] args)
{
var registrations = new List<Registration>().AsQueryable();
var reg = registrations.Include(r => r.Activities).ThenInclude([1]);
}
}
internal class Registration
{
public ICollection<Activity> Activities { get; set; }
}
public class Activity
{
public Task Task { get; set; }
}
public class Task
{
public string Name { get; set; }
}
public interface IIncludableQueryable<out TEntity, out TProperty> : IQueryable<TEntity>
{
}
public static class EntityFrameworkQuerybleExtensions
{
public static IIncludableQueryable<TEntity, TProperty> Include<TEntity, TProperty>(
this IQueryable<TEntity> source,
Expression<Func<TEntity, TProperty>> navigationPropertyPath)
where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
[2]
}
}";
return template.Replace("[1]", lambdaExpressionString).Replace("[2]", methodDeclarationString);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThenInclude()
{
var markup = CreateThenIncludeTestCode("b => b.$$",
@"
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source,
Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, TPreviousProperty> source,
Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}");
await VerifyItemExistsAsync(markup, "Task");
await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThenIncludeNoExpression()
{
var markup = CreateThenIncludeTestCode("b => b.$$",
@"
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source,
Func<TPreviousProperty, TProperty> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, TPreviousProperty> source,
Func<TPreviousProperty, TProperty> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}");
await VerifyItemExistsAsync(markup, "Task");
await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThenIncludeSecondArgument()
{
var markup = CreateThenIncludeTestCode("0, b => b.$$",
@"
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source,
int a,
Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, TPreviousProperty> source,
int a,
Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}");
await VerifyItemExistsAsync(markup, "Task");
await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThenIncludeSecondArgumentAndMultiArgumentLambda()
{
var markup = CreateThenIncludeTestCode("0, (a,b,c) => c.$$)",
@"
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source,
int a,
Expression<Func<string, string, TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, TPreviousProperty> source,
int a,
Expression<Func<string, string, TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}");
await VerifyItemExistsAsync(markup, "Task");
await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThenIncludeSecondArgumentNoOverlap()
{
var markup = CreateThenIncludeTestCode("b => b.Task, b =>b.$$",
@"
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source,
Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath,
Expression<Func<TPreviousProperty, TProperty>> anotherNavigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, TPreviousProperty> source,
Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
");
await VerifyItemExistsAsync(markup, "Task");
await VerifyItemIsAbsentAsync(markup, "FirstOrDefault", displayTextSuffix: "<>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThenIncludeSecondArgumentAndMultiArgumentLambdaWithNoLambdaOverlap()
{
var markup = CreateThenIncludeTestCode("0, (a,b,c) => c.$$",
@"
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source,
int a,
Expression<Func<string, TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, TPreviousProperty> source,
int a,
Expression<Func<string, string, TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
");
await VerifyItemIsAbsentAsync(markup, "Task");
await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>");
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/35100"), Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThenIncludeGenericAndNoGenericOverloads()
{
var markup = CreateThenIncludeTestCode("c => c.$$",
@"
public static IIncludableQueryable<Registration, Task> ThenInclude(
this IIncludableQueryable<Registration, ICollection<Activity>> source,
Func<Activity, Task> navigationPropertyPath)
{
return default(IIncludableQueryable<Registration, Task>);
}
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, TPreviousProperty> source,
Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
");
await VerifyItemExistsAsync(markup, "Task");
await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThenIncludeNoGenericOverloads()
{
var markup = CreateThenIncludeTestCode("c => c.$$",
@"
public static IIncludableQueryable<Registration, Task> ThenInclude(
this IIncludableQueryable<Registration, ICollection<Activity>> source,
Func<Activity, Task> navigationPropertyPath)
{
return default(IIncludableQueryable<Registration, Task>);
}
public static IIncludableQueryable<Registration, Activity> ThenInclude(
this IIncludableQueryable<Registration, ICollection<Activity>> source,
Func<ICollection<Activity>, Activity> navigationPropertyPath)
{
return default(IIncludableQueryable<Registration, Activity>);
}
");
await VerifyItemExistsAsync(markup, "Task");
await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionForLambdaWithOverloads()
{
var markup = @"
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace ClassLibrary1
{
class SomeItem
{
public string A;
public int B;
}
class SomeCollection<T> : List<T>
{
public virtual SomeCollection<T> Include(string path) => null;
}
static class Extensions
{
public static IList<T> Include<T, TProperty>(this IList<T> source, Expression<Func<T, TProperty>> path)
=> null;
public static IList Include(this IList source, string path) => null;
public static IList<T> Include<T>(this IList<T> source, string path) => null;
}
class Program
{
void M(SomeCollection<SomeItem> c)
{
var a = from m in c.Include(t => t.$$);
}
}
}";
await VerifyItemIsAbsentAsync(markup, "Substring");
await VerifyItemExistsAsync(markup, "A");
await VerifyItemExistsAsync(markup, "B");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(1056325, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056325")]
public async Task CompletionForLambdaWithOverloads2()
{
var markup = @"
using System;
class C
{
void M(Action<int> a) { }
void M(string s) { }
void Test()
{
M(p => p.$$);
}
}";
await VerifyItemIsAbsentAsync(markup, "Substring");
await VerifyItemExistsAsync(markup, "GetTypeCode");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(1056325, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056325")]
public async Task CompletionForLambdaWithOverloads3()
{
var markup = @"
using System;
class C
{
void M(Action<int> a) { }
void M(Action<string> a) { }
void Test()
{
M((int p) => p.$$);
}
}";
await VerifyItemIsAbsentAsync(markup, "Substring");
await VerifyItemExistsAsync(markup, "GetTypeCode");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(1056325, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056325")]
public async Task CompletionForLambdaWithOverloads4()
{
var markup = @"
using System;
class C
{
void M(Action<int> a) { }
void M(Action<string> a) { }
void Test()
{
M(p => p.$$);
}
}";
await VerifyItemExistsAsync(markup, "Substring");
await VerifyItemExistsAsync(markup, "GetTypeCode");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")]
public async Task CompletionForLambdaWithTypeParameters()
{
var markup = @"
using System;
using System.Collections.Generic;
class Program
{
static void M()
{
Create(new List<Product>(), arg => arg.$$);
}
static void Create<T>(List<T> list, Action<T> expression) { }
}
class Product { public void MyProperty() { } }";
await VerifyItemExistsAsync(markup, "MyProperty");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")]
public async Task CompletionForLambdaWithTypeParametersAndOverloads()
{
var markup = @"
using System;
using System.Collections.Generic;
class Program
{
static void M()
{
Create(new Dictionary<Product1, Product2>(), arg => arg.$$);
}
static void Create<T, U>(Dictionary<T, U> list, Action<T> expression) { }
static void Create<T, U>(Dictionary<U, T> list, Action<T> expression) { }
}
class Product1 { public void MyProperty1() { } }
class Product2 { public void MyProperty2() { } }";
await VerifyItemExistsAsync(markup, "MyProperty1");
await VerifyItemExistsAsync(markup, "MyProperty2");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")]
public async Task CompletionForLambdaWithTypeParametersAndOverloads2()
{
var markup = @"
using System;
using System.Collections.Generic;
class Program
{
static void M()
{
Create(new Dictionary<Product1,Product2>(),arg => arg.$$);
}
static void Create<T, U>(Dictionary<T, U> list, Action<T> expression) { }
static void Create<T, U>(Dictionary<U, T> list, Action<T> expression) { }
static void Create(Dictionary<Product1, Product2> list, Action<Product3> expression) { }
}
class Product1 { public void MyProperty1() { } }
class Product2 { public void MyProperty2() { } }
class Product3 { public void MyProperty3() { } }";
await VerifyItemExistsAsync(markup, "MyProperty1");
await VerifyItemExistsAsync(markup, "MyProperty2");
await VerifyItemExistsAsync(markup, "MyProperty3");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")]
public async Task CompletionForLambdaWithTypeParametersFromClass()
{
var markup = @"
using System;
class Program<T>
{
static void M()
{
Create(arg => arg.$$);
}
static void Create(Action<T> expression) { }
}
class Product { public void MyProperty() { } }";
await VerifyItemExistsAsync(markup, "GetHashCode");
await VerifyItemIsAbsentAsync(markup, "MyProperty");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")]
public async Task CompletionForLambdaWithTypeParametersFromClassWithConstraintOnType()
{
var markup = @"
using System;
class Program<T> where T : Product
{
static void M()
{
Create(arg => arg.$$);
}
static void Create(Action<T> expression) { }
}
class Product { public void MyProperty() { } }";
await VerifyItemExistsAsync(markup, "GetHashCode");
await VerifyItemExistsAsync(markup, "MyProperty");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")]
public async Task CompletionForLambdaWithTypeParametersFromClassWithConstraintOnMethod()
{
var markup = @"
using System;
class Program
{
static void M()
{
Create(arg => arg.$$);
}
static void Create<T>(Action<T> expression) where T : Product { }
}
class Product { public void MyProperty() { } }";
await VerifyItemExistsAsync(markup, "GetHashCode");
await VerifyItemExistsAsync(markup, "MyProperty");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(40216, "https://github.com/dotnet/roslyn/issues/40216")]
public async Task CompletionForLambdaPassedAsNamedArgumentAtDifferentPositionFromCorrespondingParameter1()
{
var markup = @"
using System;
class C
{
void Test()
{
X(y: t => Console.WriteLine(t.$$));
}
void X(int x = 7, Action<string> y = null) { }
}
";
await VerifyItemExistsAsync(markup, "Length");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(40216, "https://github.com/dotnet/roslyn/issues/40216")]
public async Task CompletionForLambdaPassedAsNamedArgumentAtDifferentPositionFromCorrespondingParameter2()
{
var markup = @"
using System;
class C
{
void Test()
{
X(y: t => Console.WriteLine(t.$$));
}
void X(int x, int z, Action<string> y) { }
}
";
await VerifyItemExistsAsync(markup, "Length");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionForLambdaPassedAsArgumentInReducedExtensionMethod_NonInteractive()
{
var markup = @"
using System;
static class CExtensions
{
public static void X(this C x, Action<string> y) { }
}
class C
{
void Test()
{
new C().X(t => Console.WriteLine(t.$$));
}
}
";
await VerifyItemExistsAsync(markup, "Length", sourceCodeKind: SourceCodeKind.Regular);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionForLambdaPassedAsArgumentInReducedExtensionMethod_Interactive()
{
var markup = @"
using System;
public static void X(this C x, Action<string> y) { }
public class C
{
void Test()
{
new C().X(t => Console.WriteLine(t.$$));
}
}
";
await VerifyItemExistsAsync(markup, "Length", sourceCodeKind: SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionInsideMethodsWithNonFunctionsAsArguments()
{
var markup = @"
using System;
class c
{
void M()
{
Goo(builder =>
{
builder.$$
});
}
void Goo(Action<Builder> configure)
{
var builder = new Builder();
configure(builder);
}
}
class Builder
{
public int Something { get; set; }
}";
await VerifyItemExistsAsync(markup, "Something");
await VerifyItemIsAbsentAsync(markup, "BeginInvoke");
await VerifyItemIsAbsentAsync(markup, "Clone");
await VerifyItemIsAbsentAsync(markup, "Method");
await VerifyItemIsAbsentAsync(markup, "Target");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionInsideMethodsWithDelegatesAsArguments()
{
var markup = @"
using System;
class Program
{
public delegate void Delegate1(Uri u);
public delegate void Delegate2(Guid g);
public void M(Delegate1 d) { }
public void M(Delegate2 d) { }
public void Test()
{
M(d => d.$$)
}
}";
// Guid
await VerifyItemExistsAsync(markup, "ToByteArray");
// Uri
await VerifyItemExistsAsync(markup, "AbsoluteUri");
await VerifyItemExistsAsync(markup, "Fragment");
await VerifyItemExistsAsync(markup, "Query");
// Should not appear for Delegate
await VerifyItemIsAbsentAsync(markup, "BeginInvoke");
await VerifyItemIsAbsentAsync(markup, "Clone");
await VerifyItemIsAbsentAsync(markup, "Method");
await VerifyItemIsAbsentAsync(markup, "Target");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionInsideMethodsWithDelegatesAndReversingArguments()
{
var markup = @"
using System;
class Program
{
public delegate void Delegate1<T1,T2>(T2 t2, T1 t1);
public delegate void Delegate2<T1,T2>(T2 t2, int g, T1 t1);
public void M(Delegate1<Uri,Guid> d) { }
public void M(Delegate2<Uri,Guid> d) { }
public void Test()
{
M(d => d.$$)
}
}";
// Guid
await VerifyItemExistsAsync(markup, "ToByteArray");
// Should not appear for Uri
await VerifyItemIsAbsentAsync(markup, "AbsoluteUri");
await VerifyItemIsAbsentAsync(markup, "Fragment");
await VerifyItemIsAbsentAsync(markup, "Query");
// Should not appear for Delegate
await VerifyItemIsAbsentAsync(markup, "BeginInvoke");
await VerifyItemIsAbsentAsync(markup, "Clone");
await VerifyItemIsAbsentAsync(markup, "Method");
await VerifyItemIsAbsentAsync(markup, "Target");
}
[WorkItem(36029, "https://github.com/dotnet/roslyn/issues/36029")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionInsideMethodWithParamsBeforeParams()
{
var markup = @"
using System;
class C
{
void M()
{
Goo(builder =>
{
builder.$$
});
}
void Goo(Action<Builder> action, params Action<AnotherBuilder>[] otherActions)
{
}
}
class Builder
{
public int Something { get; set; }
};
class AnotherBuilder
{
public int AnotherSomething { get; set; }
}";
await VerifyItemIsAbsentAsync(markup, "AnotherSomething");
await VerifyItemIsAbsentAsync(markup, "FirstOrDefault");
await VerifyItemExistsAsync(markup, "Something");
}
[WorkItem(36029, "https://github.com/dotnet/roslyn/issues/36029")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionInsideMethodWithParamsInParams()
{
var markup = @"
using System;
class C
{
void M()
{
Goo(b0 => { }, b1 => {}, b2 => { b2.$$ });
}
void Goo(Action<Builder> action, params Action<AnotherBuilder>[] otherActions)
{
}
}
class Builder
{
public int Something { get; set; }
};
class AnotherBuilder
{
public int AnotherSomething { get; set; }
}";
await VerifyItemIsAbsentAsync(markup, "Something");
await VerifyItemIsAbsentAsync(markup, "FirstOrDefault");
await VerifyItemExistsAsync(markup, "AnotherSomething");
}
[Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)]
public async Task TestTargetTypeFilterWithExperimentEnabled()
{
SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, true);
var markup =
@"public class C
{
int intField;
void M(int x)
{
M($$);
}
}";
await VerifyItemExistsAsync(
markup, "intField",
matchingFilters: new List<CompletionFilter> { FilterSet.FieldFilter, FilterSet.TargetTypedFilter });
}
[Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)]
public async Task TestNoTargetTypeFilterWithExperimentDisabled()
{
SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, false);
var markup =
@"public class C
{
int intField;
void M(int x)
{
M($$);
}
}";
await VerifyItemExistsAsync(
markup, "intField",
matchingFilters: new List<CompletionFilter> { FilterSet.FieldFilter });
}
[Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)]
public async Task TestTargetTypeFilter_NotOnObjectMembers()
{
SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, true);
var markup =
@"public class C
{
void M(int x)
{
M($$);
}
}";
await VerifyItemExistsAsync(
markup, "GetHashCode",
matchingFilters: new List<CompletionFilter> { FilterSet.MethodFilter });
}
[Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)]
public async Task TestTargetTypeFilter_NotNamedTypes()
{
SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, true);
var markup =
@"public class C
{
void M(C c)
{
M($$);
}
}";
await VerifyItemExistsAsync(
markup, "c",
matchingFilters: new List<CompletionFilter> { FilterSet.LocalAndParameterFilter, FilterSet.TargetTypedFilter });
await VerifyItemExistsAsync(
markup, "C",
matchingFilters: new List<CompletionFilter> { FilterSet.ClassFilter });
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionShouldNotProvideExtensionMethodsIfTypeConstraintDoesNotMatch()
{
var markup = @"
public static class Ext
{
public static void DoSomething<T>(this T thing, string s) where T : class, I
{
}
}
public interface I
{
}
public class C
{
public void M(string s)
{
this.$$
}
}";
await VerifyItemExistsAsync(markup, "M");
await VerifyItemExistsAsync(markup, "Equals");
await VerifyItemIsAbsentAsync(markup, "DoSomething", displayTextSuffix: "<>");
}
[WorkItem(38074, "https://github.com/dotnet/roslyn/issues/38074")]
[Fact]
[Trait(Traits.Feature, Traits.Features.Completion)]
[CompilerTrait(CompilerFeature.LocalFunctions)]
public async Task LocalFunctionInStaticMethod()
{
await VerifyItemExistsAsync(@"
class C
{
static void M()
{
void Local() { }
$$
}
}", "Local");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(1152109, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1152109")]
public async Task NoItemWithEmptyDisplayName()
{
var markup = @"
class C
{
static void M()
{
int$$
}
}
";
await VerifyItemIsAbsentAsync(
markup, "",
matchingFilters: new List<CompletionFilter> { FilterSet.LocalAndParameterFilter });
}
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData('.')]
[InlineData(';')]
public async Task CompletionWithCustomizedCommitCharForMethod(char commitChar)
{
var markup = @"
class Program
{
private void Bar()
{
F$$
}
private void Foo(int i)
{
}
private void Foo(int i, int c)
{
}
}";
var expected = $@"
class Program
{{
private void Bar()
{{
Foo(){commitChar}
}}
private void Foo(int i)
{{
}}
private void Foo(int i, int c)
{{
}}
}}";
await VerifyProviderCommitAsync(markup, "Foo", expected, commitChar: commitChar);
}
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData('.')]
[InlineData(';')]
public async Task CompletionWithSemicolonInNestedMethod(char commitChar)
{
var markup = @"
class Program
{
private void Bar()
{
Foo(F$$);
}
private int Foo(int i)
{
return 1;
}
}";
var expected = $@"
class Program
{{
private void Bar()
{{
Foo(Foo(){commitChar});
}}
private int Foo(int i)
{{
return 1;
}}
}}";
await VerifyProviderCommitAsync(markup, "Foo", expected, commitChar: commitChar);
}
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData('.')]
[InlineData(';')]
public async Task CompletionWithCustomizedCommitCharForDelegateInferredType(char commitChar)
{
var markup = @"
using System;
class Program
{
private void Bar()
{
Bar2(F$$);
}
private void Foo()
{
}
void Bar2(Action t) { }
}";
var expected = $@"
using System;
class Program
{{
private void Bar()
{{
Bar2(Foo{commitChar});
}}
private void Foo()
{{
}}
void Bar2(Action t) {{ }}
}}";
await VerifyProviderCommitAsync(markup, "Foo", expected, commitChar: commitChar);
}
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData('.')]
[InlineData(';')]
public async Task CompletionWithCustomizedCommitCharForConstructor(char commitChar)
{
var markup = @"
class Program
{
private static void Bar()
{
var o = new P$$
}
}";
var expected = $@"
class Program
{{
private static void Bar()
{{
var o = new Program(){commitChar}
}}
}}";
await VerifyProviderCommitAsync(markup, "Program", expected, commitChar: commitChar);
}
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData('.')]
[InlineData(';')]
public async Task CompletionWithCustomizedCharForTypeUnderNonObjectCreationContext(char commitChar)
{
var markup = @"
class Program
{
private static void Bar()
{
var o = P$$
}
}";
var expected = $@"
class Program
{{
private static void Bar()
{{
var o = Program{commitChar}
}}
}}";
await VerifyProviderCommitAsync(markup, "Program", expected, commitChar: commitChar);
}
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData('.')]
[InlineData(';')]
public async Task CompletionWithCustomizedCommitCharForAliasConstructor(char commitChar)
{
var markup = @"
using String2 = System.String;
namespace Bar1
{
class Program
{
private static void Bar()
{
var o = new S$$
}
}
}";
var expected = $@"
using String2 = System.String;
namespace Bar1
{{
class Program
{{
private static void Bar()
{{
var o = new String2(){commitChar}
}}
}}
}}";
await VerifyProviderCommitAsync(markup, "String2", expected, commitChar: commitChar);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionWithSemicolonUnderNameofContext()
{
var markup = @"
namespace Bar1
{
class Program
{
private static void Bar()
{
var o = nameof(B$$)
}
}
}";
var expected = @"
namespace Bar1
{
class Program
{
private static void Bar()
{
var o = nameof(Bar;)
}
}
}";
await VerifyProviderCommitAsync(markup, "Bar", expected, commitChar: ';');
}
[WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EnumMemberAfterPatternMatch()
{
var markup =
@"namespace N
{
enum RankedMusicians
{
BillyJoel,
EveryoneElse
}
class C
{
void M(RankedMusicians m)
{
if (m is RankedMusicians.$$
}
}
}";
// VerifyItemExistsAsync also tests with the item typed.
await VerifyItemExistsAsync(markup, "BillyJoel");
await VerifyItemExistsAsync(markup, "EveryoneElse");
await VerifyItemIsAbsentAsync(markup, "Equals");
}
[WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EnumMemberAfterPatternMatchWithDeclaration()
{
var markup =
@"namespace N
{
enum RankedMusicians
{
BillyJoel,
EveryoneElse
}
class C
{
void M(RankedMusicians m)
{
if (m is RankedMusicians.$$ r)
{
}
}
}
}";
// VerifyItemExistsAsync also tests with the item typed.
await VerifyItemExistsAsync(markup, "BillyJoel");
await VerifyItemExistsAsync(markup, "EveryoneElse");
await VerifyItemIsAbsentAsync(markup, "Equals");
}
[WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EnumMemberAfterPropertyPatternMatch()
{
var markup =
@"namespace N
{
enum RankedMusicians
{
BillyJoel,
EveryoneElse
}
class C
{
public RankedMusicians R;
void M(C m)
{
if (m is { R: RankedMusicians.$$
}
}
}";
// VerifyItemExistsAsync also tests with the item typed.
await VerifyItemExistsAsync(markup, "BillyJoel");
await VerifyItemExistsAsync(markup, "EveryoneElse");
await VerifyItemIsAbsentAsync(markup, "Equals");
}
[WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ChildClassAfterPatternMatch()
{
var markup =
@"namespace N
{
public class D { public class E { } }
class C
{
void M(object m)
{
if (m is D.$$
}
}
}";
// VerifyItemExistsAsync also tests with the item typed.
await VerifyItemExistsAsync(markup, "E");
await VerifyItemIsAbsentAsync(markup, "Equals");
}
[WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EnumMemberAfterBinaryExpression()
{
var markup =
@"namespace N
{
enum RankedMusicians
{
BillyJoel,
EveryoneElse
}
class C
{
void M(RankedMusicians m)
{
if (m == RankedMusicians.$$
}
}
}";
// VerifyItemExistsAsync also tests with the item typed.
await VerifyItemExistsAsync(markup, "BillyJoel");
await VerifyItemExistsAsync(markup, "EveryoneElse");
await VerifyItemIsAbsentAsync(markup, "Equals");
}
[WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EnumMemberAfterBinaryExpressionWithDeclaration()
{
var markup =
@"namespace N
{
enum RankedMusicians
{
BillyJoel,
EveryoneElse
}
class C
{
void M(RankedMusicians m)
{
if (m == RankedMusicians.$$ r)
{
}
}
}
}";
// VerifyItemExistsAsync also tests with the item typed.
await VerifyItemExistsAsync(markup, "BillyJoel");
await VerifyItemExistsAsync(markup, "EveryoneElse");
await VerifyItemIsAbsentAsync(markup, "Equals");
}
[WorkItem(49609, "https://github.com/dotnet/roslyn/issues/49609")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ObsoleteOverloadsAreSkippedIfNonObsoleteOverloadIsAvailable()
{
var markup =
@"
public class C
{
[System.Obsolete]
public void M() { }
public void M(int i) { }
public void Test()
{
this.$$
}
}
";
await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M(int i) (+ 1 {FeaturesResources.overload})");
}
[WorkItem(49609, "https://github.com/dotnet/roslyn/issues/49609")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FirstObsoleteOverloadIsUsedIfAllOverloadsAreObsolete()
{
var markup =
@"
public class C
{
[System.Obsolete]
public void M() { }
[System.Obsolete]
public void M(int i) { }
public void Test()
{
this.$$
}
}
";
await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"[{CSharpFeaturesResources.deprecated}] void C.M() (+ 1 {FeaturesResources.overload})");
}
[WorkItem(49609, "https://github.com/dotnet/roslyn/issues/49609")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task IgnoreCustomObsoleteAttribute()
{
var markup =
@"
public class ObsoleteAttribute: System.Attribute
{
}
public class C
{
[Obsolete]
public void M() { }
public void M(int i) { }
public void Test()
{
this.$$
}
}
";
await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M() (+ 1 {FeaturesResources.overload})");
}
[InlineData("int", "")]
[InlineData("int[]", "int a")]
[Theory, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)]
public async Task TestTargetTypeCompletionDescription(string targetType, string expectedParameterList)
{
// Check the description displayed is based on symbol matches targeted type
SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, true);
var markup =
$@"public class C
{{
bool Bar(int a, int b) => false;
int Bar() => 0;
int[] Bar(int a) => null;
bool N({targetType} x) => true;
void M(C c)
{{
N(c.$$);
}}
}}";
await VerifyItemExistsAsync(
markup, "Bar",
expectedDescriptionOrNull: $"{targetType} C.Bar({expectedParameterList}) (+{NonBreakingSpaceString}2{NonBreakingSpaceString}{FeaturesResources.overloads_})",
matchingFilters: new List<CompletionFilter> { FilterSet.MethodFilter, FilterSet.TargetTypedFilter });
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestTypesNotSuggestedInDeclarationDeconstruction()
{
await VerifyItemIsAbsentAsync(@"
class C
{
int M()
{
var (x, $$) = (0, 0);
}
}", "C");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestTypesSuggestedInMixedDeclarationAndAssignmentInDeconstruction()
{
await VerifyItemExistsAsync(@"
class C
{
int M()
{
(x, $$) = (0, 0);
}
}", "C");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestLocalDeclaredBeforeDeconstructionSuggestedInMixedDeclarationAndAssignmentInDeconstruction()
{
await VerifyItemExistsAsync(@"
class C
{
int M()
{
int y;
(var x, $$) = (0, 0);
}
}", "y");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[WorkItem(53930, "https://github.com/dotnet/roslyn/issues/53930")]
public async Task TestTypeParameterConstraintedToInterfaceWithStatics()
{
var source = @"
interface I1
{
static void M0();
static abstract void M1();
abstract static int P1 { get; set; }
abstract static event System.Action E1;
}
interface I2
{
static abstract void M2();
}
class Test
{
void M<T>(T x) where T : I1, I2
{
T.$$
}
}
";
await VerifyItemIsAbsentAsync(source, "M0");
await VerifyItemExistsAsync(source, "M1");
await VerifyItemExistsAsync(source, "M2");
await VerifyItemExistsAsync(source, "P1");
await VerifyItemExistsAsync(source, "E1");
}
}
}
| 1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/Test2/Rename/RenameEngineTests.CSharpConflicts.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.Remote.Testing
Imports Microsoft.CodeAnalysis.Rename.ConflictEngine
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename
Partial Public Class RenameEngineTests
<[UseExportProvider]>
Public Class CSharpConflicts
Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper
Public Sub New(outputHelper As Abstractions.ITestOutputHelper)
_outputHelper = outputHelper
End Sub
<WpfTheory>
<WorkItem(773543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773543")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub BreakingRenameWithRollBacksInsideLambdas_2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class C
{
class D { public int x = 1; }
Action<int> a = (int [|$$x|]) => // Rename x to y
{
var {|Conflict:y|} = new D();
Console.{|Conflict:WriteLine|}({|Conflict:x|});
};
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="y")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(773534, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773534")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub BreakingRenameWithRollBacksInsideLambdas_1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
struct y
{
public int x;
}
class C
{
class D { public int x = 1; }
Action<y> a = (y [|$$x|]) => // Rename x to y
{ var {|Conflict:y|} = new D();
Console.WriteLine(y.x);
Console.WriteLine({|Conflict:x|}.{|Conflict:x|});
};
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="y")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(773435, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773435")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub BreakingRenameWithInvocationOnDelegateInstance(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public delegate void Foo(int x);
public void FooMeth(int x)
{
}
public void Sub()
{
Foo {|Conflict:x|} = new Foo(FooMeth);
int [|$$z|] = 1; // Rename z to x
int y = {|Conflict:z|};
x({|Conflict:z|}); // Renamed to x(x)
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="x")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(782020, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782020")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub BreakingRenameWithSameClassInOneNamespace(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using K = N.{|Conflict:C|}; // No change, show compiler error
namespace N
{
class {|Conflict:C|}
{
}
}
namespace N
{
class {|Conflict:$$D|} // Rename D to C
{
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="C")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub BreakingRenameCrossAssembly(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBAssembly1">
<ProjectReference>CSAssembly1</ProjectReference>
<Document>
Class D
Public Sub Boo()
Dim x = New {|Conflict:$$C|}()
End Sub
End Class
</Document>
</Project>
<Project Language="C#" CommonReferences="true" AssemblyName="CSAssembly1">
<Document>
public class [|C|]
{
public static void Foo()
{
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="D")
result.AssertLabeledSpansAre("Conflict", "D", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInsideLambdaBody(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Proaasgram
{
object z;
public void masdain(string[] args)
{
Func<int, bool> sx = (int [|$$x|]) =>
{
{|resolve:z|} = null;
if (true)
{
bool y = foo([|x|]);
}
return true;
};
}
public bool foo(int bar)
{
return true;
}
public bool foo(object bar)
{
return true;
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="z")
result.AssertLabeledSpansAre("resolve", "this.z = null;", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<WorkItem(1069237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1069237")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInsideExpressionBodiedLambda(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
using System.Collections.Generic;
using System.Linq;
public class B
{
public readonly int z = 0;
public int X(int [|$$x|]) => {|direct:x|} + {|resolve:z|};
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="z")
result.AssertLabeledSpansAre("direct", "z + this.z", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve", "z + this.z", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<WorkItem(1069237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1069237")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInsideExpressionBodiedLambda2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
using System.Collections.Generic;
using System.Linq;
public class B
{
public static readonly int z = 0;
public int X(int [|$$x|]) => {|direct:x|} + {|resolve:z|};
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="z")
result.AssertLabeledSpansAre("direct", "z + B.z", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve", "z + B.z", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInsideMethodBody(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
using System.Collections.Generic;
using System.Linq;
public class B
{
public readonly int z = 0;
public int Y(int [|$$y|])
{
[|y|] = 0;
return {|resolve:z|};
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="z")
result.AssertLabeledSpansAre("resolve", "return this.z;", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInInvocationWithLambda_1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
static class C
{
static void Ex(this string x) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
static void Inner(Action<string> x, string y) { }
static void Inner(Action<string> x, int y) { }
static void Inner(Action<int> x, int y) { }
static void Main()
{
{|resolve1:Outer|}(y => {|resolve2:Inner|}(x => {
var z = 5;
z.{|resolve0:Ex|}();
x.Ex();
}, y), 0);
}
}
static class E
{
public static void [|$$Ex|](this int x) { } // Rename Ex to Foo
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="L")
Dim outputResult = <code>Outer((string y) => Inner(x => {</code>.Value + vbCrLf +
<code> var z = 5;</code>.Value + vbCrLf +
<code>z.L();</code>.Value + vbCrLf +
<code>x.Ex();</code>.Value + vbCrLf +
<code> }, y), 0);</code>.Value
result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInInvocationWithLambda_2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
static class C
{
static void Ex(this string x) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
static void Inner(Action<string> x, string y) { }
static void Inner(Action<string> x, int y) { }
static void Inner(Action<int> x, int y) { }
static void Main()
{
{|resolve1:Outer|}((y) => {|resolve2:Inner|}((x) => {
var z = 5;
z.{|resolve0:Ex|}();
x.Ex();
}, y), 0);
}
}
static class E
{
public static void [|$$Ex|](this int x) { } // Rename Ex to Foo
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="L")
Dim outputResult = <code>Outer((string y) => Inner((x) => {</code>.Value + vbCrLf +
<code> var z = 5;</code>.Value + vbCrLf +
<code>z.L();</code>.Value + vbCrLf +
<code>x.Ex();</code>.Value + vbCrLf +
<code> }, y), 0);</code>.Value
result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInInvocationWithLambda_3(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
static class C
{
static void Ex(this string x) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
static void Inner(Action<string> x, string y) { }
static void Inner(Action<string> x, int y) { }
static void Inner(Action<int> x, int y) { }
static void Main()
{
{|resolve1:Outer|}((y) => {|resolve2:Inner|}((x) => {
var z = 5;
z.{|resolve0:D|}();
x.Ex();
}, y), 0);
}
}
static class E
{
public static void [|$$D|](this int x) { } // Rename Ex to Foo
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Ex")
Dim outputResult = <code>Outer((y) => Inner((string x) => {</code>.Value + vbCrLf +
<code> var z = 5;</code>.Value + vbCrLf +
<code>z.Ex();</code>.Value + vbCrLf +
<code>x.Ex();</code>.Value + vbCrLf +
<code> }, y), 0);</code>.Value
result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInInvocationWithLambda_4(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
static class C
{
static void Ex(this string x) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
static void Inner(Action<string> x, string y) { }
static void Inner(Action<string> x, int y) { }
static void Inner(Action<int> x, int y) { }
static void Main()
{
{|resolve1:Outer|}(y => {|resolve2:Inner|}(x => {
var z = 5;
z.{|resolve0:D|}();
x.Ex();
}, y), 0);
}
}
static class E
{
public static void [|$$D|](this int x) { } // Rename Ex to Foo
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Ex")
Dim outputResult = <code>Outer(y => Inner((string x) => {</code>.Value + vbCrLf +
<code> var z = 5;</code>.Value + vbCrLf +
<code>z.Ex();</code>.Value + vbCrLf +
<code>x.Ex();</code>.Value + vbCrLf +
<code> }, y), 0);</code>.Value
result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInInvocationWithLambda_5(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
static class C
{
static void Ex(this string x) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
static void Inner(Action<string> x, string y) { }
static void Inner(Action<string> x, int y) { }
static void Inner(Action<int> x, int y) { }
static void Main()
{
{|resolve1:Outer|}(y => {|resolve2:Inner|}(x => {
var z = 5;
z.{|resolve0:D|}();
x.Ex();
}, y), 0);
}
}
static class E
{
public static void [|$$D|](this int x) { } // Rename Ex to Foo
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Ex")
Dim outputResult = <code>Outer(y => Inner((string x) => {</code>.Value + vbCrLf +
<code> var z = 5;</code>.Value + vbCrLf +
<code> z.Ex();</code>.Value + vbCrLf +
<code> x.Ex();</code>.Value + vbCrLf +
<code> }, y), 0);</code>.Value
result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ParameterConflictingWithInstanceField1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Foo
{
int foo;
void Blah(int [|$$bar|])
{
{|stmt2:foo|} = {|stmt1:bar|};
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="foo")
result.AssertLabeledSpansAre("stmt1", "this.foo = foo;", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", "this.foo = foo;", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ParameterConflictingWithInstanceField2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Foo
{
int foo;
void Blah(int [|$$bar|])
{
{|resolved:foo|} = 23;
{|resolved2:foo|} = {|stmt1:bar|};
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="foo")
result.AssertLabeledSpansAre("stmt1", "this.foo = foo;", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolved", "this.foo = 23;", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolved2", "this.foo = foo;", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ParameterConflictingWithInstanceFieldRenamingToKeyword(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Foo
{
int @if;
void Blah(int {|Escape1:$$bar|})
{
{|Resolve:@if|} = 23;
{|Resolve2:@if|} = {|Escape2:bar|};
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="if")
result.AssertLabeledSpansAre("Resolve", "this.@if = 23;", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpecialSpansAre("Escape1", "@if", RelatedLocationType.NoConflict)
result.AssertLabeledSpecialSpansAre("Escape2", "this.@if = @if;", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Resolve2", "this.@if = @if;", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ParameterConflictingWithStaticField(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Foo
{
static int foo;
void Blah(int [|$$bar|])
{
{|Resolved:foo|} = 23;
{|Resolved2:foo|} = {|stmt1:bar|};
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="foo")
result.AssertLabeledSpansAre("Resolved", "Foo.foo = 23;", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("stmt1", "Foo.foo = foo;", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Resolved2", "Foo.foo = foo;", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ParameterConflictingWithFieldFromAnotherLanguage(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<ProjectReference>VisualBasicAssembly</ProjectReference>
<Document>
class Foo : FooBase
{
void Blah(int bar)
{
{|Resolve:$$foo|} = bar;
}
}
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="VisualBasicAssembly" CommonReferences="true">
<Document>
Public Class FooBase
Protected [|foo|] As Integer
End Class
</Document>
</Project>
</Workspace>, host:=host, renameTo:="bar")
result.AssertLabeledSpansAre("Resolve", "base.bar = bar;", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory>
<WorkItem(539745, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539745")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictingTypeDeclaration(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true" LanguageVersion="6">
<Document>< { }
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="Goo")
result.AssertLabeledSpansAre("ReplacementCInt", "C<int>.Goo(i, i);", RelatedLocationType.ResolvedReferenceConflict)
result.AssertLabeledSpansAre("ReplacementCString", "C<string>.Goo(s, s);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingToInvalidIdentifier(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|Invalid:$$Foo|}
{
{|Invalid:Foo|} foo;
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="`")
result.AssertLabeledSpansAre("Invalid", "`", RelatedLocationType.UnresolvedConflict)
result.AssertReplacementTextInvalid()
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingToInvalidIdentifier2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|Invalid:$$Foo|}
{
{|Invalid:Foo|} foo;
}
</Document>
</Project>
</Workspace>, host:=host,
renameTo:="!")
result.AssertLabeledSpansAre("Invalid", "!", RelatedLocationType.UnresolvedConflict)
result.AssertReplacementTextInvalid()
End Using
End Sub
<Theory>
<WorkItem(539636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539636")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingToConflictingMethodInvocation(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
static void F()
{
}
class Blah
{
void [|$$M|]()
{
{|Replacement:F|}();
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="F")
result.AssertLabeledSpansAre("Replacement", "Program.F();", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingToConflictingMethodInvocation2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void M()
{
int foo;
{|Replacement:Bar|}();
}
void [|$$Bar|]()
{
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="foo")
result.AssertLabeledSpansAre("Replacement", "this.foo();", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory>
<WorkItem(539733, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539733")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingTypeToConflictingMemberAndParentTypeName(host As RenameTestHost)
' It's important that we see conflicts for both simultaneously, so I do a single
' test for both cases.
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|Conflict:Foo|}
{
class [|$$Bar|]
{
int {|Conflict:Foo|};
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(539733, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539733")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingMemberToNameConflictingWithParent(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|Conflict:Foo|}
{
int [|$$Bar|];
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(540199, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540199")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingMemberToInvalidIdentifierName(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|Invalid:$$Foo|}
{
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo@")
result.AssertReplacementTextInvalid()
result.AssertLabeledSpansAre("Invalid", "Foo@", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MinimalQualificationOfBaseType1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class X
{
protected class [|$$A|] { }
}
class Y : X
{
private class C : {|Resolve:A|} { }
private class B { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="B")
result.AssertLabeledSpansAre("Resolve", "X.B", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MinimalQualificationOfBaseType2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class X
{
protected class A { }
}
class Y : X
{
private class C : {|Resolve:A|} { }
private class [|$$B|] { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="A")
result.AssertLabeledSpansAre("Resolve", "X.A", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542322")>
Public Sub EscapeIfKeywordWhenDoingTypeNameQualification(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
static class Foo
{
static void {|Escape:Method$$|}() { }
static void Test()
{
int @if;
{|Replacement:Method|}();
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="if")
result.AssertLabeledSpecialSpansAre("Escape", "@if", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Replacement", "Foo.@if();", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542322")>
Public Sub EscapeUnboundGenericTypesInTypeOfContext(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using C = A<int>;
class A<T>
{
public class B<S> { }
}
class Program
{
static void Main()
{
var type = typeof({|stmt1:C|}.B<>);
}
class [|D$$|] { }
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="C")
result.AssertLabeledSpansAre("stmt1", "var type = typeof(A<>.B<>);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542322")>
Public Sub EscapeUnboundGenericTypesInTypeOfContext2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using C = A<int>;
class A<T>
{
public class B<S>
{
public class E { }
}
}
class Program
{
static void Main()
{
var type = typeof({|Replacement:C|}.B<>.E);
}
class [|D$$|] { }
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="C")
result.AssertLabeledSpansAre("Replacement", "var type = typeof(A<>.B<>.E);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542322")>
Public Sub EscapeUnboundGenericTypesInTypeOfContext3(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using C = A<int>;
class A<T>
{
public class B<S>
{
public class E { }
}
}
class Program
{
static void Main()
{
var type = typeof({|Replacement:C|}.B<>.E);
}
class [|D$$|]
{
public class B<S>
{
public class E { }
}
}
}
]]></Document>
</Project>
</Workspace>, host:=host,
renameTo:="C")
result.AssertLabeledSpansAre("Replacement", "var type = typeof(A<>.B<>.E);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542651")>
Public Sub ReplaceAliasWithGenericTypeThatIncludesArrays(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using C = A<int[]>;
class A<T> { }
class Program
{
{|Resolve:C|} x;
class [|D$$|] { }
}
]]></Document>
</Project>
</Workspace>, host:=host,
renameTo:="C")
result.AssertLabeledSpansAre("Resolve", "A<int[]>", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542651")>
Public Sub ReplaceAliasWithGenericTypeThatIncludesPointers(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using C = A<int*>;
class A<T> { }
class Program
{
{|Resolve:C|} x;
class [|D$$|] { }
}
]]></Document>
</Project>
</Workspace>, host:=host,
renameTo:="C")
result.AssertLabeledSpansAre("Resolve", "A<int*>", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542651")>
Public Sub ReplaceAliasWithNestedGenericType(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using C = A<int>.E;
class A<T>
{
public class E { }
}
class B
{
{|Resolve:C|} x;
class [|D$$|] { } // Rename D to C
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="C")
result.AssertLabeledSpansAre("Resolve", "A<int>.E", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory()>
<WorkItem(535068, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535068")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542103")>
<WorkItem(8334, "https://github.com/dotnet/roslyn/issues/8334")>
Public Sub RewriteConflictingExtensionMethodCallSite(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
C Bar(int tag)
{
return this.{|stmt1:Foo|}(1).{|stmt1:Foo|}(2);
}
}
static class E
{
public static C [|$$Foo|](this C x, int tag) { return new C(); }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Bar")
result.AssertLabeledSpansAre("stmt1", "return E.Bar(E.Bar(this, 1), 2);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(535068, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535068")>
<WorkItem(528902, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528902")>
<WorkItem(645152, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/645152")>
<WorkItem(8334, "https://github.com/dotnet/roslyn/issues/8334")>
Public Sub RewriteConflictingExtensionMethodCallSiteWithReturnTypeChange(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void [|$$Bar|](int tag)
{
this.{|Resolved:Foo|}(1).{|Resolved:Foo|}(2);
}
}
static class E
{
public static C Foo(this C x, int tag) { return x; }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("Resolved", "E.Foo(E.Foo(this, 1), 2);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(535068, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535068")>
<WorkItem(542821, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542821")>
Public Sub RewriteConflictingExtensionMethodCallSiteRequiringTypeArguments(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class C
{
void [|$$Bar|]<T>()
{
{|Replacement:this.{|Resolved:Foo|}<int>()|};
}
}
static class E
{
public static void Foo<T>(this C x) { }
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("Resolved", type:=RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("Replacement", "E.Foo<int>(this)")
End Using
End Sub
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(535068, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535068")>
<WorkItem(542103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542103")>
Public Sub RewriteConflictingExtensionMethodCallSiteInferredTypeArguments(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class C
{
void [|$$Bar|]<T>(T y)
{
{|Replacement:this.{|Resolved:Foo|}(42)|};
}
}
static class E
{
public static void Foo<T>(this C x, T y) { }
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("Resolved", type:=RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("Replacement", "E.Foo(this, 42)")
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub DoNotDetectQueryContinuationNamedTheSame(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System.Linq;
class C
{
static void Main(string[] args)
{
var temp = from {|stmt1:$$x|} in "abc"
select {|stmt1:x|} into y
select y;
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="y")
' This may feel strange, but the "into" effectively splits scopes
' into two. There are no errors here.
result.AssertLabeledSpansAre("stmt1", "y", RelatedLocationType.NoConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(543027, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543027")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameHandlesUsingWithoutDeclaration(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System.IO;
class Program
{
public static void Main(string[] args)
{
Stream {|stmt1:$$s|} = new Stream();
using ({|stmt2:s|})
{
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="x")
result.AssertLabeledSpansAre("stmt1", "x", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", "x", RelatedLocationType.NoConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(543027, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543027")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameHandlesForWithoutDeclaration(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
public static void Main(string[] args)
{
int {|stmt1:$$i|};
for ({|stmt2:i|} = 0; ; )
{
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="x")
result.AssertLabeledSpansAre("stmt1", "x", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", "x", RelatedLocationType.NoConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameAttributeSuffix(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
[{|Special:Something|}()]
class Foo{ }
public class [|$$SomethingAttribute|] : Attribute
{
public [|SomethingAttribute|]() { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="SpecialAttribute")
result.AssertLabeledSpansAre("Special", "Special", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameAddAttributeSuffix(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
[[|Something|]()]
class Foo{ }
public class [|$$SomethingAttribute|] : Attribute
{
public [|SomethingAttribute|]() { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Special")
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameKeepAttributeSuffixOnUsages(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
[[|SomethingAttribute|]()]
class Foo { }
public class [|$$SomethingAttribute|] : Attribute
{
public [|SomethingAttribute|] { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="FooAttribute")
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameToConflictWithValue(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
class C
{
public int TestProperty
{
set
{
int [|$$x|];
[|x|] = {|Conflict:value|};
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="value")
' result.AssertLabeledSpansAre("stmt1", "value", RelatedLocationType.NoConflict)
' result.AssertLabeledSpansAre("stmt2", "value", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(543482, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543482")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameAttributeWithConflictingUse(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
class C
{
[Main()]
static void test() { }
}
class MainAttribute : System.Attribute
{
static void Main() { }
}
class [|$$Main|] : System.Attribute
{
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="FooAttribute")
End Using
End Sub
<Theory>
<WorkItem(542649, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542649")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub QualifyTypeWithGlobalWhenConflicting(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
class A { }
class B
{
{|Resolve:A|} x;
class [|$$C|] { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="A")
result.AssertLabeledSpansAre("Resolve", "global::A", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
End Class
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameSymbolDoesNotConflictWithNestedLocals(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class C
{
void Foo()
{
{ int x; }
{|Stmt1:Bar|}();
}
void [|$$Bar|]() { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="x")
result.AssertLabeledSpansAre("Stmt1", "x();", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameSymbolConflictWithLocals(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class C
{
void Foo()
{
int x;
{|Stmt1:Bar|}();
}
void [|$$Bar|]() { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="x")
result.AssertLabeledSpansAre("Stmt1", "this.x();", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(528738, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528738")>
Public Sub RenameAliasToCatchConflict(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using [|$$A|] = X.Something;
using {|Conflict:B|} = X.SomethingElse;
namespace X
{
class Something { }
class SomethingElse { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="B")
result.AssertLabeledSpansAre("Conflict", "B", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameAttributeToCreateConflict(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
[{|Escape:Main|}]
class Some
{
}
class SpecialAttribute : Attribute
{
}
class [|$$Main|] : Attribute // Rename 'Main' to 'Special'
{
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Special")
result.AssertLabeledSpecialSpansAre("Escape", "@Special", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameUsingToKeyword(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
using [|$$S|] = System.Collections;
[A]
class A : {|Resolve:Attribute|}
{
}
class B
{
[|S|].ArrayList a;
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Attribute")
result.AssertLabeledSpansAre("Resolve", "System.Attribute", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(16809, "http://vstfdevdiv:8080/DevDiv_Projects/Roslyn/_workitems/edit/16809")>
<WorkItem(535066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535066")>
Public Sub RenameInNestedClasses(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
namespace N
{
class A<T>
{
public virtual void Foo(T x) { }
class B<S> : A<B<S>>
{
class [|$$C|]<U> : B<{|Resolve1:C|}<U>> // Rename C to A
{
public override void Foo({|Resolve2:A|}<{|Resolve3:A|}<T>.B<S>>.B<{|Resolve4:A|}<T>.B<S>.{|Resolve1:C|}<U>> x) { }
}
}
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="A")
result.AssertLabeledSpansAre("Resolve1", "A", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Resolve2", "N.A<N.A<T>.B<S>>", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("Resolve3", "N.A<N.A<T>.B<S>>", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("Resolve4", "N.A<T>", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory()>
<WorkItem(535066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535066")>
<WorkItem(531433, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531433")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameAndEscapeContextualKeywordsInCSharp(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System.Linq;
class [|t$$o|] // Rename 'to' to 'from'
{
object q = from x in "" select new {|resolved:to|}();
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="from")
result.AssertLabeledSpansAre("resolved", "@from", RelatedLocationType.NoConflict)
End Using
End Sub
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(522774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/522774")>
Public Sub RenameCrefWithConflict(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
using F = N;
namespace N
{
interface I
{
void Foo();
}
}
class C
{
class E : {|Resolve:F|}.I
{
/// <summary>
/// This is a function <see cref="{|Resolve:F|}.I.Foo"/>
/// </summary>
public void Foo() { }
}
class [|$$K|]
{
}
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="F")
result.AssertLabeledSpansAre("Resolve", "N", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameClassContainingAlias(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
using C = A<int,int>;
class A<T,U>
{
public class B<S>
{
}
}
class [|$$B|]
{
{|Resolve:C|}.B<int> cb;
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="C")
result.AssertLabeledSpansAre("Resolve", "A<int, int>", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameFunctionWithOverloadConflict(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
class Bar
{
void Foo(int x) { }
void [|Boo|](object x) { }
void Some()
{
Foo(1);
{|Resolve:$$Boo|}(1);
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("Resolve", "Foo((object)1);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameActionWithFunctionConflict(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
class Program
{
static void doer(int x)
{
Console.WriteLine("Hey");
}
static void Main(string[] args)
{
Action<int> {|stmt1:$$action|} = delegate(int x) { Console.WriteLine(x); }; // Rename action to doer
{|stmt2:doer|}(3);
}
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="doer")
result.AssertLabeledSpansAre("stmt1", "doer", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", "Program.doer(3);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(552522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552522")>
Public Sub RenameFunctionNameToDelegateTypeConflict1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class A
{
static void [|Foo|]() { }
class B
{
delegate void Del();
void Boo()
{
Del d = new Del({|Stmt1:Foo|});
{|Stmt2:$$Foo|}();
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Del")
result.AssertLabeledSpansAre("Stmt1", "Del d = new Del(A.Del);", RelatedLocationType.ResolvedReferenceConflict)
result.AssertLabeledSpansAre("Stmt2", "Del", RelatedLocationType.NoConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(552520, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552520")>
Public Sub RenameFunctionNameToDelegateTypeConflict2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class A
{
static void [|$$Foo|]() { }
class B
{
delegate void Del();
void Bar() { }
void Boo()
{
Del d = new Del({|Stmt1:Foo|});
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Bar")
result.AssertLabeledSpansAre("Stmt1", "Del d = new Del(A.Bar);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameFunctionNameToDelegateTypeConflict3(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class A
{
delegate void Del(Del a);
static void [|Bar|](Del a) { }
class B
{
Del Boo = new Del({|decl1:Bar|});
void Foo()
{
Boo({|Stmt2:Bar|});
{|Stmt3:$$Bar|}(Boo);
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Boo")
result.AssertLabeledSpansAre("decl1", "new Del(A.Boo)", RelatedLocationType.ResolvedReferenceConflict)
result.AssertLabeledSpansAre("Stmt2", "Boo(A.Boo);", RelatedLocationType.ResolvedReferenceConflict)
result.AssertLabeledSpansAre("Stmt3", "A.Boo(Boo);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(552520, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552520")>
Public Sub RenameFunctionNameToDelegateTypeConflict4(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class A
{
static void Foo(int i) { }
static void Foo(string s) { }
class B
{
delegate void Del(string s);
void [|$$Bar|](string s) { }
void Boo()
{
Del d = new Del({|stmt1:Foo|});
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Del d = new Del(A.Foo);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(552722, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552722")>
Public Sub RenameActionTypeConflict(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
class A
{
static Action<int> [|$$Baz|] = (int x) => { };
class B
{
Action<int> Bar = (int x) => { };
void Foo()
{
{|Stmt1:Baz|}(3);
}
}
}]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Bar")
result.AssertLabeledSpansAre("Stmt1", "A.Bar(3);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(552722, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552722")>
Public Sub RenameConflictAttribute1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
[{|escape:Bar|}]
class Bar : System.Attribute
{ }
class [|$$FooAttribute|] : System.Attribute
{ }
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="BarAttribute")
result.AssertLabeledSpansAre("escape", "@Bar", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameConflictAttribute2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
[{|Resolve:B|}]
class [|$$BAttribute|] : Attribute
{
}
class AAttributeAttribute : Attribute
{
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="AAttribute")
result.AssertLabeledSpecialSpansAre("Resolve", "A", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<WorkItem(576573, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576573")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub Bug576573_ConflictAttributeWithNamespace(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
namespace X
{
class BAttribute
: System.Attribute
{ }
namespace Y.[|$$Z|]
{
[{|Resolve:B|}]
class Foo { }
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="BAttribute")
result.AssertLabeledSpansAre("Resolve", "X.B", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(579602, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579602")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub Bug579602_RenameFunctionWithDynamicParameter(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class A
{
class B
{
public void [|Boo|](int d) { } //Line 1
}
void Bar()
{
B b = new B();
dynamic d = 1.5f;
b.{|stmt1:$$Boo|}(d); //Line 2 Rename Boo to Foo
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo", RelatedLocationType.NoConflict)
End Using
End Sub
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub IdentifyConflictsWithVar(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class [|$$vor|]
{
static void Main(string[] args)
{
{|conflict:var|} x = 23;
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="v\u0061r")
result.AssertLabeledSpansAre("conflict", "var", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(633180, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633180")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub CS_DetectOverLoadResolutionChangesInEnclosingInvocations(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
static class C
{
static void Ex(this string x) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
static void Inner(Action<string> x, string y) { }
static void Inner(Action<string> x, int y) { }
static void Inner(Action<int> x, int y) { }
static void Main()
{
{|resolved:Outer|}(y => {|resolved:Inner|}(x => x.Ex(), y), 0);
}
}
static class E
{
public static void [|$$Ex|](this int x) { } // Rename Ex to Foo
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("resolved", "Outer((string y) => Inner(x => x.Ex(), y), 0);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(635622, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635622")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ExpandingDynamicAddsObjectCast(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class C
{
static void [|$$Foo|](int x, Action y) { } // Rename Foo to Bar
static void Bar(dynamic x, Action y) { }
static void Main()
{
{|resolve:Bar|}(1, Console.WriteLine);
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Bar")
result.AssertLabeledSpansAre("resolve", "Bar((object)1, Console.WriteLine);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(673562, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/673562")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameNamespaceConflictsAndResolves(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
namespace N
{
class C
{
{|resolve:N|}.C x;
/// <see cref="{|resolve:N|}.C"/>
void Sub()
{ }
}
namespace [|$$K|] // Rename K to N
{
class C
{ }
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="N")
result.AssertLabeledSpansAre("resolve", "global::N", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(673667, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/673667")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameUnnecessaryExpansion(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
namespace N
{
using K = {|stmt1:N|}.C;
class C
{
}
class [|$$D|] // Rename D to N
{
class C
{
[|D|] x;
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="N")
result.AssertLabeledSpansAre("stmt1", "global::N", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(768910, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768910")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameInCrefPreservesWhitespaceTrivia(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
<![CDATA[
public class A
{
public class B
{
public class C
{
}
/// <summary>
/// <see cref=" {|Resolve:D|}"/>
/// </summary>
public static void [|$$foo|]() // Rename foo to D
{
}
}
public class D
{
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="D")
result.AssertLabeledSpansAre("Resolve", "A.D", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
#Region "Type Argument Expand/Reduce for Generic Method Calls - 639136"
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class C
{
static void F<T>(Func<int, T> x) { }
static void [|$$B|](Func<int, int> x) { } // Rename Bar to Foo
static void Main()
{
{|stmt1:F|}(a => a);
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="F")
result.AssertLabeledSpansAre("stmt1", "F<int>(a => a);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<WorkItem(725934, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/725934")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_This(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class C
{
void TestMethod()
{
int x = 1;
Func<int> y = delegate { return {|stmt1:Foo|}(x); };
}
int Foo<T>(T x) { return 1; }
int [|$$Bar|](int x) { return 1; }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "return Foo<int>(x);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_Nested(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
public static void [|$$Foo|]<T>(T x) { }
public static void Bar(int x) { }
class D
{
void Bar<T>(T x) { }
void Bar(int x) { }
void sub()
{
{|stmt1:Foo|}(1);
}
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Bar")
result.AssertLabeledSpansAre("stmt1", "C.Bar<int>(1);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_ReferenceType(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< {return 1; } // Rename Bar to Foo
public void Test()
{
string one = "1";
{|stmt1:Foo|}(one);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<string>(one);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_ConstructedTypeArgumentNonGenericContainer(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { } // Rename Bar to Foo
public void Sub()
{
D<int> x = new D<int>();
{|stmt1:Foo|}(x);
}
}
class D<T>
{}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<D<int>>(x);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_SameTypeParameter(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System.Linq.Expressions;
class C
{
public static int Foo<T>(T x) { return 1; }
public static int [|$$Bar|]<T>(Expression<Func<int, T>> x) { return 1; }
Expression<Func<int, int>> x = (y) => Foo(1);
public void sub()
{
{|stmt1:Foo|}(x);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<Expression<Func<int, int>>>(x);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_ArrayTypeParameter(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
public void [|$$Foo|]<S>(S x) { }
public void Bar(int[] x) { }
public void Sub()
{
var x = new int[] { 1, 2, 3 };
{|stmt1:Foo|}(x);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Bar")
result.AssertLabeledSpansAre("stmt1", "Bar<int[]>(x);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_MultiDArrayTypeParameter(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { }
public void Sub()
{
var x = new int[,] { { 1, 2 }, { 2, 3 } };
{|stmt1:Foo|}(x);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<int[,]>(x);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_UsedAsArgument(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< {return 1; }
public void Sub(int x) { }
public void Test()
{
Sub({|stmt1:Foo|}(1));
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Sub(Foo<int>(1));", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_UsedInConstructorInitialization(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< {return 1; }
public void Test()
{
C c = new C({|stmt1:Foo|}(1));
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "C c = new C(Foo<int>(1));", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_CalledOnObject(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< {return 1; } // Rename Bar to Foo
public void Test()
{
C c = new C();
c.{|stmt1:Foo|}(1);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "c.Foo<int>(1);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_UsedInGenericDelegate(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< {return 1; } // Rename Bar to Foo
public void Test()
{
FooDel<int> foodel = new FooDel<int>({|stmt1:Foo|});
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "FooDel<int> foodel = new FooDel<int>(Foo<int>);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_UsedInNonGenericDelegate(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< {return 1; } // Rename Bar to Foo
public void Test()
{
FooDel foodel = new FooDel({|stmt1:Foo|});
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "FooDel foodel = new FooDel(Foo<int>);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_MultipleTypeParameters(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
public void Foo<T, S>(T x, S y) { }
public void [|$$Bar|]<U, P>(U[] x, P y) { }
public void Sub()
{
int[] x;
{|stmt1:Foo|}(x, new C());
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<int[], C>(x, new C());", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<WorkItem(730781, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730781")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_ConflictInDerived(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { }
public void Sub()
{
{|stmt1:Foo|}(1);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "base.Foo(1);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(728653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728653")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameGenericInvocationWithDynamicArgument(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { } // Rename Bar to F
public void sub()
{
dynamic x = 1;
{|stmt1:F|}(x);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="F")
result.AssertLabeledSpansAre("stmt1", "F", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(728646, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728646")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ExpandInvocationInStaticMemberAccess(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { } // Rename Bar to Foo
public void Sub()
{
}
}
class D
{
public void Sub()
{
C.{|stmt1:Foo|}(1);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "C.Foo<int>(1);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(728628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728628")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RecursiveTypeParameterExpansionFail(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { } // Rename Bar to Foo
public void Sub()
{
C<int> x = new C<int>();
{|stmt1:Foo|}(x);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<C<int>>(x);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(728575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728575")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameCrefWithProperBracesForTypeInferenceAdditionToMethod(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { } // Rename to Zoo
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Zoo")
result.AssertLabeledSpansAre("cref1", "Zoo{T}", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_GenericBase(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { } // Rename Bar to Foo
}
class D : C<int>
{
public void Test()
{
{|stmt1:Foo|}(1);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<int>(1);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<WpfTheory(Skip:="Story 736967"), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_InErrorCode(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< // Rename Bar to Foo
{
x = 1;
}
public void Test()
{
int y = 1;
int x;
{|stmt1:Foo|}(y, x); // error in code, but Foo is bound to Foo<T>
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<int>(y, x);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
#End Region
<WorkItem(1016652, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1016652")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub CS_ConflictBetweenTypeNamesInTypeConstraintSyntax(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System.Collections.Generic;
// rename INamespaceSymbol to ISymbol
public interface {|unresolved1:$$INamespaceSymbol|} { }
public interface {|DeclConflict:ISymbol|} { }
public interface IReferenceFinder { }
internal abstract partial class AbstractReferenceFinder<TSymbol> : IReferenceFinder
where TSymbol : {|unresolved2:INamespaceSymbol|}
{
}]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="ISymbol")
result.AssertLabeledSpansAre("DeclConflict", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("unresolved1", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("unresolved2", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(1193, "https://github.com/dotnet/roslyn/issues/1193")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MemberQualificationInNameOfUsesTypeName_StaticReferencingInstance(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
static void F(int [|$$z|])
{
string x = nameof({|ref:zoo|});
}
int zoo;
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="zoo")
result.AssertLabeledSpansAre("ref", "string x = nameof(C.zoo);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1193, "https://github.com/dotnet/roslyn/issues/1193")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MemberQualificationInNameOfUsesTypeName_InstanceReferencingStatic(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
void F(int [|$$z|])
{
string x = nameof({|ref:zoo|});
}
static int zoo;
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="zoo")
result.AssertLabeledSpansAre("ref", "string x = nameof(C.zoo);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1193, "https://github.com/dotnet/roslyn/issues/1193")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MemberQualificationInNameOfUsesTypeName_InstanceReferencingInstance(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
void F(int [|$$z|])
{
string x = nameof({|ref:zoo|});
}
int zoo;
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="zoo")
result.AssertLabeledSpansAre("ref", "string x = nameof(C.zoo);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1193, "https://github.com/dotnet/roslyn/issues/1193")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MemberQualificationInNameOfMethodInvocationUsesThisDot(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
int zoo;
void F(int [|$$z|])
{
string x = nameof({|ref:zoo|});
}
void nameof(int x) { }
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="zoo")
result.AssertLabeledSpansAre("ref", "string x = nameof(this.zoo);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1053, "https://github.com/dotnet/roslyn/issues/1053")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameComplexifiesInLambdaBodyExpression(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< => 5;
static int N(long b) => 5;
System.Func<int, int> a = d => {|resolved:N|}(1);
System.Func<int> b = () => {|resolved:N|}(1);
}]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="N")
result.AssertLabeledSpansAre("resolved", "N((long)1)", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1053, "https://github.com/dotnet/roslyn/issues/1053")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameComplexifiesInExpressionBodiedMembers(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< => {|resolved2:N|}(0);
int N(long b) => [|M|](0);
int P => {|resolved2:N|}(0);
}]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="N")
result.AssertLabeledSpansAre("resolved1", "new C().N((long)0)", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolved2", "N((long)0)", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestConflictBetweenClassAndInterface1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class {|conflict:C|} { }
interface [|$$I|] { }
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="C")
result.AssertLabeledSpansAre("conflict", "C", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
<WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestConflictBetweenClassAndInterface2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class [|$$C|] { }
interface {|conflict:I|} { }
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="I")
result.AssertLabeledSpansAre("conflict", "I", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
<WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestConflictBetweenClassAndNamespace1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class {|conflict:$$C|} { }
namespace N { }
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="N")
result.AssertLabeledSpansAre("conflict", "N", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
<WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestConflictBetweenClassAndNamespace1_FileScopedNamespace(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class {|conflict:$$C|} { }
namespace N;
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="N")
result.AssertLabeledSpansAre("conflict", "N", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
<WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestConflictBetweenClassAndNamespace2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class {|conflict:C|} { }
namespace [|$$N|] { }
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="C")
result.AssertLabeledSpansAre("conflict", "C", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
<WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestNoConflictBetweenTwoNamespaces(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
namespace [|$$N1|][ { }
namespace N2 { }
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="N2")
End Using
End Sub
<WorkItem(1729, "https://github.com/dotnet/roslyn/issues/1729")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestNoConflictWithParametersOrLocalsOfDelegateType(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
class C
{
void M1(Action [|callback$$|])
{
[|callback|]();
}
void M2(Func<bool> callback)
{
callback();
}
void M3()
{
Action callback = () => { };
callback();
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="callback2")
End Using
End Sub
<WorkItem(1729, "https://github.com/dotnet/roslyn/issues/1729")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestConflictWithLocalsOfDelegateTypeWhenBindingChangesToNonDelegateLocal(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
class C
{
void M()
{
int [|x$$|] = 7; // Rename x to a. "a()" will bind to the first definition of a.
Action {|conflict:a|} = () => { };
{|conflict:a|}();
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="a")
result.AssertLabeledSpansAre("conflict", "a", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(446, "https://github.com/dotnet/roslyn/issues/446")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub NoCrashOrConflictOnRenameWithNameOfInAttribute(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
static void [|T|]$$(int x) { }
[System.Obsolete(nameof(Test))]
static void Test() { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Test")
End Using
End Sub
<WorkItem(1195, "https://github.com/dotnet/roslyn/issues/1195")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictWhenNameOfReferenceDoesNotBindToAnyOriginalSymbols(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void Test()
{
int [|T$$|];
var x = nameof({|conflict:Test|});
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Test")
result.AssertLabeledSpansAre("conflict", "Test", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(1195, "https://github.com/dotnet/roslyn/issues/1195")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub NoConflictWhenNameOfReferenceDoesNotBindToSomeOriginalSymbols(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void [|$$M|](int x) { }
void M() { var x = nameof(M); }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="X")
End Using
End Sub
<WorkItem(1195, "https://github.com/dotnet/roslyn/issues/1195")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub NoConflictWhenNameOfReferenceBindsToSymbolForFirstTime(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void [|X$$|]() { }
void M() { var x = nameof(T); }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="T")
End Using
End Sub
<WorkItem(1195, "https://github.com/dotnet/roslyn/issues/1195")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictWhenNameOfReferenceChangesBindingFromMetadataToSource(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class Program
{
static void M()
{
var [|Consol$$|] = 7;
var x = nameof({|conflict:Console|});
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Console")
result.AssertLabeledSpansAre("conflict", "Console", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(1031, "https://github.com/dotnet/roslyn/issues/1031")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub InvalidNamesDoNotCauseCrash_IntroduceQualifiedName(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|conflict:C$$|} { }
</Document>
</Project>
</Workspace>, host:=host, renameTo:="C.D")
result.AssertReplacementTextInvalid()
result.AssertLabeledSpansAre("conflict", "C.D", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(1031, "https://github.com/dotnet/roslyn/issues/1031")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub InvalidNamesDoNotCauseCrash_AccidentallyPasteLotsOfCode(host As RenameTestHost)
Dim renameTo = "class C { public void M() { for (int i = 0; i < 10; i++) { System.Console.Writeline(""This is a test""); } } }"
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|conflict:C$$|} { }
</Document>
</Project>
</Workspace>, host:=host, renameTo:=renameTo)
result.AssertReplacementTextInvalid()
result.AssertLabeledSpansAre("conflict", renameTo, RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(2352, "https://github.com/dotnet/roslyn/issues/2352")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub DeclarationConflictInFileWithoutReferences_SameProject(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test1.cs">
class Program
{
internal void [|A$$|]() { }
internal void {|conflict:B|}() { }
}
</Document>
<Document FilePath="Test2.cs">
class Program2
{
void M()
{
Program p = null;
p.{|conflict:A|}();
p.{|conflict:B|}();
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="B")
result.AssertLabeledSpansAre("conflict", "B", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(2352, "https://github.com/dotnet/roslyn/issues/2352")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub DeclarationConflictInFileWithoutReferences_DifferentProjects(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSAssembly1">
<Document FilePath="Test1.cs">
public class Program
{
public void [|A$$|]() { }
public void {|conflict:B|}() { }
}
</Document>
</Project>
<Project Language="C#" CommonReferences="true" AssemblyName="CSAssembly2">
<ProjectReference>CSAssembly1</ProjectReference>
<Document FilePath="Test2.cs">
class Program2
{
void M()
{
Program p = null;
p.{|conflict:A|}();
p.{|conflict:B|}();
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="B")
result.AssertLabeledSpansAre("conflict", "B", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(2352, "https://github.com/dotnet/roslyn/issues/2352")>
<WorkItem(3303, "https://github.com/dotnet/roslyn/issues/3303")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub DeclarationConflictInFileWithoutReferences_PartialTypes(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test1.cs">
partial class C
{
private static void [|$$M|]()
{
{|conflict:M|}();
}
}
</Document>
<Document FilePath="Test2.cs">
partial class C
{
private static void {|conflict:Method|}()
{
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Method")
result.AssertLabeledSpansAre("conflict", "Method", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(1439, "https://github.com/dotnet/roslyn/issues/1439")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameInsideNameOf1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
int field;
static void Main(string[] args)
{
// Rename "local" to "field"
int [|$$local|];
nameof({|Conflict:field|}).ToString(); // Should also expand to Program.field
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="field")
result.AssertLabeledSpansAre("Conflict", replacement:="nameof(Program.field).ToString();", type:=RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1439, "https://github.com/dotnet/roslyn/issues/1439")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameInsideNameOf2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
int field;
static void Main(string[] args)
{
// Rename "local" to "field"
int [|$$local|];
nameof({|Conflict:field|})?.ToString(); // Should also expand to Program.field
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="field")
result.AssertLabeledSpansAre("Conflict", replacement:="nameof(Program.field)?.ToString();", type:=RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1439, "https://github.com/dotnet/roslyn/issues/1439")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameInsideNameOf3(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
static int field;
static void Main(string[] args)
{
// Rename "local" to "field"
int [|$$local|];
Program.nameof({|Conflict:field|}); // Should also expand to Program.field
}
static void nameof(string s) { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="field")
result.AssertLabeledSpansAre("Conflict", replacement:="Program.nameof(Program.field);", type:=RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(7440, "https://github.com/dotnet/roslyn/issues/7440")>
Public Sub RenameTypeParameterInPartialClass(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
partial class C<[|$$T|]> {}
partial class C<[|T|]> {}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="T2")
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(7440, "https://github.com/dotnet/roslyn/issues/7440")>
Public Sub RenameMethodToConflictWithTypeParameter(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
partial class C<{|Conflict:T|}> { void [|$$M|]() { } }
partial class C<{|Conflict:T|}> {}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="T")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(10469, "https://github.com/dotnet/roslyn/issues/10469")>
Public Sub RenameTypeToCurrent(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
partial class {|current:$$C|} { }
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Current")
result.AssertLabeledSpansAre("current", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(16567, "https://github.com/dotnet/roslyn/issues/16567")>
Public Sub RenameMethodToFinalizeWithDestructorPresent(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
~{|Conflict:C|}() { }
void $$[|M|]()
{
int x = 7;
int y = ~x;
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Finalize")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WpfTheory>
<WorkItem(5872, "https://github.com/dotnet/roslyn/issues/5872")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub CannotRenameToVar(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class $${|Conflict:X|} {
{|Conflict:X|}() {
var a = 2;
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="var")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WpfTheory>
<WorkItem(45677, "https://github.com/dotnet/roslyn/issues/45677")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictWhenRenamingPropertySetterLikeMethod(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public int MyProperty { get; {|conflict:set|}; }
private void {|conflict:$$_set_MyProperty|}(int value) => throw null;
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="set_MyProperty")
result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WpfTheory>
<WorkItem(45677, "https://github.com/dotnet/roslyn/issues/45677")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictWhenRenamingPropertyInitterLikeMethod(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public int MyProperty { get; {|conflict:init|}; }
private void {|conflict:$$_set_MyProperty|}(int value) => throw null;
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="set_MyProperty")
result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WpfTheory>
<WorkItem(45677, "https://github.com/dotnet/roslyn/issues/45677")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictWhenRenamingPropertyGetterLikeMethod(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public int MyProperty { {|conflict:get|}; set; }
private int {|conflict:$$_get_MyProperty|}() => throw null;
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="get_MyProperty")
result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Remote.Testing
Imports Microsoft.CodeAnalysis.Rename.ConflictEngine
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename
Partial Public Class RenameEngineTests
<[UseExportProvider]>
Public Class CSharpConflicts
Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper
Public Sub New(outputHelper As Abstractions.ITestOutputHelper)
_outputHelper = outputHelper
End Sub
<WpfTheory>
<WorkItem(773543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773543")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub BreakingRenameWithRollBacksInsideLambdas_2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class C
{
class D { public int x = 1; }
Action<int> a = (int [|$$x|]) => // Rename x to y
{
var {|Conflict:y|} = new D();
Console.{|Conflict:WriteLine|}({|Conflict:x|});
};
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="y")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(773534, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773534")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub BreakingRenameWithRollBacksInsideLambdas_1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
struct y
{
public int x;
}
class C
{
class D { public int x = 1; }
Action<y> a = (y [|$$x|]) => // Rename x to y
{ var {|Conflict:y|} = new D();
Console.WriteLine(y.x);
Console.WriteLine({|Conflict:x|}.{|Conflict:x|});
};
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="y")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(773435, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773435")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub BreakingRenameWithInvocationOnDelegateInstance(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public delegate void Foo(int x);
public void FooMeth(int x)
{
}
public void Sub()
{
Foo {|Conflict:x|} = new Foo(FooMeth);
int [|$$z|] = 1; // Rename z to x
int y = {|Conflict:z|};
x({|Conflict:z|}); // Renamed to x(x)
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="x")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(782020, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782020")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub BreakingRenameWithSameClassInOneNamespace(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using K = N.{|Conflict:C|}; // No change, show compiler error
namespace N
{
class {|Conflict:C|}
{
}
}
namespace N
{
class {|Conflict:$$D|} // Rename D to C
{
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="C")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub BreakingRenameCrossAssembly(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBAssembly1">
<ProjectReference>CSAssembly1</ProjectReference>
<Document>
Class D
Public Sub Boo()
Dim x = New {|Conflict:$$C|}()
End Sub
End Class
</Document>
</Project>
<Project Language="C#" CommonReferences="true" AssemblyName="CSAssembly1">
<Document>
public class [|C|]
{
public static void Foo()
{
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="D")
result.AssertLabeledSpansAre("Conflict", "D", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInsideLambdaBody(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Proaasgram
{
object z;
public void masdain(string[] args)
{
Func<int, bool> sx = (int [|$$x|]) =>
{
{|resolve:z|} = null;
if (true)
{
bool y = foo([|x|]);
}
return true;
};
}
public bool foo(int bar)
{
return true;
}
public bool foo(object bar)
{
return true;
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="z")
result.AssertLabeledSpansAre("resolve", "this.z = null;", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<WorkItem(1069237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1069237")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInsideExpressionBodiedLambda(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
using System.Collections.Generic;
using System.Linq;
public class B
{
public readonly int z = 0;
public int X(int [|$$x|]) => {|direct:x|} + {|resolve:z|};
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="z")
result.AssertLabeledSpansAre("direct", "z + this.z", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve", "z + this.z", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<WorkItem(1069237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1069237")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInsideExpressionBodiedLambda2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
using System.Collections.Generic;
using System.Linq;
public class B
{
public static readonly int z = 0;
public int X(int [|$$x|]) => {|direct:x|} + {|resolve:z|};
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="z")
result.AssertLabeledSpansAre("direct", "z + B.z", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve", "z + B.z", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInsideMethodBody(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
using System.Collections.Generic;
using System.Linq;
public class B
{
public readonly int z = 0;
public int Y(int [|$$y|])
{
[|y|] = 0;
return {|resolve:z|};
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="z")
result.AssertLabeledSpansAre("resolve", "return this.z;", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInInvocationWithLambda_1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
static class C
{
static void Ex(this string x) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
static void Inner(Action<string> x, string y) { }
static void Inner(Action<string> x, int y) { }
static void Inner(Action<int> x, int y) { }
static void Main()
{
{|resolve1:Outer|}(y => {|resolve2:Inner|}(x => {
var z = 5;
z.{|resolve0:Ex|}();
x.Ex();
}, y), 0);
}
}
static class E
{
public static void [|$$Ex|](this int x) { } // Rename Ex to Foo
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="L")
Dim outputResult = <code>Outer((string y) => Inner(x => {</code>.Value + vbCrLf +
<code> var z = 5;</code>.Value + vbCrLf +
<code>z.L();</code>.Value + vbCrLf +
<code>x.Ex();</code>.Value + vbCrLf +
<code> }, y), 0);</code>.Value
result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInInvocationWithLambda_2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
static class C
{
static void Ex(this string x) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
static void Inner(Action<string> x, string y) { }
static void Inner(Action<string> x, int y) { }
static void Inner(Action<int> x, int y) { }
static void Main()
{
{|resolve1:Outer|}((y) => {|resolve2:Inner|}((x) => {
var z = 5;
z.{|resolve0:Ex|}();
x.Ex();
}, y), 0);
}
}
static class E
{
public static void [|$$Ex|](this int x) { } // Rename Ex to Foo
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="L")
Dim outputResult = <code>Outer((string y) => Inner((x) => {</code>.Value + vbCrLf +
<code> var z = 5;</code>.Value + vbCrLf +
<code>z.L();</code>.Value + vbCrLf +
<code>x.Ex();</code>.Value + vbCrLf +
<code> }, y), 0);</code>.Value
result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInInvocationWithLambda_3(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
static class C
{
static void Ex(this string x) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
static void Inner(Action<string> x, string y) { }
static void Inner(Action<string> x, int y) { }
static void Inner(Action<int> x, int y) { }
static void Main()
{
{|resolve1:Outer|}((y) => {|resolve2:Inner|}((x) => {
var z = 5;
z.{|resolve0:D|}();
x.Ex();
}, y), 0);
}
}
static class E
{
public static void [|$$D|](this int x) { } // Rename Ex to Foo
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Ex")
Dim outputResult = <code>Outer((y) => Inner((string x) => {</code>.Value + vbCrLf +
<code> var z = 5;</code>.Value + vbCrLf +
<code>z.Ex();</code>.Value + vbCrLf +
<code>x.Ex();</code>.Value + vbCrLf +
<code> }, y), 0);</code>.Value
result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInInvocationWithLambda_4(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
static class C
{
static void Ex(this string x) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
static void Inner(Action<string> x, string y) { }
static void Inner(Action<string> x, int y) { }
static void Inner(Action<int> x, int y) { }
static void Main()
{
{|resolve1:Outer|}(y => {|resolve2:Inner|}(x => {
var z = 5;
z.{|resolve0:D|}();
x.Ex();
}, y), 0);
}
}
static class E
{
public static void [|$$D|](this int x) { } // Rename Ex to Foo
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Ex")
Dim outputResult = <code>Outer(y => Inner((string x) => {</code>.Value + vbCrLf +
<code> var z = 5;</code>.Value + vbCrLf +
<code>z.Ex();</code>.Value + vbCrLf +
<code>x.Ex();</code>.Value + vbCrLf +
<code> }, y), 0);</code>.Value
result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInInvocationWithLambda_5(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
static class C
{
static void Ex(this string x) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
static void Inner(Action<string> x, string y) { }
static void Inner(Action<string> x, int y) { }
static void Inner(Action<int> x, int y) { }
static void Main()
{
{|resolve1:Outer|}(y => {|resolve2:Inner|}(x => {
var z = 5;
z.{|resolve0:D|}();
x.Ex();
}, y), 0);
}
}
static class E
{
public static void [|$$D|](this int x) { } // Rename Ex to Foo
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Ex")
Dim outputResult = <code>Outer(y => Inner((string x) => {</code>.Value + vbCrLf +
<code> var z = 5;</code>.Value + vbCrLf +
<code> z.Ex();</code>.Value + vbCrLf +
<code> x.Ex();</code>.Value + vbCrLf +
<code> }, y), 0);</code>.Value
result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ParameterConflictingWithInstanceField1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Foo
{
int foo;
void Blah(int [|$$bar|])
{
{|stmt2:foo|} = {|stmt1:bar|};
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="foo")
result.AssertLabeledSpansAre("stmt1", "this.foo = foo;", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", "this.foo = foo;", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ParameterConflictingWithInstanceField2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Foo
{
int foo;
void Blah(int [|$$bar|])
{
{|resolved:foo|} = 23;
{|resolved2:foo|} = {|stmt1:bar|};
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="foo")
result.AssertLabeledSpansAre("stmt1", "this.foo = foo;", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolved", "this.foo = 23;", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolved2", "this.foo = foo;", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ParameterConflictingWithInstanceFieldRenamingToKeyword(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Foo
{
int @if;
void Blah(int {|Escape1:$$bar|})
{
{|Resolve:@if|} = 23;
{|Resolve2:@if|} = {|Escape2:bar|};
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="if")
result.AssertLabeledSpansAre("Resolve", "this.@if = 23;", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpecialSpansAre("Escape1", "@if", RelatedLocationType.NoConflict)
result.AssertLabeledSpecialSpansAre("Escape2", "this.@if = @if;", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Resolve2", "this.@if = @if;", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ParameterConflictingWithStaticField(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Foo
{
static int foo;
void Blah(int [|$$bar|])
{
{|Resolved:foo|} = 23;
{|Resolved2:foo|} = {|stmt1:bar|};
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="foo")
result.AssertLabeledSpansAre("Resolved", "Foo.foo = 23;", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("stmt1", "Foo.foo = foo;", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Resolved2", "Foo.foo = foo;", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ParameterConflictingWithFieldFromAnotherLanguage(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<ProjectReference>VisualBasicAssembly</ProjectReference>
<Document>
class Foo : FooBase
{
void Blah(int bar)
{
{|Resolve:$$foo|} = bar;
}
}
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="VisualBasicAssembly" CommonReferences="true">
<Document>
Public Class FooBase
Protected [|foo|] As Integer
End Class
</Document>
</Project>
</Workspace>, host:=host, renameTo:="bar")
result.AssertLabeledSpansAre("Resolve", "base.bar = bar;", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory>
<WorkItem(539745, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539745")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictingTypeDeclaration(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true" LanguageVersion="6">
<Document>< { }
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="Goo")
result.AssertLabeledSpansAre("ReplacementCInt", "C<int>.Goo(i, i);", RelatedLocationType.ResolvedReferenceConflict)
result.AssertLabeledSpansAre("ReplacementCString", "C<string>.Goo(s, s);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingToInvalidIdentifier(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|Invalid:$$Foo|}
{
{|Invalid:Foo|} foo;
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="`")
result.AssertLabeledSpansAre("Invalid", "`", RelatedLocationType.UnresolvedConflict)
result.AssertReplacementTextInvalid()
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingToInvalidIdentifier2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|Invalid:$$Foo|}
{
{|Invalid:Foo|} foo;
}
</Document>
</Project>
</Workspace>, host:=host,
renameTo:="!")
result.AssertLabeledSpansAre("Invalid", "!", RelatedLocationType.UnresolvedConflict)
result.AssertReplacementTextInvalid()
End Using
End Sub
<Theory>
<WorkItem(539636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539636")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingToConflictingMethodInvocation(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
static void F()
{
}
class Blah
{
void [|$$M|]()
{
{|Replacement:F|}();
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="F")
result.AssertLabeledSpansAre("Replacement", "Program.F();", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingToConflictingMethodInvocation2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void M()
{
int foo;
{|Replacement:Bar|}();
}
void [|$$Bar|]()
{
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="foo")
result.AssertLabeledSpansAre("Replacement", "this.foo();", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory>
<WorkItem(539733, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539733")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingTypeToConflictingMemberAndParentTypeName(host As RenameTestHost)
' It's important that we see conflicts for both simultaneously, so I do a single
' test for both cases.
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|Conflict:Foo|}
{
class [|$$Bar|]
{
int {|Conflict:Foo|};
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(539733, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539733")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingMemberToNameConflictingWithParent(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|Conflict:Foo|}
{
int [|$$Bar|];
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(540199, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540199")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingMemberToInvalidIdentifierName(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|Invalid:$$Foo|}
{
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo@")
result.AssertReplacementTextInvalid()
result.AssertLabeledSpansAre("Invalid", "Foo@", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MinimalQualificationOfBaseType1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class X
{
protected class [|$$A|] { }
}
class Y : X
{
private class C : {|Resolve:A|} { }
private class B { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="B")
result.AssertLabeledSpansAre("Resolve", "X.B", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MinimalQualificationOfBaseType2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class X
{
protected class A { }
}
class Y : X
{
private class C : {|Resolve:A|} { }
private class [|$$B|] { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="A")
result.AssertLabeledSpansAre("Resolve", "X.A", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542322")>
Public Sub EscapeIfKeywordWhenDoingTypeNameQualification(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
static class Foo
{
static void {|Escape:Method$$|}() { }
static void Test()
{
int @if;
{|Replacement:Method|}();
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="if")
result.AssertLabeledSpecialSpansAre("Escape", "@if", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Replacement", "Foo.@if();", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542322")>
Public Sub EscapeUnboundGenericTypesInTypeOfContext(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using C = A<int>;
class A<T>
{
public class B<S> { }
}
class Program
{
static void Main()
{
var type = typeof({|stmt1:C|}.B<>);
}
class [|D$$|] { }
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="C")
result.AssertLabeledSpansAre("stmt1", "var type = typeof(A<>.B<>);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542322")>
Public Sub EscapeUnboundGenericTypesInTypeOfContext2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using C = A<int>;
class A<T>
{
public class B<S>
{
public class E { }
}
}
class Program
{
static void Main()
{
var type = typeof({|Replacement:C|}.B<>.E);
}
class [|D$$|] { }
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="C")
result.AssertLabeledSpansAre("Replacement", "var type = typeof(A<>.B<>.E);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542322")>
Public Sub EscapeUnboundGenericTypesInTypeOfContext3(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using C = A<int>;
class A<T>
{
public class B<S>
{
public class E { }
}
}
class Program
{
static void Main()
{
var type = typeof({|Replacement:C|}.B<>.E);
}
class [|D$$|]
{
public class B<S>
{
public class E { }
}
}
}
]]></Document>
</Project>
</Workspace>, host:=host,
renameTo:="C")
result.AssertLabeledSpansAre("Replacement", "var type = typeof(A<>.B<>.E);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542651")>
Public Sub ReplaceAliasWithGenericTypeThatIncludesArrays(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using C = A<int[]>;
class A<T> { }
class Program
{
{|Resolve:C|} x;
class [|D$$|] { }
}
]]></Document>
</Project>
</Workspace>, host:=host,
renameTo:="C")
result.AssertLabeledSpansAre("Resolve", "A<int[]>", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542651")>
Public Sub ReplaceAliasWithGenericTypeThatIncludesPointers(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using C = A<int*>;
class A<T> { }
class Program
{
{|Resolve:C|} x;
class [|D$$|] { }
}
]]></Document>
</Project>
</Workspace>, host:=host,
renameTo:="C")
result.AssertLabeledSpansAre("Resolve", "A<int*>", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542651")>
Public Sub ReplaceAliasWithNestedGenericType(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using C = A<int>.E;
class A<T>
{
public class E { }
}
class B
{
{|Resolve:C|} x;
class [|D$$|] { } // Rename D to C
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="C")
result.AssertLabeledSpansAre("Resolve", "A<int>.E", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory()>
<WorkItem(535068, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535068")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542103")>
<WorkItem(8334, "https://github.com/dotnet/roslyn/issues/8334")>
Public Sub RewriteConflictingExtensionMethodCallSite(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
C Bar(int tag)
{
return this.{|stmt1:Foo|}(1).{|stmt1:Foo|}(2);
}
}
static class E
{
public static C [|$$Foo|](this C x, int tag) { return new C(); }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Bar")
result.AssertLabeledSpansAre("stmt1", "return E.Bar(E.Bar(this, 1), 2);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(535068, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535068")>
<WorkItem(528902, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528902")>
<WorkItem(645152, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/645152")>
<WorkItem(8334, "https://github.com/dotnet/roslyn/issues/8334")>
Public Sub RewriteConflictingExtensionMethodCallSiteWithReturnTypeChange(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void [|$$Bar|](int tag)
{
this.{|Resolved:Foo|}(1).{|Resolved:Foo|}(2);
}
}
static class E
{
public static C Foo(this C x, int tag) { return x; }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("Resolved", "E.Foo(E.Foo(this, 1), 2);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(535068, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535068")>
<WorkItem(542821, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542821")>
Public Sub RewriteConflictingExtensionMethodCallSiteRequiringTypeArguments(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class C
{
void [|$$Bar|]<T>()
{
{|Replacement:this.{|Resolved:Foo|}<int>()|};
}
}
static class E
{
public static void Foo<T>(this C x) { }
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("Resolved", type:=RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("Replacement", "E.Foo<int>(this)")
End Using
End Sub
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(535068, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535068")>
<WorkItem(542103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542103")>
Public Sub RewriteConflictingExtensionMethodCallSiteInferredTypeArguments(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class C
{
void [|$$Bar|]<T>(T y)
{
{|Replacement:this.{|Resolved:Foo|}(42)|};
}
}
static class E
{
public static void Foo<T>(this C x, T y) { }
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("Resolved", type:=RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("Replacement", "E.Foo(this, 42)")
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub DoNotDetectQueryContinuationNamedTheSame(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System.Linq;
class C
{
static void Main(string[] args)
{
var temp = from {|stmt1:$$x|} in "abc"
select {|stmt1:x|} into y
select y;
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="y")
' This may feel strange, but the "into" effectively splits scopes
' into two. There are no errors here.
result.AssertLabeledSpansAre("stmt1", "y", RelatedLocationType.NoConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(543027, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543027")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameHandlesUsingWithoutDeclaration(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System.IO;
class Program
{
public static void Main(string[] args)
{
Stream {|stmt1:$$s|} = new Stream();
using ({|stmt2:s|})
{
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="x")
result.AssertLabeledSpansAre("stmt1", "x", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", "x", RelatedLocationType.NoConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(543027, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543027")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameHandlesForWithoutDeclaration(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
public static void Main(string[] args)
{
int {|stmt1:$$i|};
for ({|stmt2:i|} = 0; ; )
{
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="x")
result.AssertLabeledSpansAre("stmt1", "x", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", "x", RelatedLocationType.NoConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameAttributeSuffix(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
[{|Special:Something|}()]
class Foo{ }
public class [|$$SomethingAttribute|] : Attribute
{
public [|SomethingAttribute|]() { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="SpecialAttribute")
result.AssertLabeledSpansAre("Special", "Special", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameAddAttributeSuffix(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
[[|Something|]()]
class Foo{ }
public class [|$$SomethingAttribute|] : Attribute
{
public [|SomethingAttribute|]() { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Special")
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameKeepAttributeSuffixOnUsages(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
[[|SomethingAttribute|]()]
class Foo { }
public class [|$$SomethingAttribute|] : Attribute
{
public [|SomethingAttribute|] { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="FooAttribute")
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameToConflictWithValue(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
class C
{
public int TestProperty
{
set
{
int [|$$x|];
[|x|] = {|Conflict:value|};
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="value")
' result.AssertLabeledSpansAre("stmt1", "value", RelatedLocationType.NoConflict)
' result.AssertLabeledSpansAre("stmt2", "value", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(543482, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543482")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameAttributeWithConflictingUse(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
class C
{
[Main()]
static void test() { }
}
class MainAttribute : System.Attribute
{
static void Main() { }
}
class [|$$Main|] : System.Attribute
{
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="FooAttribute")
End Using
End Sub
<Theory>
<WorkItem(542649, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542649")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub QualifyTypeWithGlobalWhenConflicting(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
class A { }
class B
{
{|Resolve:A|} x;
class [|$$C|] { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="A")
result.AssertLabeledSpansAre("Resolve", "global::A", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
End Class
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameSymbolDoesNotConflictWithNestedLocals(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class C
{
void Foo()
{
{ int x; }
{|Stmt1:Bar|}();
}
void [|$$Bar|]() { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="x")
result.AssertLabeledSpansAre("Stmt1", "x();", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameSymbolConflictWithLocals(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class C
{
void Foo()
{
int x;
{|Stmt1:Bar|}();
}
void [|$$Bar|]() { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="x")
result.AssertLabeledSpansAre("Stmt1", "this.x();", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(528738, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528738")>
Public Sub RenameAliasToCatchConflict(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using [|$$A|] = X.Something;
using {|Conflict:B|} = X.SomethingElse;
namespace X
{
class Something { }
class SomethingElse { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="B")
result.AssertLabeledSpansAre("Conflict", "B", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameAttributeToCreateConflict(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
[{|Escape:Main|}]
class Some
{
}
class SpecialAttribute : Attribute
{
}
class [|$$Main|] : Attribute // Rename 'Main' to 'Special'
{
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Special")
result.AssertLabeledSpecialSpansAre("Escape", "@Special", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameUsingToKeyword(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
using [|$$S|] = System.Collections;
[A]
class A : {|Resolve:Attribute|}
{
}
class B
{
[|S|].ArrayList a;
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Attribute")
result.AssertLabeledSpansAre("Resolve", "System.Attribute", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(16809, "http://vstfdevdiv:8080/DevDiv_Projects/Roslyn/_workitems/edit/16809")>
<WorkItem(535066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535066")>
Public Sub RenameInNestedClasses(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
namespace N
{
class A<T>
{
public virtual void Foo(T x) { }
class B<S> : A<B<S>>
{
class [|$$C|]<U> : B<{|Resolve1:C|}<U>> // Rename C to A
{
public override void Foo({|Resolve2:A|}<{|Resolve3:A|}<T>.B<S>>.B<{|Resolve4:A|}<T>.B<S>.{|Resolve1:C|}<U>> x) { }
}
}
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="A")
result.AssertLabeledSpansAre("Resolve1", "A", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Resolve2", "N.A<N.A<T>.B<S>>", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("Resolve3", "N.A<N.A<T>.B<S>>", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("Resolve4", "N.A<T>", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory()>
<WorkItem(535066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535066")>
<WorkItem(531433, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531433")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameAndEscapeContextualKeywordsInCSharp(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System.Linq;
class [|t$$o|] // Rename 'to' to 'from'
{
object q = from x in "" select new {|resolved:to|}();
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="from")
result.AssertLabeledSpansAre("resolved", "@from", RelatedLocationType.NoConflict)
End Using
End Sub
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(522774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/522774")>
Public Sub RenameCrefWithConflict(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
using F = N;
namespace N
{
interface I
{
void Foo();
}
}
class C
{
class E : {|Resolve:F|}.I
{
/// <summary>
/// This is a function <see cref="{|Resolve:F|}.I.Foo"/>
/// </summary>
public void Foo() { }
}
class [|$$K|]
{
}
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="F")
result.AssertLabeledSpansAre("Resolve", "N", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameClassContainingAlias(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
using C = A<int,int>;
class A<T,U>
{
public class B<S>
{
}
}
class [|$$B|]
{
{|Resolve:C|}.B<int> cb;
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="C")
result.AssertLabeledSpansAre("Resolve", "A<int, int>", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameFunctionWithOverloadConflict(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
class Bar
{
void Foo(int x) { }
void [|Boo|](object x) { }
void Some()
{
Foo(1);
{|Resolve:$$Boo|}(1);
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("Resolve", "Foo((object)1);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameActionWithFunctionConflict(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
class Program
{
static void doer(int x)
{
Console.WriteLine("Hey");
}
static void Main(string[] args)
{
Action<int> {|stmt1:$$action|} = delegate(int x) { Console.WriteLine(x); }; // Rename action to doer
{|stmt2:doer|}(3);
}
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="doer")
result.AssertLabeledSpansAre("stmt1", "doer", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", "Program.doer(3);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(552522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552522")>
Public Sub RenameFunctionNameToDelegateTypeConflict1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class A
{
static void [|Foo|]() { }
class B
{
delegate void Del();
void Boo()
{
Del d = new Del({|Stmt1:Foo|});
{|Stmt2:$$Foo|}();
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Del")
result.AssertLabeledSpansAre("Stmt1", "Del d = new Del(A.Del);", RelatedLocationType.ResolvedReferenceConflict)
result.AssertLabeledSpansAre("Stmt2", "Del", RelatedLocationType.NoConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(552520, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552520")>
Public Sub RenameFunctionNameToDelegateTypeConflict2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class A
{
static void [|$$Foo|]() { }
class B
{
delegate void Del();
void Bar() { }
void Boo()
{
Del d = new Del({|Stmt1:Foo|});
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Bar")
result.AssertLabeledSpansAre("Stmt1", "Del d = new Del(A.Bar);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameFunctionNameToDelegateTypeConflict3(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class A
{
delegate void Del(Del a);
static void [|Bar|](Del a) { }
class B
{
Del Boo = new Del({|decl1:Bar|});
void Foo()
{
Boo({|Stmt2:Bar|});
{|Stmt3:$$Bar|}(Boo);
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Boo")
result.AssertLabeledSpansAre("decl1", "new Del(A.Boo)", RelatedLocationType.ResolvedReferenceConflict)
result.AssertLabeledSpansAre("Stmt2", "Boo(A.Boo);", RelatedLocationType.ResolvedReferenceConflict)
result.AssertLabeledSpansAre("Stmt3", "A.Boo(Boo);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(552520, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552520")>
Public Sub RenameFunctionNameToDelegateTypeConflict4(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class A
{
static void Foo(int i) { }
static void Foo(string s) { }
class B
{
delegate void Del(string s);
void [|$$Bar|](string s) { }
void Boo()
{
Del d = new Del({|stmt1:Foo|});
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Del d = new Del(A.Foo);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(552722, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552722")>
Public Sub RenameActionTypeConflict(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
class A
{
static Action<int> [|$$Baz|] = (int x) => { };
class B
{
Action<int> Bar = (int x) => { };
void Foo()
{
{|Stmt1:Baz|}(3);
}
}
}]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Bar")
result.AssertLabeledSpansAre("Stmt1", "A.Bar(3);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(552722, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552722")>
Public Sub RenameConflictAttribute1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
[{|escape:Bar|}]
class Bar : System.Attribute
{ }
class [|$$FooAttribute|] : System.Attribute
{ }
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="BarAttribute")
result.AssertLabeledSpansAre("escape", "@Bar", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameConflictAttribute2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
[{|Resolve:B|}]
class [|$$BAttribute|] : Attribute
{
}
class AAttributeAttribute : Attribute
{
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="AAttribute")
result.AssertLabeledSpecialSpansAre("Resolve", "A", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<WorkItem(576573, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576573")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub Bug576573_ConflictAttributeWithNamespace(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
namespace X
{
class BAttribute
: System.Attribute
{ }
namespace Y.[|$$Z|]
{
[{|Resolve:B|}]
class Foo { }
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="BAttribute")
result.AssertLabeledSpansAre("Resolve", "X.B", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(579602, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579602")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub Bug579602_RenameFunctionWithDynamicParameter(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class A
{
class B
{
public void [|Boo|](int d) { } //Line 1
}
void Bar()
{
B b = new B();
dynamic d = 1.5f;
b.{|stmt1:$$Boo|}(d); //Line 2 Rename Boo to Foo
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo", RelatedLocationType.NoConflict)
End Using
End Sub
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub IdentifyConflictsWithVar(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class [|$$vor|]
{
static void Main(string[] args)
{
{|conflict:var|} x = 23;
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="v\u0061r")
result.AssertLabeledSpansAre("conflict", "var", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(633180, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633180")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub CS_DetectOverLoadResolutionChangesInEnclosingInvocations(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
static class C
{
static void Ex(this string x) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
static void Inner(Action<string> x, string y) { }
static void Inner(Action<string> x, int y) { }
static void Inner(Action<int> x, int y) { }
static void Main()
{
{|resolved:Outer|}(y => {|resolved:Inner|}(x => x.Ex(), y), 0);
}
}
static class E
{
public static void [|$$Ex|](this int x) { } // Rename Ex to Foo
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("resolved", "Outer((string y) => Inner(x => x.Ex(), y), 0);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(635622, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635622")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ExpandingDynamicAddsObjectCast(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class C
{
static void [|$$Foo|](int x, Action y) { } // Rename Foo to Bar
static void Bar(dynamic x, Action y) { }
static void Main()
{
{|resolve:Bar|}(1, Console.WriteLine);
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Bar")
result.AssertLabeledSpansAre("resolve", "Bar((object)1, Console.WriteLine);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(673562, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/673562")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameNamespaceConflictsAndResolves(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
namespace N
{
class C
{
{|resolve:N|}.C x;
/// <see cref="{|resolve:N|}.C"/>
void Sub()
{ }
}
namespace [|$$K|] // Rename K to N
{
class C
{ }
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="N")
result.AssertLabeledSpansAre("resolve", "global::N", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(673667, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/673667")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameUnnecessaryExpansion(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
namespace N
{
using K = {|stmt1:N|}.C;
class C
{
}
class [|$$D|] // Rename D to N
{
class C
{
[|D|] x;
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="N")
result.AssertLabeledSpansAre("stmt1", "global::N", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(768910, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768910")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameInCrefPreservesWhitespaceTrivia(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
<![CDATA[
public class A
{
public class B
{
public class C
{
}
/// <summary>
/// <see cref=" {|Resolve:D|}"/>
/// </summary>
public static void [|$$foo|]() // Rename foo to D
{
}
}
public class D
{
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="D")
result.AssertLabeledSpansAre("Resolve", "A.D", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
#Region "Type Argument Expand/Reduce for Generic Method Calls - 639136"
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class C
{
static void F<T>(Func<int, T> x) { }
static void [|$$B|](Func<int, int> x) { } // Rename Bar to Foo
static void Main()
{
{|stmt1:F|}(a => a);
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="F")
result.AssertLabeledSpansAre("stmt1", "F<int>(a => a);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<WorkItem(725934, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/725934")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_This(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class C
{
void TestMethod()
{
int x = 1;
Func<int> y = delegate { return {|stmt1:Foo|}(x); };
}
int Foo<T>(T x) { return 1; }
int [|$$Bar|](int x) { return 1; }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "return Foo<int>(x);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_Nested(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
public static void [|$$Foo|]<T>(T x) { }
public static void Bar(int x) { }
class D
{
void Bar<T>(T x) { }
void Bar(int x) { }
void sub()
{
{|stmt1:Foo|}(1);
}
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Bar")
result.AssertLabeledSpansAre("stmt1", "C.Bar<int>(1);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_ReferenceType(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< {return 1; } // Rename Bar to Foo
public void Test()
{
string one = "1";
{|stmt1:Foo|}(one);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<string>(one);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_ConstructedTypeArgumentNonGenericContainer(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { } // Rename Bar to Foo
public void Sub()
{
D<int> x = new D<int>();
{|stmt1:Foo|}(x);
}
}
class D<T>
{}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<D<int>>(x);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_SameTypeParameter(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System.Linq.Expressions;
class C
{
public static int Foo<T>(T x) { return 1; }
public static int [|$$Bar|]<T>(Expression<Func<int, T>> x) { return 1; }
Expression<Func<int, int>> x = (y) => Foo(1);
public void sub()
{
{|stmt1:Foo|}(x);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<Expression<Func<int, int>>>(x);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_ArrayTypeParameter(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
public void [|$$Foo|]<S>(S x) { }
public void Bar(int[] x) { }
public void Sub()
{
var x = new int[] { 1, 2, 3 };
{|stmt1:Foo|}(x);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Bar")
result.AssertLabeledSpansAre("stmt1", "Bar<int[]>(x);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_MultiDArrayTypeParameter(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { }
public void Sub()
{
var x = new int[,] { { 1, 2 }, { 2, 3 } };
{|stmt1:Foo|}(x);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<int[,]>(x);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_UsedAsArgument(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< {return 1; }
public void Sub(int x) { }
public void Test()
{
Sub({|stmt1:Foo|}(1));
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Sub(Foo<int>(1));", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_UsedInConstructorInitialization(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< {return 1; }
public void Test()
{
C c = new C({|stmt1:Foo|}(1));
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "C c = new C(Foo<int>(1));", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_CalledOnObject(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< {return 1; } // Rename Bar to Foo
public void Test()
{
C c = new C();
c.{|stmt1:Foo|}(1);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "c.Foo<int>(1);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_UsedInGenericDelegate(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< {return 1; } // Rename Bar to Foo
public void Test()
{
FooDel<int> foodel = new FooDel<int>({|stmt1:Foo|});
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "FooDel<int> foodel = new FooDel<int>(Foo<int>);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_UsedInNonGenericDelegate(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< {return 1; } // Rename Bar to Foo
public void Test()
{
FooDel foodel = new FooDel({|stmt1:Foo|});
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "FooDel foodel = new FooDel(Foo<int>);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_MultipleTypeParameters(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
public void Foo<T, S>(T x, S y) { }
public void [|$$Bar|]<U, P>(U[] x, P y) { }
public void Sub()
{
int[] x;
{|stmt1:Foo|}(x, new C());
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<int[], C>(x, new C());", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<WorkItem(730781, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730781")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_ConflictInDerived(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { }
public void Sub()
{
{|stmt1:Foo|}(1);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "base.Foo(1);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(728653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728653")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameGenericInvocationWithDynamicArgument(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { } // Rename Bar to F
public void sub()
{
dynamic x = 1;
{|stmt1:F|}(x);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="F")
result.AssertLabeledSpansAre("stmt1", "F", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(728646, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728646")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ExpandInvocationInStaticMemberAccess(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { } // Rename Bar to Foo
public void Sub()
{
}
}
class D
{
public void Sub()
{
C.{|stmt1:Foo|}(1);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "C.Foo<int>(1);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(728628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728628")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RecursiveTypeParameterExpansionFail(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { } // Rename Bar to Foo
public void Sub()
{
C<int> x = new C<int>();
{|stmt1:Foo|}(x);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<C<int>>(x);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(728575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728575")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameCrefWithProperBracesForTypeInferenceAdditionToMethod(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { } // Rename to Zoo
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Zoo")
result.AssertLabeledSpansAre("cref1", "Zoo{T}", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_GenericBase(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { } // Rename Bar to Foo
}
class D : C<int>
{
public void Test()
{
{|stmt1:Foo|}(1);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<int>(1);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<WpfTheory(Skip:="Story 736967"), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_InErrorCode(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< // Rename Bar to Foo
{
x = 1;
}
public void Test()
{
int y = 1;
int x;
{|stmt1:Foo|}(y, x); // error in code, but Foo is bound to Foo<T>
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<int>(y, x);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
#End Region
<WorkItem(1016652, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1016652")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub CS_ConflictBetweenTypeNamesInTypeConstraintSyntax(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System.Collections.Generic;
// rename INamespaceSymbol to ISymbol
public interface {|unresolved1:$$INamespaceSymbol|} { }
public interface {|DeclConflict:ISymbol|} { }
public interface IReferenceFinder { }
internal abstract partial class AbstractReferenceFinder<TSymbol> : IReferenceFinder
where TSymbol : {|unresolved2:INamespaceSymbol|}
{
}]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="ISymbol")
result.AssertLabeledSpansAre("DeclConflict", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("unresolved1", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("unresolved2", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(1193, "https://github.com/dotnet/roslyn/issues/1193")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MemberQualificationInNameOfUsesTypeName_StaticReferencingInstance(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
static void F(int [|$$z|])
{
string x = nameof({|ref:zoo|});
}
int zoo;
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="zoo")
result.AssertLabeledSpansAre("ref", "string x = nameof(C.zoo);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1193, "https://github.com/dotnet/roslyn/issues/1193")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MemberQualificationInNameOfUsesTypeName_InstanceReferencingStatic(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
void F(int [|$$z|])
{
string x = nameof({|ref:zoo|});
}
static int zoo;
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="zoo")
result.AssertLabeledSpansAre("ref", "string x = nameof(C.zoo);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1193, "https://github.com/dotnet/roslyn/issues/1193")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MemberQualificationInNameOfUsesTypeName_InstanceReferencingInstance(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
void F(int [|$$z|])
{
string x = nameof({|ref:zoo|});
}
int zoo;
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="zoo")
result.AssertLabeledSpansAre("ref", "string x = nameof(C.zoo);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1193, "https://github.com/dotnet/roslyn/issues/1193")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MemberQualificationInNameOfMethodInvocationUsesThisDot(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
int zoo;
void F(int [|$$z|])
{
string x = nameof({|ref:zoo|});
}
void nameof(int x) { }
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="zoo")
result.AssertLabeledSpansAre("ref", "string x = nameof(this.zoo);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1053, "https://github.com/dotnet/roslyn/issues/1053")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameComplexifiesInLambdaBodyExpression(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< => 5;
static int N(long b) => 5;
System.Func<int, int> a = d => {|resolved:N|}(1);
System.Func<int> b = () => {|resolved:N|}(1);
}]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="N")
result.AssertLabeledSpansAre("resolved", "N((long)1)", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1053, "https://github.com/dotnet/roslyn/issues/1053")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameComplexifiesInExpressionBodiedMembers(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< => {|resolved2:N|}(0);
int N(long b) => [|M|](0);
int P => {|resolved2:N|}(0);
}]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="N")
result.AssertLabeledSpansAre("resolved1", "new C().N((long)0)", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolved2", "N((long)0)", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestConflictBetweenClassAndInterface1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class {|conflict:C|} { }
interface [|$$I|] { }
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="C")
result.AssertLabeledSpansAre("conflict", "C", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
<WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestConflictBetweenClassAndInterface2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class [|$$C|] { }
interface {|conflict:I|} { }
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="I")
result.AssertLabeledSpansAre("conflict", "I", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
<WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestConflictBetweenClassAndNamespace1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class {|conflict:$$C|} { }
namespace N { }
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="N")
result.AssertLabeledSpansAre("conflict", "N", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
<WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestConflictBetweenClassAndNamespace1_FileScopedNamespace(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class {|conflict:$$C|} { }
namespace N;
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="N")
result.AssertLabeledSpansAre("conflict", "N", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
<WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestConflictBetweenClassAndNamespace2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class {|conflict:C|} { }
namespace [|$$N|] { }
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="C")
result.AssertLabeledSpansAre("conflict", "C", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
<WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestNoConflictBetweenTwoNamespaces(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
namespace [|$$N1|][ { }
namespace N2 { }
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="N2")
End Using
End Sub
<WorkItem(1729, "https://github.com/dotnet/roslyn/issues/1729")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestNoConflictWithParametersOrLocalsOfDelegateType(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
class C
{
void M1(Action [|callback$$|])
{
[|callback|]();
}
void M2(Func<bool> callback)
{
callback();
}
void M3()
{
Action callback = () => { };
callback();
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="callback2")
End Using
End Sub
<WorkItem(1729, "https://github.com/dotnet/roslyn/issues/1729")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestConflictWithLocalsOfDelegateTypeWhenBindingChangesToNonDelegateLocal(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
class C
{
void M()
{
int [|x$$|] = 7; // Rename x to a. "a()" will bind to the first definition of a.
Action {|conflict:a|} = () => { };
{|conflict:a|}();
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="a")
result.AssertLabeledSpansAre("conflict", "a", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(446, "https://github.com/dotnet/roslyn/issues/446")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub NoCrashOrConflictOnRenameWithNameOfInAttribute(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
static void [|T|]$$(int x) { }
[System.Obsolete(nameof(Test))]
static void Test() { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Test")
End Using
End Sub
<WorkItem(1195, "https://github.com/dotnet/roslyn/issues/1195")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictWhenNameOfReferenceDoesNotBindToAnyOriginalSymbols(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void Test()
{
int [|T$$|];
var x = nameof({|conflict:Test|});
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Test")
result.AssertLabeledSpansAre("conflict", "Test", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(1195, "https://github.com/dotnet/roslyn/issues/1195")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub NoConflictWhenNameOfReferenceDoesNotBindToSomeOriginalSymbols(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void [|$$M|](int x) { }
void M() { var x = nameof(M); }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="X")
End Using
End Sub
<WorkItem(1195, "https://github.com/dotnet/roslyn/issues/1195")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub NoConflictWhenNameOfReferenceBindsToSymbolForFirstTime(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void [|X$$|]() { }
void M() { var x = nameof(T); }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="T")
End Using
End Sub
<WorkItem(1195, "https://github.com/dotnet/roslyn/issues/1195")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictWhenNameOfReferenceChangesBindingFromMetadataToSource(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class Program
{
static void M()
{
var [|Consol$$|] = 7;
var x = nameof({|conflict:Console|});
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Console")
result.AssertLabeledSpansAre("conflict", "Console", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(1031, "https://github.com/dotnet/roslyn/issues/1031")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub InvalidNamesDoNotCauseCrash_IntroduceQualifiedName(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|conflict:C$$|} { }
</Document>
</Project>
</Workspace>, host:=host, renameTo:="C.D")
result.AssertReplacementTextInvalid()
result.AssertLabeledSpansAre("conflict", "C.D", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(1031, "https://github.com/dotnet/roslyn/issues/1031")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub InvalidNamesDoNotCauseCrash_AccidentallyPasteLotsOfCode(host As RenameTestHost)
Dim renameTo = "class C { public void M() { for (int i = 0; i < 10; i++) { System.Console.Writeline(""This is a test""); } } }"
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|conflict:C$$|} { }
</Document>
</Project>
</Workspace>, host:=host, renameTo:=renameTo)
result.AssertReplacementTextInvalid()
result.AssertLabeledSpansAre("conflict", renameTo, RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(2352, "https://github.com/dotnet/roslyn/issues/2352")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub DeclarationConflictInFileWithoutReferences_SameProject(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test1.cs">
class Program
{
internal void [|A$$|]() { }
internal void {|conflict:B|}() { }
}
</Document>
<Document FilePath="Test2.cs">
class Program2
{
void M()
{
Program p = null;
p.{|conflict:A|}();
p.{|conflict:B|}();
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="B")
result.AssertLabeledSpansAre("conflict", "B", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(2352, "https://github.com/dotnet/roslyn/issues/2352")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub DeclarationConflictInFileWithoutReferences_DifferentProjects(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSAssembly1">
<Document FilePath="Test1.cs">
public class Program
{
public void [|A$$|]() { }
public void {|conflict:B|}() { }
}
</Document>
</Project>
<Project Language="C#" CommonReferences="true" AssemblyName="CSAssembly2">
<ProjectReference>CSAssembly1</ProjectReference>
<Document FilePath="Test2.cs">
class Program2
{
void M()
{
Program p = null;
p.{|conflict:A|}();
p.{|conflict:B|}();
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="B")
result.AssertLabeledSpansAre("conflict", "B", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(2352, "https://github.com/dotnet/roslyn/issues/2352")>
<WorkItem(3303, "https://github.com/dotnet/roslyn/issues/3303")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub DeclarationConflictInFileWithoutReferences_PartialTypes(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test1.cs">
partial class C
{
private static void [|$$M|]()
{
{|conflict:M|}();
}
}
</Document>
<Document FilePath="Test2.cs">
partial class C
{
private static void {|conflict:Method|}()
{
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Method")
result.AssertLabeledSpansAre("conflict", "Method", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(1439, "https://github.com/dotnet/roslyn/issues/1439")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameInsideNameOf1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
int field;
static void Main(string[] args)
{
// Rename "local" to "field"
int [|$$local|];
nameof({|Conflict:field|}).ToString(); // Should also expand to Program.field
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="field")
result.AssertLabeledSpansAre("Conflict", replacement:="nameof(Program.field).ToString();", type:=RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1439, "https://github.com/dotnet/roslyn/issues/1439")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameInsideNameOf2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
int field;
static void Main(string[] args)
{
// Rename "local" to "field"
int [|$$local|];
nameof({|Conflict:field|})?.ToString(); // Should also expand to Program.field
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="field")
result.AssertLabeledSpansAre("Conflict", replacement:="nameof(Program.field)?.ToString();", type:=RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1439, "https://github.com/dotnet/roslyn/issues/1439")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameInsideNameOf3(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
static int field;
static void Main(string[] args)
{
// Rename "local" to "field"
int [|$$local|];
Program.nameof({|Conflict:field|}); // Should also expand to Program.field
}
static void nameof(string s) { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="field")
result.AssertLabeledSpansAre("Conflict", replacement:="Program.nameof(Program.field);", type:=RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(7440, "https://github.com/dotnet/roslyn/issues/7440")>
Public Sub RenameTypeParameterInPartialClass(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
partial class C<[|$$T|]> {}
partial class C<[|T|]> {}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="T2")
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(7440, "https://github.com/dotnet/roslyn/issues/7440")>
Public Sub RenameMethodToConflictWithTypeParameter(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
partial class C<{|Conflict:T|}> { void [|$$M|]() { } }
partial class C<{|Conflict:T|}> {}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="T")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(10469, "https://github.com/dotnet/roslyn/issues/10469")>
Public Sub RenameTypeToCurrent(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
partial class {|current:$$C|} { }
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Current")
result.AssertLabeledSpansAre("current", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(16567, "https://github.com/dotnet/roslyn/issues/16567")>
Public Sub RenameMethodToFinalizeWithDestructorPresent(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
~{|Conflict:C|}() { }
void $$[|M|]()
{
int x = 7;
int y = ~x;
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Finalize")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WpfTheory>
<WorkItem(5872, "https://github.com/dotnet/roslyn/issues/5872")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub CannotRenameToVar(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class $${|Conflict:X|} {
{|Conflict:X|}() {
var a = 2;
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="var")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WpfTheory>
<WorkItem(45677, "https://github.com/dotnet/roslyn/issues/45677")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictWhenRenamingPropertySetterLikeMethod(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public int MyProperty { get; {|conflict:set|}; }
private void {|conflict:$$_set_MyProperty|}(int value) => throw null;
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="set_MyProperty")
result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WpfTheory>
<WorkItem(45677, "https://github.com/dotnet/roslyn/issues/45677")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictWhenRenamingPropertyInitterLikeMethod(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public int MyProperty { get; {|conflict:init|}; }
private void {|conflict:$$_set_MyProperty|}(int value) => throw null;
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="set_MyProperty")
result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WpfTheory>
<WorkItem(45677, "https://github.com/dotnet/roslyn/issues/45677")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictWhenRenamingPropertyGetterLikeMethod(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public int MyProperty { {|conflict:get|}; set; }
private int {|conflict:$$_get_MyProperty|}() => throw null;
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="get_MyProperty")
result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
End Class
End Namespace
| 1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/CSharp/Portable/CodeGeneration/NamespaceGenerator.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers;
using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers;
namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration
{
internal static class NamespaceGenerator
{
public static BaseNamespaceDeclarationSyntax AddNamespaceTo(
ICodeGenerationService service,
BaseNamespaceDeclarationSyntax destination,
INamespaceSymbol @namespace,
CodeGenerationOptions options,
IList<bool> availableIndices,
CancellationToken cancellationToken)
{
var declaration = GenerateNamespaceDeclaration(service, @namespace, options, cancellationToken);
if (declaration is not BaseNamespaceDeclarationSyntax namespaceDeclaration)
throw new ArgumentException(CSharpWorkspaceResources.Namespace_can_not_be_added_in_this_destination);
var members = Insert(destination.Members, namespaceDeclaration, options, availableIndices);
return destination.WithMembers(members);
}
public static CompilationUnitSyntax AddNamespaceTo(
ICodeGenerationService service,
CompilationUnitSyntax destination,
INamespaceSymbol @namespace,
CodeGenerationOptions options,
IList<bool> availableIndices,
CancellationToken cancellationToken)
{
var declaration = GenerateNamespaceDeclaration(service, @namespace, options, cancellationToken);
if (declaration is not NamespaceDeclarationSyntax namespaceDeclaration)
throw new ArgumentException(CSharpWorkspaceResources.Namespace_can_not_be_added_in_this_destination);
var members = Insert(destination.Members, namespaceDeclaration, options, availableIndices);
return destination.WithMembers(members);
}
internal static SyntaxNode GenerateNamespaceDeclaration(
ICodeGenerationService service,
INamespaceSymbol @namespace,
CodeGenerationOptions options,
CancellationToken cancellationToken)
{
options ??= CodeGenerationOptions.Default;
GetNameAndInnermostNamespace(@namespace, options, out var name, out var innermostNamespace);
var declaration = GetDeclarationSyntaxWithoutMembers(@namespace, innermostNamespace, name, options);
declaration = options.GenerateMembers
? service.AddMembers(declaration, innermostNamespace.GetMembers(), options, cancellationToken)
: declaration;
return AddFormatterAndCodeGeneratorAnnotationsTo(declaration);
}
public static SyntaxNode UpdateCompilationUnitOrNamespaceDeclaration(
ICodeGenerationService service,
SyntaxNode declaration,
IList<ISymbol> newMembers,
CodeGenerationOptions options,
CancellationToken cancellationToken)
{
declaration = RemoveAllMembers(declaration);
declaration = service.AddMembers(declaration, newMembers, options, cancellationToken);
return AddFormatterAndCodeGeneratorAnnotationsTo(declaration);
}
private static SyntaxNode GenerateNamespaceDeclarationWorker(
string name, INamespaceSymbol innermostNamespace)
{
var usings = GenerateUsingDirectives(innermostNamespace);
// If they're just generating the empty namespace then make that into compilation unit.
if (name == string.Empty)
{
return SyntaxFactory.CompilationUnit().WithUsings(usings);
}
return SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(name)).WithUsings(usings);
}
private static SyntaxNode GetDeclarationSyntaxWithoutMembers(
INamespaceSymbol @namespace,
INamespaceSymbol innermostNamespace,
string name,
CodeGenerationOptions options)
{
var reusableSyntax = GetReuseableSyntaxNodeForSymbol<SyntaxNode>(@namespace, options);
if (reusableSyntax == null)
{
return GenerateNamespaceDeclarationWorker(name, innermostNamespace);
}
return RemoveAllMembers(reusableSyntax);
}
private static SyntaxNode RemoveAllMembers(SyntaxNode declaration)
=> declaration switch
{
CompilationUnitSyntax compilationUnit => compilationUnit.WithMembers(default),
BaseNamespaceDeclarationSyntax namespaceDeclaration => namespaceDeclaration.WithMembers(default),
_ => declaration,
};
private static SyntaxList<UsingDirectiveSyntax> GenerateUsingDirectives(INamespaceSymbol innermostNamespace)
{
var usingDirectives =
CodeGenerationNamespaceInfo.GetImports(innermostNamespace)
.Select(GenerateUsingDirective)
.WhereNotNull()
.ToList();
return usingDirectives.ToSyntaxList();
}
private static UsingDirectiveSyntax GenerateUsingDirective(ISymbol symbol)
{
if (symbol is IAliasSymbol alias)
{
var name = GenerateName(alias.Target);
if (name != null)
{
return SyntaxFactory.UsingDirective(
SyntaxFactory.NameEquals(alias.Name.ToIdentifierName()),
name);
}
}
else if (symbol is INamespaceOrTypeSymbol namespaceOrType)
{
var name = GenerateName(namespaceOrType);
if (name != null)
{
return SyntaxFactory.UsingDirective(name);
}
}
return null;
}
private static NameSyntax GenerateName(INamespaceOrTypeSymbol symbol)
{
if (symbol is ITypeSymbol type)
{
return type.GenerateTypeSyntax() as NameSyntax;
}
else
{
return SyntaxFactory.ParseName(symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat));
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers;
using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers;
namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration
{
internal static class NamespaceGenerator
{
public static BaseNamespaceDeclarationSyntax AddNamespaceTo(
ICodeGenerationService service,
BaseNamespaceDeclarationSyntax destination,
INamespaceSymbol @namespace,
CodeGenerationOptions options,
IList<bool> availableIndices,
CancellationToken cancellationToken)
{
var declaration = GenerateNamespaceDeclaration(service, @namespace, options, cancellationToken);
if (declaration is not BaseNamespaceDeclarationSyntax namespaceDeclaration)
throw new ArgumentException(CSharpWorkspaceResources.Namespace_can_not_be_added_in_this_destination);
var members = Insert(destination.Members, namespaceDeclaration, options, availableIndices);
return destination.WithMembers(members);
}
public static CompilationUnitSyntax AddNamespaceTo(
ICodeGenerationService service,
CompilationUnitSyntax destination,
INamespaceSymbol @namespace,
CodeGenerationOptions options,
IList<bool> availableIndices,
CancellationToken cancellationToken)
{
var declaration = GenerateNamespaceDeclaration(service, @namespace, options, cancellationToken);
if (declaration is not NamespaceDeclarationSyntax namespaceDeclaration)
throw new ArgumentException(CSharpWorkspaceResources.Namespace_can_not_be_added_in_this_destination);
var members = Insert(destination.Members, namespaceDeclaration, options, availableIndices);
return destination.WithMembers(members);
}
internal static SyntaxNode GenerateNamespaceDeclaration(
ICodeGenerationService service,
INamespaceSymbol @namespace,
CodeGenerationOptions options,
CancellationToken cancellationToken)
{
options ??= CodeGenerationOptions.Default;
GetNameAndInnermostNamespace(@namespace, options, out var name, out var innermostNamespace);
var declaration = GetDeclarationSyntaxWithoutMembers(@namespace, innermostNamespace, name, options);
declaration = options.GenerateMembers
? service.AddMembers(declaration, innermostNamespace.GetMembers(), options, cancellationToken)
: declaration;
return AddFormatterAndCodeGeneratorAnnotationsTo(declaration);
}
public static SyntaxNode UpdateCompilationUnitOrNamespaceDeclaration(
ICodeGenerationService service,
SyntaxNode declaration,
IList<ISymbol> newMembers,
CodeGenerationOptions options,
CancellationToken cancellationToken)
{
declaration = RemoveAllMembers(declaration);
declaration = service.AddMembers(declaration, newMembers, options, cancellationToken);
return AddFormatterAndCodeGeneratorAnnotationsTo(declaration);
}
private static SyntaxNode GenerateNamespaceDeclarationWorker(
string name, INamespaceSymbol innermostNamespace)
{
var usings = GenerateUsingDirectives(innermostNamespace);
// If they're just generating the empty namespace then make that into compilation unit.
if (name == string.Empty)
{
return SyntaxFactory.CompilationUnit().WithUsings(usings);
}
return SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(name)).WithUsings(usings);
}
private static SyntaxNode GetDeclarationSyntaxWithoutMembers(
INamespaceSymbol @namespace,
INamespaceSymbol innermostNamespace,
string name,
CodeGenerationOptions options)
{
var reusableSyntax = GetReuseableSyntaxNodeForSymbol<SyntaxNode>(@namespace, options);
if (reusableSyntax == null)
{
return GenerateNamespaceDeclarationWorker(name, innermostNamespace);
}
return RemoveAllMembers(reusableSyntax);
}
private static SyntaxNode RemoveAllMembers(SyntaxNode declaration)
=> declaration switch
{
CompilationUnitSyntax compilationUnit => compilationUnit.WithMembers(default),
BaseNamespaceDeclarationSyntax namespaceDeclaration => namespaceDeclaration.WithMembers(default),
_ => declaration,
};
private static SyntaxList<UsingDirectiveSyntax> GenerateUsingDirectives(INamespaceSymbol innermostNamespace)
{
var usingDirectives =
CodeGenerationNamespaceInfo.GetImports(innermostNamespace)
.Select(GenerateUsingDirective)
.WhereNotNull()
.ToList();
return usingDirectives.ToSyntaxList();
}
private static UsingDirectiveSyntax GenerateUsingDirective(ISymbol symbol)
{
if (symbol is IAliasSymbol alias)
{
var name = GenerateName(alias.Target);
if (name != null)
{
return SyntaxFactory.UsingDirective(
SyntaxFactory.NameEquals(alias.Name.ToIdentifierName()),
name);
}
}
else if (symbol is INamespaceOrTypeSymbol namespaceOrType)
{
var name = GenerateName(namespaceOrType);
if (name != null)
{
return SyntaxFactory.UsingDirective(name);
}
}
return null;
}
private static NameSyntax GenerateName(INamespaceOrTypeSymbol symbol)
{
if (symbol is ITypeSymbol type)
{
return type.GenerateTypeSyntax() as NameSyntax;
}
else
{
return SyntaxFactory.ParseName(symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat));
}
}
}
}
| 1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/CSharp/Portable/OrganizeImports/CSharpOrganizeImportsService.Rewriter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.OrganizeImports
{
internal partial class CSharpOrganizeImportsService
{
private class Rewriter : CSharpSyntaxRewriter
{
private readonly bool _placeSystemNamespaceFirst;
private readonly bool _separateGroups;
public readonly IList<TextChange> TextChanges = new List<TextChange>();
public Rewriter(bool placeSystemNamespaceFirst,
bool separateGroups)
{
_placeSystemNamespaceFirst = placeSystemNamespaceFirst;
_separateGroups = separateGroups;
}
public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node)
{
node = (CompilationUnitSyntax)base.VisitCompilationUnit(node)!;
UsingsAndExternAliasesOrganizer.Organize(
node.Externs, node.Usings,
_placeSystemNamespaceFirst, _separateGroups,
out var organizedExternAliasList, out var organizedUsingList);
var result = node.WithExterns(organizedExternAliasList).WithUsings(organizedUsingList);
if (node != result)
{
AddTextChange(node.Externs, organizedExternAliasList);
AddTextChange(node.Usings, organizedUsingList);
}
return result;
}
public override SyntaxNode VisitFileScopedNamespaceDeclaration(FileScopedNamespaceDeclarationSyntax node)
=> VisitBaseNamespaceDeclaration((BaseNamespaceDeclarationSyntax?)base.VisitFileScopedNamespaceDeclaration(node));
public override SyntaxNode VisitNamespaceDeclaration(NamespaceDeclarationSyntax node)
=> VisitBaseNamespaceDeclaration((BaseNamespaceDeclarationSyntax?)base.VisitNamespaceDeclaration(node));
private BaseNamespaceDeclarationSyntax VisitBaseNamespaceDeclaration(BaseNamespaceDeclarationSyntax? node)
{
Contract.ThrowIfNull(node);
UsingsAndExternAliasesOrganizer.Organize(
node.Externs, node.Usings,
_placeSystemNamespaceFirst, _separateGroups,
out var organizedExternAliasList, out var organizedUsingList);
var result = node.WithExterns(organizedExternAliasList).WithUsings(organizedUsingList);
if (node != result)
{
AddTextChange(node.Externs, organizedExternAliasList);
AddTextChange(node.Usings, organizedUsingList);
}
return result;
}
private void AddTextChange<TSyntax>(SyntaxList<TSyntax> list, SyntaxList<TSyntax> organizedList)
where TSyntax : SyntaxNode
{
if (list.Count > 0)
this.TextChanges.Add(new TextChange(GetTextSpan(list), GetNewText(organizedList)));
}
private static string GetNewText<TSyntax>(SyntaxList<TSyntax> organizedList) where TSyntax : SyntaxNode
=> string.Join(string.Empty, organizedList.Select(t => t.ToFullString()));
private static TextSpan GetTextSpan<TSyntax>(SyntaxList<TSyntax> list) where TSyntax : SyntaxNode
=> TextSpan.FromBounds(list.First().FullSpan.Start, list.Last().FullSpan.End);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.OrganizeImports
{
internal partial class CSharpOrganizeImportsService
{
private class Rewriter : CSharpSyntaxRewriter
{
private readonly bool _placeSystemNamespaceFirst;
private readonly bool _separateGroups;
public readonly IList<TextChange> TextChanges = new List<TextChange>();
public Rewriter(bool placeSystemNamespaceFirst,
bool separateGroups)
{
_placeSystemNamespaceFirst = placeSystemNamespaceFirst;
_separateGroups = separateGroups;
}
public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node)
{
node = (CompilationUnitSyntax)base.VisitCompilationUnit(node)!;
UsingsAndExternAliasesOrganizer.Organize(
node.Externs, node.Usings,
_placeSystemNamespaceFirst, _separateGroups,
out var organizedExternAliasList, out var organizedUsingList);
var result = node.WithExterns(organizedExternAliasList).WithUsings(organizedUsingList);
if (node != result)
{
AddTextChange(node.Externs, organizedExternAliasList);
AddTextChange(node.Usings, organizedUsingList);
}
return result;
}
public override SyntaxNode VisitFileScopedNamespaceDeclaration(FileScopedNamespaceDeclarationSyntax node)
=> VisitBaseNamespaceDeclaration((BaseNamespaceDeclarationSyntax?)base.VisitFileScopedNamespaceDeclaration(node));
public override SyntaxNode VisitNamespaceDeclaration(NamespaceDeclarationSyntax node)
=> VisitBaseNamespaceDeclaration((BaseNamespaceDeclarationSyntax?)base.VisitNamespaceDeclaration(node));
private BaseNamespaceDeclarationSyntax VisitBaseNamespaceDeclaration(BaseNamespaceDeclarationSyntax? node)
{
Contract.ThrowIfNull(node);
UsingsAndExternAliasesOrganizer.Organize(
node.Externs, node.Usings,
_placeSystemNamespaceFirst, _separateGroups,
out var organizedExternAliasList, out var organizedUsingList);
var result = node.WithExterns(organizedExternAliasList).WithUsings(organizedUsingList);
if (node != result)
{
AddTextChange(node.Externs, organizedExternAliasList);
AddTextChange(node.Usings, organizedUsingList);
}
return result;
}
private void AddTextChange<TSyntax>(SyntaxList<TSyntax> list, SyntaxList<TSyntax> organizedList)
where TSyntax : SyntaxNode
{
if (list.Count > 0)
this.TextChanges.Add(new TextChange(GetTextSpan(list), GetNewText(organizedList)));
}
private static string GetNewText<TSyntax>(SyntaxList<TSyntax> organizedList) where TSyntax : SyntaxNode
=> string.Join(string.Empty, organizedList.Select(t => t.ToFullString()));
private static TextSpan GetTextSpan<TSyntax>(SyntaxList<TSyntax> list) where TSyntax : SyntaxNode
=> TextSpan.FromBounds(list.First().FullSpan.Start, list.Last().FullSpan.End);
}
}
}
| 1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/CSharp/Portable/Recommendations/CSharpRecommendationServiceRunner.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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 System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Recommendations;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Recommendations
{
internal partial class CSharpRecommendationServiceRunner : AbstractRecommendationServiceRunner<CSharpSyntaxContext>
{
public CSharpRecommendationServiceRunner(
CSharpSyntaxContext context, bool filterOutOfScopeLocals, CancellationToken cancellationToken)
: base(context, filterOutOfScopeLocals, cancellationToken)
{
}
public override RecommendedSymbols GetRecommendedSymbols()
{
if (_context.IsInNonUserCode ||
_context.IsPreProcessorDirectiveContext)
{
return default;
}
if (!_context.IsRightOfNameSeparator)
return new RecommendedSymbols(GetSymbolsForCurrentContext());
return GetSymbolsOffOfContainer();
}
public override bool TryGetExplicitTypeOfLambdaParameter(SyntaxNode lambdaSyntax, int ordinalInLambda, [NotNullWhen(true)] out ITypeSymbol? explicitLambdaParameterType)
{
if (lambdaSyntax.IsKind<ParenthesizedLambdaExpressionSyntax>(SyntaxKind.ParenthesizedLambdaExpression, out var parenthesizedLambdaSyntax))
{
var parameters = parenthesizedLambdaSyntax.ParameterList.Parameters;
if (parameters.Count > ordinalInLambda)
{
var parameter = parameters[ordinalInLambda];
if (parameter.Type != null)
{
explicitLambdaParameterType = _context.SemanticModel.GetTypeInfo(parameter.Type, _cancellationToken).Type;
return explicitLambdaParameterType != null;
}
}
}
// Non-parenthesized lambdas cannot explicitly specify the type of the single parameter
explicitLambdaParameterType = null;
return false;
}
private ImmutableArray<ISymbol> GetSymbolsForCurrentContext()
{
if (_context.IsGlobalStatementContext)
{
// Script and interactive
return GetSymbolsForGlobalStatementContext();
}
else if (_context.IsAnyExpressionContext ||
_context.IsStatementContext ||
_context.SyntaxTree.IsDefiniteCastTypeContext(_context.Position, _context.LeftToken))
{
// GitHub #717: With automatic brace completion active, typing '(i' produces "(i)", which gets parsed as
// as cast. The user might be trying to type a parenthesized expression, so even though a cast
// is a type-only context, we'll show all symbols anyway.
return GetSymbolsForExpressionOrStatementContext();
}
else if (_context.IsTypeContext || _context.IsNamespaceContext)
{
return GetSymbolsForTypeOrNamespaceContext();
}
else if (_context.IsLabelContext)
{
return GetSymbolsForLabelContext();
}
else if (_context.IsTypeArgumentOfConstraintContext)
{
return GetSymbolsForTypeArgumentOfConstraintClause();
}
else if (_context.IsDestructorTypeContext)
{
var symbol = _context.SemanticModel.GetDeclaredSymbol(_context.ContainingTypeOrEnumDeclaration!, _cancellationToken);
return symbol == null ? ImmutableArray<ISymbol>.Empty : ImmutableArray.Create<ISymbol>(symbol);
}
else if (_context.IsNamespaceDeclarationNameContext)
{
return GetSymbolsForNamespaceDeclarationNameContext<BaseNamespaceDeclarationSyntax>();
}
return ImmutableArray<ISymbol>.Empty;
}
private RecommendedSymbols GetSymbolsOffOfContainer()
{
// Ensure that we have the correct token in A.B| case
var node = _context.TargetToken.GetRequiredParent();
return node switch
{
MemberAccessExpressionSyntax(SyntaxKind.SimpleMemberAccessExpression) memberAccess
=> GetSymbolsOffOfExpression(memberAccess.Expression),
MemberAccessExpressionSyntax(SyntaxKind.PointerMemberAccessExpression) memberAccess
=> GetSymbolsOffOfDereferencedExpression(memberAccess.Expression),
// This code should be executing only if the cursor is between two dots in a dotdot token.
RangeExpressionSyntax rangeExpression => GetSymbolsOffOfExpression(rangeExpression.LeftOperand),
QualifiedNameSyntax qualifiedName => GetSymbolsOffOfName(qualifiedName.Left),
AliasQualifiedNameSyntax aliasName => GetSymbolsOffOffAlias(aliasName.Alias),
MemberBindingExpressionSyntax _ => GetSymbolsOffOfConditionalReceiver(node.GetParentConditionalAccessExpression()!.Expression),
_ => default,
};
}
private ImmutableArray<ISymbol> GetSymbolsForGlobalStatementContext()
{
var syntaxTree = _context.SyntaxTree;
var position = _context.Position;
var token = _context.LeftToken;
// The following code is a hack to get around a binding problem when asking binding
// questions immediately after a using directive. This is special-cased in the binder
// factory to ensure that using directives are not within scope inside other using
// directives. That generally works fine for .cs, but it's a problem for interactive
// code in this case:
//
// using System;
// |
if (token.Kind() == SyntaxKind.SemicolonToken &&
token.Parent.IsKind(SyntaxKind.UsingDirective) &&
position >= token.Span.End)
{
var compUnit = (CompilationUnitSyntax)syntaxTree.GetRoot(_cancellationToken);
if (compUnit.Usings.Count > 0 && compUnit.Usings.Last().GetLastToken() == token)
{
token = token.GetNextToken(includeZeroWidth: true);
}
}
var symbols = _context.SemanticModel.LookupSymbols(token.SpanStart);
return symbols;
}
private ImmutableArray<ISymbol> GetSymbolsForTypeArgumentOfConstraintClause()
{
var enclosingSymbol = _context.LeftToken.GetRequiredParent()
.AncestorsAndSelf()
.Select(n => _context.SemanticModel.GetDeclaredSymbol(n, _cancellationToken))
.WhereNotNull()
.FirstOrDefault();
var symbols = enclosingSymbol != null
? enclosingSymbol.GetTypeArguments()
: ImmutableArray<ITypeSymbol>.Empty;
return ImmutableArray<ISymbol>.CastUp(symbols);
}
private RecommendedSymbols GetSymbolsOffOffAlias(IdentifierNameSyntax alias)
{
var aliasSymbol = _context.SemanticModel.GetAliasInfo(alias, _cancellationToken);
if (aliasSymbol == null)
return default;
return new RecommendedSymbols(_context.SemanticModel.LookupNamespacesAndTypes(
alias.SpanStart,
aliasSymbol.Target));
}
private ImmutableArray<ISymbol> GetSymbolsForLabelContext()
{
var allLabels = _context.SemanticModel.LookupLabels(_context.LeftToken.SpanStart);
// Exclude labels (other than 'default') that come from case switch statements
return allLabels
.WhereAsArray(label => label.DeclaringSyntaxReferences.First().GetSyntax(_cancellationToken)
.IsKind(SyntaxKind.LabeledStatement, SyntaxKind.DefaultSwitchLabel));
}
private ImmutableArray<ISymbol> GetSymbolsForTypeOrNamespaceContext()
{
var symbols = _context.SemanticModel.LookupNamespacesAndTypes(_context.LeftToken.SpanStart);
if (_context.TargetToken.IsUsingKeywordInUsingDirective())
{
return symbols.WhereAsArray(s => s.IsNamespace());
}
if (_context.TargetToken.IsStaticKeywordInUsingDirective())
{
return symbols.WhereAsArray(s => !s.IsDelegateType() && !s.IsInterfaceType());
}
return symbols;
}
private ImmutableArray<ISymbol> GetSymbolsForExpressionOrStatementContext()
{
// Check if we're in an interesting situation like this:
//
// i // <-- here
// I = 0;
// The problem is that "i I = 0" causes a local to be in scope called "I". So, later when
// we look up symbols, it masks any other 'I's in scope (i.e. if there's a field with that
// name). If this is the case, we do not want to filter out inaccessible locals.
var filterOutOfScopeLocals = _filterOutOfScopeLocals;
if (filterOutOfScopeLocals)
filterOutOfScopeLocals = !_context.LeftToken.GetRequiredParent().IsFoundUnder<LocalDeclarationStatementSyntax>(d => d.Declaration.Type);
var symbols = !_context.IsNameOfContext && _context.LeftToken.GetRequiredParent().IsInStaticContext()
? _context.SemanticModel.LookupStaticMembers(_context.LeftToken.SpanStart)
: _context.SemanticModel.LookupSymbols(_context.LeftToken.SpanStart);
// Filter out any extension methods that might be imported by a using static directive.
// But include extension methods declared in the context's type or it's parents
var contextOuterTypes = _context.GetOuterTypes(_cancellationToken);
var contextEnclosingNamedType = _context.SemanticModel.GetEnclosingNamedType(_context.Position, _cancellationToken);
symbols = symbols.WhereAsArray(symbol =>
!symbol.IsExtensionMethod() ||
Equals(contextEnclosingNamedType, symbol.ContainingType) ||
contextOuterTypes.Any(outerType => outerType.Equals(symbol.ContainingType)));
// The symbols may include local variables that are declared later in the method and
// should not be included in the completion list, so remove those. Filter them away,
// unless we're in the debugger, where we show all locals in scope.
if (filterOutOfScopeLocals)
{
symbols = symbols.WhereAsArray(symbol => !symbol.IsInaccessibleLocal(_context.Position));
}
return symbols;
}
private RecommendedSymbols GetSymbolsOffOfName(NameSyntax name)
{
// Using an is pattern on an enum is a qualified name, but normal symbol processing works fine
if (_context.IsEnumTypeMemberAccessContext)
return GetSymbolsOffOfExpression(name);
if (ShouldBeTreatedAsTypeInsteadOfExpression(name, out var nameBinding, out var container))
return GetSymbolsOffOfBoundExpression(name, name, nameBinding, container, unwrapNullable: false);
// We're in a name-only context, since if we were an expression we'd be a
// MemberAccessExpressionSyntax. Thus, let's do other namespaces and types.
nameBinding = _context.SemanticModel.GetSymbolInfo(name, _cancellationToken);
if (nameBinding.Symbol is not INamespaceOrTypeSymbol symbol)
return default;
if (_context.IsNameOfContext)
return new RecommendedSymbols(_context.SemanticModel.LookupSymbols(position: name.SpanStart, container: symbol));
var symbols = _context.SemanticModel.LookupNamespacesAndTypes(
position: name.SpanStart,
container: symbol);
if (_context.IsNamespaceDeclarationNameContext)
{
var declarationSyntax = name.GetAncestorOrThis<BaseNamespaceDeclarationSyntax>();
return new RecommendedSymbols(symbols.WhereAsArray(s => IsNonIntersectingNamespace(s, declarationSyntax)));
}
// Filter the types when in a using directive, but not an alias.
//
// Cases:
// using | -- Show namespaces
// using A.| -- Show namespaces
// using static | -- Show namespace and types
// using A = B.| -- Show namespace and types
var usingDirective = name.GetAncestorOrThis<UsingDirectiveSyntax>();
if (usingDirective != null && usingDirective.Alias == null)
{
return new RecommendedSymbols(usingDirective.StaticKeyword.IsKind(SyntaxKind.StaticKeyword)
? symbols.WhereAsArray(s => !s.IsDelegateType() && !s.IsInterfaceType())
: symbols.WhereAsArray(s => s.IsNamespace()));
}
return new RecommendedSymbols(symbols);
}
/// <summary>
/// DeterminesCheck if we're in an interesting situation like this:
/// <code>
/// int i = 5;
/// i. // -- here
/// List ml = new List();
/// </code>
/// The problem is that "i.List" gets parsed as a type. In this case we need to try binding again as if "i" is
/// an expression and not a type. In order to do that, we need to speculate as to what 'i' meant if it wasn't
/// part of a local declaration's type.
/// <para/>
/// Another interesting case is something like:
/// <code>
/// stringList.
/// await Test2();
/// </code>
/// Here "stringList.await" is thought of as the return type of a local function.
/// </summary>
private bool ShouldBeTreatedAsTypeInsteadOfExpression(
ExpressionSyntax name,
out SymbolInfo leftHandBinding,
out ITypeSymbol? container)
{
if (name.IsFoundUnder<LocalFunctionStatementSyntax>(d => d.ReturnType) ||
name.IsFoundUnder<LocalDeclarationStatementSyntax>(d => d.Declaration.Type) ||
name.IsFoundUnder<FieldDeclarationSyntax>(d => d.Declaration.Type))
{
leftHandBinding = _context.SemanticModel.GetSpeculativeSymbolInfo(
name.SpanStart, name, SpeculativeBindingOption.BindAsExpression);
container = _context.SemanticModel.GetSpeculativeTypeInfo(
name.SpanStart, name, SpeculativeBindingOption.BindAsExpression).Type;
return true;
}
leftHandBinding = default;
container = null;
return false;
}
private RecommendedSymbols GetSymbolsOffOfExpression(ExpressionSyntax? originalExpression)
{
if (originalExpression == null)
return default;
// In case of 'await x$$', we want to move to 'x' to get it's members.
// To run GetSymbolInfo, we also need to get rid of parenthesis.
var expression = originalExpression is AwaitExpressionSyntax awaitExpression
? awaitExpression.Expression.WalkDownParentheses()
: originalExpression.WalkDownParentheses();
var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken);
var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type;
var result = GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: false);
// Check for the Color Color case.
if (originalExpression.CanAccessInstanceAndStaticMembersOffOf(_context.SemanticModel, _cancellationToken))
{
var speculativeSymbolInfo = _context.SemanticModel.GetSpeculativeSymbolInfo(expression.SpanStart, expression, SpeculativeBindingOption.BindAsTypeOrNamespace);
var typeMembers = GetSymbolsOffOfBoundExpression(originalExpression, expression, speculativeSymbolInfo, container, unwrapNullable: false);
result = new RecommendedSymbols(
result.NamedSymbols.Concat(typeMembers.NamedSymbols),
result.UnnamedSymbols);
}
return result;
}
private RecommendedSymbols GetSymbolsOffOfDereferencedExpression(ExpressionSyntax originalExpression)
{
var expression = originalExpression.WalkDownParentheses();
var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken);
var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type;
if (container is IPointerTypeSymbol pointerType)
{
container = pointerType.PointedAtType;
}
return GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: false);
}
private RecommendedSymbols GetSymbolsOffOfConditionalReceiver(ExpressionSyntax originalExpression)
{
// Given ((T?)t)?.|, the '.' will behave as if the expression was actually ((T)t).|. More plainly,
// a member access off of a conditional receiver of nullable type binds to the unwrapped nullable
// type. This is not exposed via the binding information for the LHS, so repeat this work here.
var expression = originalExpression.WalkDownParentheses();
var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken);
var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type;
// If the thing on the left is a type, namespace, or alias, we shouldn't show anything in
// IntelliSense.
if (leftHandBinding.GetBestOrAllSymbols().FirstOrDefault().MatchesKind(SymbolKind.NamedType, SymbolKind.Namespace, SymbolKind.Alias))
return default;
return GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: true);
}
private RecommendedSymbols GetSymbolsOffOfBoundExpression(
ExpressionSyntax originalExpression,
ExpressionSyntax expression,
SymbolInfo leftHandBinding,
ITypeSymbol? containerType,
bool unwrapNullable)
{
var abstractsOnly = false;
var excludeInstance = false;
var excludeStatic = true;
ISymbol? containerSymbol = containerType;
var symbol = leftHandBinding.GetAnySymbol();
if (symbol != null)
{
// If the thing on the left is a lambda expression, we shouldn't show anything.
if (symbol is IMethodSymbol { MethodKind: MethodKind.AnonymousFunction })
return default;
var originalExpressionKind = originalExpression.Kind();
// If the thing on the left is a type, namespace or alias and the original
// expression was parenthesized, we shouldn't show anything in IntelliSense.
if (originalExpressionKind is SyntaxKind.ParenthesizedExpression &&
symbol.Kind is SymbolKind.NamedType or SymbolKind.Namespace or SymbolKind.Alias)
{
return default;
}
// If the thing on the left is a method name identifier, we shouldn't show anything.
if (symbol.Kind is SymbolKind.Method &&
originalExpressionKind is SyntaxKind.IdentifierName or SyntaxKind.GenericName)
{
return default;
}
// If the thing on the left is an event that can't be used as a field, we shouldn't show anything
if (symbol is IEventSymbol ev &&
!_context.SemanticModel.IsEventUsableAsField(originalExpression.SpanStart, ev))
{
return default;
}
if (symbol is IAliasSymbol alias)
symbol = alias.Target;
if (symbol.Kind is SymbolKind.NamedType or SymbolKind.Namespace or SymbolKind.TypeParameter)
{
// For named typed, namespaces, and type parameters (potentially constrainted to interface with statics), we flip things around.
// We only want statics and not instance members.
excludeInstance = true;
excludeStatic = false;
abstractsOnly = symbol.Kind == SymbolKind.TypeParameter;
containerSymbol = symbol;
}
// Special case parameters. If we have a normal (non this/base) parameter, then that's what we want to
// lookup symbols off of as we have a lot of special logic for determining member symbols of lambda
// parameters.
//
// If it is a this/base parameter and we're in a static context, we shouldn't show anything
if (symbol is IParameterSymbol parameter)
{
if (parameter.IsThis && expression.IsInStaticContext())
return default;
containerSymbol = symbol;
}
}
else if (containerType != null)
{
// Otherwise, if it wasn't a symbol on the left, but it was something that had a type,
// then include instance members for it.
excludeStatic = true;
}
if (containerSymbol == null)
return default;
Debug.Assert(!excludeInstance || !excludeStatic);
Debug.Assert(!abstractsOnly || (abstractsOnly && !excludeStatic && excludeInstance));
// nameof(X.|
// Show static and instance members.
if (_context.IsNameOfContext)
{
excludeInstance = false;
excludeStatic = false;
}
var useBaseReferenceAccessibility = symbol is IParameterSymbol { IsThis: true } p && !p.Type.Equals(containerType);
var symbols = GetMemberSymbols(containerSymbol, position: originalExpression.SpanStart, excludeInstance, useBaseReferenceAccessibility, unwrapNullable);
// If we're showing instance members, don't include nested types
var namedSymbols = excludeStatic
? symbols.WhereAsArray(s => !(s.IsStatic || s is ITypeSymbol))
: (abstractsOnly ? symbols.WhereAsArray(s => s.IsAbstract) : symbols);
// if we're dotting off an instance, then add potential operators/indexers/conversions that may be
// applicable to it as well.
var unnamedSymbols = _context.IsNameOfContext || excludeInstance
? default
: GetUnnamedSymbols(originalExpression);
return new RecommendedSymbols(namedSymbols, unnamedSymbols);
}
private ImmutableArray<ISymbol> GetUnnamedSymbols(ExpressionSyntax originalExpression)
{
var semanticModel = _context.SemanticModel;
var container = GetContainerForUnnamedSymbols(semanticModel, originalExpression);
if (container == null)
return ImmutableArray<ISymbol>.Empty;
// In a case like `x?.Y` if we bind the type of `.Y` we will get a value type back (like `int`), and not
// `int?`. However, we want to think of the constructed type as that's the type of the overall expression
// that will be casted.
if (originalExpression.GetRootConditionalAccessExpression() != null)
container = TryMakeNullable(semanticModel.Compilation, container);
using var _ = ArrayBuilder<ISymbol>.GetInstance(out var symbols);
AddIndexers(container, symbols);
AddOperators(container, symbols);
AddConversions(container, symbols);
return symbols.ToImmutable();
}
private ITypeSymbol? GetContainerForUnnamedSymbols(SemanticModel semanticModel, ExpressionSyntax originalExpression)
{
return ShouldBeTreatedAsTypeInsteadOfExpression(originalExpression, out _, out var container)
? container
: semanticModel.GetTypeInfo(originalExpression, _cancellationToken).Type;
}
private void AddIndexers(ITypeSymbol container, ArrayBuilder<ISymbol> symbols)
{
var containingType = _context.SemanticModel.GetEnclosingNamedType(_context.Position, _cancellationToken);
if (containingType == null)
return;
foreach (var member in container.RemoveNullableIfPresent().GetAccessibleMembersInThisAndBaseTypes<IPropertySymbol>(containingType))
{
if (member.IsIndexer)
symbols.Add(member);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Recommendations;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Recommendations
{
internal partial class CSharpRecommendationServiceRunner : AbstractRecommendationServiceRunner<CSharpSyntaxContext>
{
public CSharpRecommendationServiceRunner(
CSharpSyntaxContext context, bool filterOutOfScopeLocals, CancellationToken cancellationToken)
: base(context, filterOutOfScopeLocals, cancellationToken)
{
}
public override RecommendedSymbols GetRecommendedSymbols()
{
if (_context.IsInNonUserCode ||
_context.IsPreProcessorDirectiveContext)
{
return default;
}
if (!_context.IsRightOfNameSeparator)
return new RecommendedSymbols(GetSymbolsForCurrentContext());
return GetSymbolsOffOfContainer();
}
public override bool TryGetExplicitTypeOfLambdaParameter(SyntaxNode lambdaSyntax, int ordinalInLambda, [NotNullWhen(true)] out ITypeSymbol? explicitLambdaParameterType)
{
if (lambdaSyntax.IsKind<ParenthesizedLambdaExpressionSyntax>(SyntaxKind.ParenthesizedLambdaExpression, out var parenthesizedLambdaSyntax))
{
var parameters = parenthesizedLambdaSyntax.ParameterList.Parameters;
if (parameters.Count > ordinalInLambda)
{
var parameter = parameters[ordinalInLambda];
if (parameter.Type != null)
{
explicitLambdaParameterType = _context.SemanticModel.GetTypeInfo(parameter.Type, _cancellationToken).Type;
return explicitLambdaParameterType != null;
}
}
}
// Non-parenthesized lambdas cannot explicitly specify the type of the single parameter
explicitLambdaParameterType = null;
return false;
}
private ImmutableArray<ISymbol> GetSymbolsForCurrentContext()
{
if (_context.IsGlobalStatementContext)
{
// Script and interactive
return GetSymbolsForGlobalStatementContext();
}
else if (_context.IsAnyExpressionContext ||
_context.IsStatementContext ||
_context.SyntaxTree.IsDefiniteCastTypeContext(_context.Position, _context.LeftToken))
{
// GitHub #717: With automatic brace completion active, typing '(i' produces "(i)", which gets parsed as
// as cast. The user might be trying to type a parenthesized expression, so even though a cast
// is a type-only context, we'll show all symbols anyway.
return GetSymbolsForExpressionOrStatementContext();
}
else if (_context.IsTypeContext || _context.IsNamespaceContext)
{
return GetSymbolsForTypeOrNamespaceContext();
}
else if (_context.IsLabelContext)
{
return GetSymbolsForLabelContext();
}
else if (_context.IsTypeArgumentOfConstraintContext)
{
return GetSymbolsForTypeArgumentOfConstraintClause();
}
else if (_context.IsDestructorTypeContext)
{
var symbol = _context.SemanticModel.GetDeclaredSymbol(_context.ContainingTypeOrEnumDeclaration!, _cancellationToken);
return symbol == null ? ImmutableArray<ISymbol>.Empty : ImmutableArray.Create<ISymbol>(symbol);
}
else if (_context.IsNamespaceDeclarationNameContext)
{
return GetSymbolsForNamespaceDeclarationNameContext<BaseNamespaceDeclarationSyntax>();
}
return ImmutableArray<ISymbol>.Empty;
}
private RecommendedSymbols GetSymbolsOffOfContainer()
{
// Ensure that we have the correct token in A.B| case
var node = _context.TargetToken.GetRequiredParent();
return node switch
{
MemberAccessExpressionSyntax(SyntaxKind.SimpleMemberAccessExpression) memberAccess
=> GetSymbolsOffOfExpression(memberAccess.Expression),
MemberAccessExpressionSyntax(SyntaxKind.PointerMemberAccessExpression) memberAccess
=> GetSymbolsOffOfDereferencedExpression(memberAccess.Expression),
// This code should be executing only if the cursor is between two dots in a dotdot token.
RangeExpressionSyntax rangeExpression => GetSymbolsOffOfExpression(rangeExpression.LeftOperand),
QualifiedNameSyntax qualifiedName => GetSymbolsOffOfName(qualifiedName.Left),
AliasQualifiedNameSyntax aliasName => GetSymbolsOffOffAlias(aliasName.Alias),
MemberBindingExpressionSyntax _ => GetSymbolsOffOfConditionalReceiver(node.GetParentConditionalAccessExpression()!.Expression),
_ => default,
};
}
private ImmutableArray<ISymbol> GetSymbolsForGlobalStatementContext()
{
var syntaxTree = _context.SyntaxTree;
var position = _context.Position;
var token = _context.LeftToken;
// The following code is a hack to get around a binding problem when asking binding
// questions immediately after a using directive. This is special-cased in the binder
// factory to ensure that using directives are not within scope inside other using
// directives. That generally works fine for .cs, but it's a problem for interactive
// code in this case:
//
// using System;
// |
if (token.Kind() == SyntaxKind.SemicolonToken &&
token.Parent.IsKind(SyntaxKind.UsingDirective) &&
position >= token.Span.End)
{
var compUnit = (CompilationUnitSyntax)syntaxTree.GetRoot(_cancellationToken);
if (compUnit.Usings.Count > 0 && compUnit.Usings.Last().GetLastToken() == token)
{
token = token.GetNextToken(includeZeroWidth: true);
}
}
var symbols = _context.SemanticModel.LookupSymbols(token.SpanStart);
return symbols;
}
private ImmutableArray<ISymbol> GetSymbolsForTypeArgumentOfConstraintClause()
{
var enclosingSymbol = _context.LeftToken.GetRequiredParent()
.AncestorsAndSelf()
.Select(n => _context.SemanticModel.GetDeclaredSymbol(n, _cancellationToken))
.WhereNotNull()
.FirstOrDefault();
var symbols = enclosingSymbol != null
? enclosingSymbol.GetTypeArguments()
: ImmutableArray<ITypeSymbol>.Empty;
return ImmutableArray<ISymbol>.CastUp(symbols);
}
private RecommendedSymbols GetSymbolsOffOffAlias(IdentifierNameSyntax alias)
{
var aliasSymbol = _context.SemanticModel.GetAliasInfo(alias, _cancellationToken);
if (aliasSymbol == null)
return default;
return new RecommendedSymbols(_context.SemanticModel.LookupNamespacesAndTypes(
alias.SpanStart,
aliasSymbol.Target));
}
private ImmutableArray<ISymbol> GetSymbolsForLabelContext()
{
var allLabels = _context.SemanticModel.LookupLabels(_context.LeftToken.SpanStart);
// Exclude labels (other than 'default') that come from case switch statements
return allLabels
.WhereAsArray(label => label.DeclaringSyntaxReferences.First().GetSyntax(_cancellationToken)
.IsKind(SyntaxKind.LabeledStatement, SyntaxKind.DefaultSwitchLabel));
}
private ImmutableArray<ISymbol> GetSymbolsForTypeOrNamespaceContext()
{
var symbols = _context.SemanticModel.LookupNamespacesAndTypes(_context.LeftToken.SpanStart);
if (_context.TargetToken.IsUsingKeywordInUsingDirective())
{
return symbols.WhereAsArray(s => s.IsNamespace());
}
if (_context.TargetToken.IsStaticKeywordInUsingDirective())
{
return symbols.WhereAsArray(s => !s.IsDelegateType() && !s.IsInterfaceType());
}
return symbols;
}
private ImmutableArray<ISymbol> GetSymbolsForExpressionOrStatementContext()
{
// Check if we're in an interesting situation like this:
//
// i // <-- here
// I = 0;
// The problem is that "i I = 0" causes a local to be in scope called "I". So, later when
// we look up symbols, it masks any other 'I's in scope (i.e. if there's a field with that
// name). If this is the case, we do not want to filter out inaccessible locals.
var filterOutOfScopeLocals = _filterOutOfScopeLocals;
if (filterOutOfScopeLocals)
filterOutOfScopeLocals = !_context.LeftToken.GetRequiredParent().IsFoundUnder<LocalDeclarationStatementSyntax>(d => d.Declaration.Type);
var symbols = !_context.IsNameOfContext && _context.LeftToken.GetRequiredParent().IsInStaticContext()
? _context.SemanticModel.LookupStaticMembers(_context.LeftToken.SpanStart)
: _context.SemanticModel.LookupSymbols(_context.LeftToken.SpanStart);
// Filter out any extension methods that might be imported by a using static directive.
// But include extension methods declared in the context's type or it's parents
var contextOuterTypes = _context.GetOuterTypes(_cancellationToken);
var contextEnclosingNamedType = _context.SemanticModel.GetEnclosingNamedType(_context.Position, _cancellationToken);
symbols = symbols.WhereAsArray(symbol =>
!symbol.IsExtensionMethod() ||
Equals(contextEnclosingNamedType, symbol.ContainingType) ||
contextOuterTypes.Any(outerType => outerType.Equals(symbol.ContainingType)));
// The symbols may include local variables that are declared later in the method and
// should not be included in the completion list, so remove those. Filter them away,
// unless we're in the debugger, where we show all locals in scope.
if (filterOutOfScopeLocals)
{
symbols = symbols.WhereAsArray(symbol => !symbol.IsInaccessibleLocal(_context.Position));
}
return symbols;
}
private RecommendedSymbols GetSymbolsOffOfName(NameSyntax name)
{
// Using an is pattern on an enum is a qualified name, but normal symbol processing works fine
if (_context.IsEnumTypeMemberAccessContext)
return GetSymbolsOffOfExpression(name);
if (ShouldBeTreatedAsTypeInsteadOfExpression(name, out var nameBinding, out var container))
return GetSymbolsOffOfBoundExpression(name, name, nameBinding, container, unwrapNullable: false);
// We're in a name-only context, since if we were an expression we'd be a
// MemberAccessExpressionSyntax. Thus, let's do other namespaces and types.
nameBinding = _context.SemanticModel.GetSymbolInfo(name, _cancellationToken);
if (nameBinding.Symbol is not INamespaceOrTypeSymbol symbol)
return default;
if (_context.IsNameOfContext)
return new RecommendedSymbols(_context.SemanticModel.LookupSymbols(position: name.SpanStart, container: symbol));
var symbols = _context.SemanticModel.LookupNamespacesAndTypes(
position: name.SpanStart,
container: symbol);
if (_context.IsNamespaceDeclarationNameContext)
{
var declarationSyntax = name.GetAncestorOrThis<BaseNamespaceDeclarationSyntax>();
return new RecommendedSymbols(symbols.WhereAsArray(s => IsNonIntersectingNamespace(s, declarationSyntax)));
}
// Filter the types when in a using directive, but not an alias.
//
// Cases:
// using | -- Show namespaces
// using A.| -- Show namespaces
// using static | -- Show namespace and types
// using A = B.| -- Show namespace and types
var usingDirective = name.GetAncestorOrThis<UsingDirectiveSyntax>();
if (usingDirective != null && usingDirective.Alias == null)
{
return new RecommendedSymbols(usingDirective.StaticKeyword.IsKind(SyntaxKind.StaticKeyword)
? symbols.WhereAsArray(s => !s.IsDelegateType() && !s.IsInterfaceType())
: symbols.WhereAsArray(s => s.IsNamespace()));
}
return new RecommendedSymbols(symbols);
}
/// <summary>
/// DeterminesCheck if we're in an interesting situation like this:
/// <code>
/// int i = 5;
/// i. // -- here
/// List ml = new List();
/// </code>
/// The problem is that "i.List" gets parsed as a type. In this case we need to try binding again as if "i" is
/// an expression and not a type. In order to do that, we need to speculate as to what 'i' meant if it wasn't
/// part of a local declaration's type.
/// <para/>
/// Another interesting case is something like:
/// <code>
/// stringList.
/// await Test2();
/// </code>
/// Here "stringList.await" is thought of as the return type of a local function.
/// </summary>
private bool ShouldBeTreatedAsTypeInsteadOfExpression(
ExpressionSyntax name,
out SymbolInfo leftHandBinding,
out ITypeSymbol? container)
{
if (name.IsFoundUnder<LocalFunctionStatementSyntax>(d => d.ReturnType) ||
name.IsFoundUnder<LocalDeclarationStatementSyntax>(d => d.Declaration.Type) ||
name.IsFoundUnder<FieldDeclarationSyntax>(d => d.Declaration.Type))
{
leftHandBinding = _context.SemanticModel.GetSpeculativeSymbolInfo(
name.SpanStart, name, SpeculativeBindingOption.BindAsExpression);
container = _context.SemanticModel.GetSpeculativeTypeInfo(
name.SpanStart, name, SpeculativeBindingOption.BindAsExpression).Type;
return true;
}
leftHandBinding = default;
container = null;
return false;
}
private RecommendedSymbols GetSymbolsOffOfExpression(ExpressionSyntax? originalExpression)
{
if (originalExpression == null)
return default;
// In case of 'await x$$', we want to move to 'x' to get it's members.
// To run GetSymbolInfo, we also need to get rid of parenthesis.
var expression = originalExpression is AwaitExpressionSyntax awaitExpression
? awaitExpression.Expression.WalkDownParentheses()
: originalExpression.WalkDownParentheses();
var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken);
var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type;
var result = GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: false);
// Check for the Color Color case.
if (originalExpression.CanAccessInstanceAndStaticMembersOffOf(_context.SemanticModel, _cancellationToken))
{
var speculativeSymbolInfo = _context.SemanticModel.GetSpeculativeSymbolInfo(expression.SpanStart, expression, SpeculativeBindingOption.BindAsTypeOrNamespace);
var typeMembers = GetSymbolsOffOfBoundExpression(originalExpression, expression, speculativeSymbolInfo, container, unwrapNullable: false);
result = new RecommendedSymbols(
result.NamedSymbols.Concat(typeMembers.NamedSymbols),
result.UnnamedSymbols);
}
return result;
}
private RecommendedSymbols GetSymbolsOffOfDereferencedExpression(ExpressionSyntax originalExpression)
{
var expression = originalExpression.WalkDownParentheses();
var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken);
var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type;
if (container is IPointerTypeSymbol pointerType)
{
container = pointerType.PointedAtType;
}
return GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: false);
}
private RecommendedSymbols GetSymbolsOffOfConditionalReceiver(ExpressionSyntax originalExpression)
{
// Given ((T?)t)?.|, the '.' will behave as if the expression was actually ((T)t).|. More plainly,
// a member access off of a conditional receiver of nullable type binds to the unwrapped nullable
// type. This is not exposed via the binding information for the LHS, so repeat this work here.
var expression = originalExpression.WalkDownParentheses();
var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken);
var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type;
// If the thing on the left is a type, namespace, or alias, we shouldn't show anything in
// IntelliSense.
if (leftHandBinding.GetBestOrAllSymbols().FirstOrDefault().MatchesKind(SymbolKind.NamedType, SymbolKind.Namespace, SymbolKind.Alias))
return default;
return GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: true);
}
private RecommendedSymbols GetSymbolsOffOfBoundExpression(
ExpressionSyntax originalExpression,
ExpressionSyntax expression,
SymbolInfo leftHandBinding,
ITypeSymbol? containerType,
bool unwrapNullable)
{
var abstractsOnly = false;
var excludeInstance = false;
var excludeStatic = true;
ISymbol? containerSymbol = containerType;
var symbol = leftHandBinding.GetAnySymbol();
if (symbol != null)
{
// If the thing on the left is a lambda expression, we shouldn't show anything.
if (symbol is IMethodSymbol { MethodKind: MethodKind.AnonymousFunction })
return default;
var originalExpressionKind = originalExpression.Kind();
// If the thing on the left is a type, namespace or alias and the original
// expression was parenthesized, we shouldn't show anything in IntelliSense.
if (originalExpressionKind is SyntaxKind.ParenthesizedExpression &&
symbol.Kind is SymbolKind.NamedType or SymbolKind.Namespace or SymbolKind.Alias)
{
return default;
}
// If the thing on the left is a method name identifier, we shouldn't show anything.
if (symbol.Kind is SymbolKind.Method &&
originalExpressionKind is SyntaxKind.IdentifierName or SyntaxKind.GenericName)
{
return default;
}
// If the thing on the left is an event that can't be used as a field, we shouldn't show anything
if (symbol is IEventSymbol ev &&
!_context.SemanticModel.IsEventUsableAsField(originalExpression.SpanStart, ev))
{
return default;
}
if (symbol is IAliasSymbol alias)
symbol = alias.Target;
if (symbol.Kind is SymbolKind.NamedType or SymbolKind.Namespace or SymbolKind.TypeParameter)
{
// For named typed, namespaces, and type parameters (potentially constrainted to interface with statics), we flip things around.
// We only want statics and not instance members.
excludeInstance = true;
excludeStatic = false;
abstractsOnly = symbol.Kind == SymbolKind.TypeParameter;
containerSymbol = symbol;
}
// Special case parameters. If we have a normal (non this/base) parameter, then that's what we want to
// lookup symbols off of as we have a lot of special logic for determining member symbols of lambda
// parameters.
//
// If it is a this/base parameter and we're in a static context, we shouldn't show anything
if (symbol is IParameterSymbol parameter)
{
if (parameter.IsThis && expression.IsInStaticContext())
return default;
containerSymbol = symbol;
}
}
else if (containerType != null)
{
// Otherwise, if it wasn't a symbol on the left, but it was something that had a type,
// then include instance members for it.
excludeStatic = true;
}
if (containerSymbol == null)
return default;
Debug.Assert(!excludeInstance || !excludeStatic);
Debug.Assert(!abstractsOnly || (abstractsOnly && !excludeStatic && excludeInstance));
// nameof(X.|
// Show static and instance members.
if (_context.IsNameOfContext)
{
excludeInstance = false;
excludeStatic = false;
}
var useBaseReferenceAccessibility = symbol is IParameterSymbol { IsThis: true } p && !p.Type.Equals(containerType);
var symbols = GetMemberSymbols(containerSymbol, position: originalExpression.SpanStart, excludeInstance, useBaseReferenceAccessibility, unwrapNullable);
// If we're showing instance members, don't include nested types
var namedSymbols = excludeStatic
? symbols.WhereAsArray(s => !(s.IsStatic || s is ITypeSymbol))
: (abstractsOnly ? symbols.WhereAsArray(s => s.IsAbstract) : symbols);
// if we're dotting off an instance, then add potential operators/indexers/conversions that may be
// applicable to it as well.
var unnamedSymbols = _context.IsNameOfContext || excludeInstance
? default
: GetUnnamedSymbols(originalExpression);
return new RecommendedSymbols(namedSymbols, unnamedSymbols);
}
private ImmutableArray<ISymbol> GetUnnamedSymbols(ExpressionSyntax originalExpression)
{
var semanticModel = _context.SemanticModel;
var container = GetContainerForUnnamedSymbols(semanticModel, originalExpression);
if (container == null)
return ImmutableArray<ISymbol>.Empty;
// In a case like `x?.Y` if we bind the type of `.Y` we will get a value type back (like `int`), and not
// `int?`. However, we want to think of the constructed type as that's the type of the overall expression
// that will be casted.
if (originalExpression.GetRootConditionalAccessExpression() != null)
container = TryMakeNullable(semanticModel.Compilation, container);
using var _ = ArrayBuilder<ISymbol>.GetInstance(out var symbols);
AddIndexers(container, symbols);
AddOperators(container, symbols);
AddConversions(container, symbols);
return symbols.ToImmutable();
}
private ITypeSymbol? GetContainerForUnnamedSymbols(SemanticModel semanticModel, ExpressionSyntax originalExpression)
{
return ShouldBeTreatedAsTypeInsteadOfExpression(originalExpression, out _, out var container)
? container
: semanticModel.GetTypeInfo(originalExpression, _cancellationToken).Type;
}
private void AddIndexers(ITypeSymbol container, ArrayBuilder<ISymbol> symbols)
{
var containingType = _context.SemanticModel.GetEnclosingNamedType(_context.Position, _cancellationToken);
if (containingType == null)
return;
foreach (var member in container.RemoveNullableIfPresent().GetAccessibleMembersInThisAndBaseTypes<IPropertySymbol>(containingType))
{
if (member.IsIndexer)
symbols.Add(member);
}
}
}
}
| 1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/CSharp/Portable/Rename/CSharpRenameRewriterLanguageService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Simplification;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Rename;
using Microsoft.CodeAnalysis.Rename.ConflictEngine;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Rename
{
[ExportLanguageService(typeof(IRenameRewriterLanguageService), LanguageNames.CSharp), Shared]
internal class CSharpRenameConflictLanguageService : AbstractRenameRewriterLanguageService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpRenameConflictLanguageService()
{
}
#region "Annotation"
public override SyntaxNode AnnotateAndRename(RenameRewriterParameters parameters)
{
var renameAnnotationRewriter = new RenameRewriter(parameters);
return renameAnnotationRewriter.Visit(parameters.SyntaxRoot)!;
}
private class RenameRewriter : CSharpSyntaxRewriter
{
private readonly DocumentId _documentId;
private readonly RenameAnnotation _renameRenamableSymbolDeclaration;
private readonly Solution _solution;
private readonly string _replacementText;
private readonly string _originalText;
private readonly ICollection<string> _possibleNameConflicts;
private readonly Dictionary<TextSpan, RenameLocation> _renameLocations;
private readonly ISet<TextSpan> _conflictLocations;
private readonly SemanticModel _semanticModel;
private readonly CancellationToken _cancellationToken;
private readonly ISymbol _renamedSymbol;
private readonly IAliasSymbol? _aliasSymbol;
private readonly Location? _renamableDeclarationLocation;
private readonly RenamedSpansTracker _renameSpansTracker;
private readonly bool _isVerbatim;
private readonly bool _replacementTextValid;
private readonly ISimplificationService _simplificationService;
private readonly ISemanticFactsService _semanticFactsService;
private readonly HashSet<SyntaxToken> _annotatedIdentifierTokens = new();
private readonly HashSet<InvocationExpressionSyntax> _invocationExpressionsNeedingConflictChecks = new();
private readonly AnnotationTable<RenameAnnotation> _renameAnnotations;
/// <summary>
/// Flag indicating if we should perform a rename inside string literals.
/// </summary>
private readonly bool _isRenamingInStrings;
/// <summary>
/// Flag indicating if we should perform a rename inside comment trivia.
/// </summary>
private readonly bool _isRenamingInComments;
/// <summary>
/// A map from spans of tokens needing rename within strings or comments to an optional
/// set of specific sub-spans within the token span that
/// have <see cref="_originalText"/> matches and should be renamed.
/// If this sorted set is null, it indicates that sub-spans to rename within the token span
/// are not available, and a regex match should be performed to rename
/// all <see cref="_originalText"/> matches within the span.
/// </summary>
private readonly ImmutableDictionary<TextSpan, ImmutableSortedSet<TextSpan>?> _stringAndCommentTextSpans;
public bool AnnotateForComplexification
{
get
{
return _skipRenameForComplexification > 0 && !_isProcessingComplexifiedSpans;
}
}
private int _skipRenameForComplexification;
private bool _isProcessingComplexifiedSpans;
private List<(TextSpan oldSpan, TextSpan newSpan)>? _modifiedSubSpans;
private SemanticModel? _speculativeModel;
private int _isProcessingTrivia;
private void AddModifiedSpan(TextSpan oldSpan, TextSpan newSpan)
{
newSpan = new TextSpan(oldSpan.Start, newSpan.Length);
if (!_isProcessingComplexifiedSpans)
{
_renameSpansTracker.AddModifiedSpan(_documentId, oldSpan, newSpan);
}
else
{
RoslynDebug.Assert(_modifiedSubSpans != null);
_modifiedSubSpans.Add((oldSpan, newSpan));
}
}
public RenameRewriter(RenameRewriterParameters parameters)
: base(visitIntoStructuredTrivia: true)
{
_documentId = parameters.Document.Id;
_renameRenamableSymbolDeclaration = parameters.RenamedSymbolDeclarationAnnotation;
_solution = parameters.OriginalSolution;
_replacementText = parameters.ReplacementText;
_originalText = parameters.OriginalText;
_possibleNameConflicts = parameters.PossibleNameConflicts;
_renameLocations = parameters.RenameLocations;
_conflictLocations = parameters.ConflictLocationSpans;
_cancellationToken = parameters.CancellationToken;
_semanticModel = parameters.SemanticModel;
_renamedSymbol = parameters.RenameSymbol;
_replacementTextValid = parameters.ReplacementTextValid;
_renameSpansTracker = parameters.RenameSpansTracker;
_isRenamingInStrings = parameters.OptionSet.RenameInStrings;
_isRenamingInComments = parameters.OptionSet.RenameInComments;
_stringAndCommentTextSpans = parameters.StringAndCommentTextSpans;
_renameAnnotations = parameters.RenameAnnotations;
_aliasSymbol = _renamedSymbol as IAliasSymbol;
_renamableDeclarationLocation = _renamedSymbol.Locations.FirstOrDefault(loc => loc.IsInSource && loc.SourceTree == _semanticModel.SyntaxTree);
_isVerbatim = _replacementText.StartsWith("@", StringComparison.Ordinal);
_simplificationService = parameters.Document.Project.LanguageServices.GetRequiredService<ISimplificationService>();
_semanticFactsService = parameters.Document.Project.LanguageServices.GetRequiredService<ISemanticFactsService>();
}
public override SyntaxNode? Visit(SyntaxNode? node)
{
if (node == null)
{
return node;
}
var isInConflictLambdaBody = false;
var lambdas = node.GetAncestorsOrThis(n => n is SimpleLambdaExpressionSyntax || n is ParenthesizedLambdaExpressionSyntax);
if (lambdas.Count() != 0)
{
foreach (var lambda in lambdas)
{
if (_conflictLocations.Any(cf => cf.Contains(lambda.Span)))
{
isInConflictLambdaBody = true;
break;
}
}
}
var shouldComplexifyNode = ShouldComplexifyNode(node, isInConflictLambdaBody);
SyntaxNode result;
// in case the current node was identified as being a complexification target of
// a previous node, we'll handle it accordingly.
if (shouldComplexifyNode)
{
_skipRenameForComplexification++;
result = base.Visit(node)!;
_skipRenameForComplexification--;
result = Complexify(node, result);
}
else
{
result = base.Visit(node)!;
}
return result;
}
private bool ShouldComplexifyNode(SyntaxNode node, bool isInConflictLambdaBody)
{
return !isInConflictLambdaBody &&
_skipRenameForComplexification == 0 &&
!_isProcessingComplexifiedSpans &&
_conflictLocations.Contains(node.Span) &&
(node is AttributeSyntax ||
node is AttributeArgumentSyntax ||
node is ConstructorInitializerSyntax ||
node is ExpressionSyntax ||
node is FieldDeclarationSyntax ||
node is StatementSyntax ||
node is CrefSyntax ||
node is XmlNameAttributeSyntax ||
node is TypeConstraintSyntax ||
node is BaseTypeSyntax);
}
public override SyntaxToken VisitToken(SyntaxToken token)
{
var shouldCheckTrivia = _stringAndCommentTextSpans.ContainsKey(token.Span);
_isProcessingTrivia += shouldCheckTrivia ? 1 : 0;
var newToken = base.VisitToken(token);
_isProcessingTrivia -= shouldCheckTrivia ? 1 : 0;
// Handle Alias annotations
newToken = UpdateAliasAnnotation(newToken);
// Rename matches in strings and comments
newToken = RenameWithinToken(token, newToken);
// We don't want to annotate XmlName with RenameActionAnnotation
if (newToken.Parent.IsKind(SyntaxKind.XmlName))
{
return newToken;
}
var isRenameLocation = IsRenameLocation(token);
// if this is a reference location, or the identifier token's name could possibly
// be a conflict, we need to process this token
var isOldText = token.ValueText == _originalText;
var tokenNeedsConflictCheck =
isRenameLocation ||
token.ValueText == _replacementText ||
isOldText ||
_possibleNameConflicts.Contains(token.ValueText) ||
IsPossiblyDestructorConflict(token) ||
IsPropertyAccessorNameConflict(token);
if (tokenNeedsConflictCheck)
{
newToken = RenameAndAnnotateAsync(token, newToken, isRenameLocation, isOldText).WaitAndGetResult_CanCallOnBackground(_cancellationToken);
if (!_isProcessingComplexifiedSpans)
{
_invocationExpressionsNeedingConflictChecks.AddRange(token.GetAncestors<InvocationExpressionSyntax>());
}
}
return newToken;
}
private bool IsPropertyAccessorNameConflict(SyntaxToken token)
=> IsGetPropertyAccessorNameConflict(token)
|| IsSetPropertyAccessorNameConflict(token)
|| IsInitPropertyAccessorNameConflict(token);
private bool IsGetPropertyAccessorNameConflict(SyntaxToken token)
=> token.IsKind(SyntaxKind.GetKeyword)
&& IsNameConflictWithProperty("get", token.Parent as AccessorDeclarationSyntax);
private bool IsSetPropertyAccessorNameConflict(SyntaxToken token)
=> token.IsKind(SyntaxKind.SetKeyword)
&& IsNameConflictWithProperty("set", token.Parent as AccessorDeclarationSyntax);
private bool IsInitPropertyAccessorNameConflict(SyntaxToken token)
=> token.IsKind(SyntaxKind.InitKeyword)
// using "set" here is intentional. The compiler generates set_PropName for both set and init accessors.
&& IsNameConflictWithProperty("set", token.Parent as AccessorDeclarationSyntax);
private bool IsNameConflictWithProperty(string prefix, AccessorDeclarationSyntax? accessor)
=> accessor?.Parent?.Parent is PropertyDeclarationSyntax property // 3 null checks in one: accessor -> accessor list -> property declaration
&& _replacementText.Equals(prefix + "_" + property.Identifier.Text, StringComparison.Ordinal);
private bool IsPossiblyDestructorConflict(SyntaxToken token)
{
return _replacementText == "Finalize" &&
token.IsKind(SyntaxKind.IdentifierToken) &&
token.Parent.IsKind(SyntaxKind.DestructorDeclaration);
}
private SyntaxNode Complexify(SyntaxNode originalNode, SyntaxNode newNode)
{
_isProcessingComplexifiedSpans = true;
_modifiedSubSpans = new List<(TextSpan oldSpan, TextSpan newSpan)>();
var annotation = new SyntaxAnnotation();
newNode = newNode.WithAdditionalAnnotations(annotation);
var speculativeTree = originalNode.SyntaxTree.GetRoot(_cancellationToken).ReplaceNode(originalNode, newNode);
newNode = speculativeTree.GetAnnotatedNodes<SyntaxNode>(annotation).First();
_speculativeModel = GetSemanticModelForNode(newNode, _semanticModel);
RoslynDebug.Assert(_speculativeModel != null, "expanding a syntax node which cannot be speculated?");
var oldSpan = originalNode.Span;
var expandParameter = originalNode.GetAncestorsOrThis(n => n is SimpleLambdaExpressionSyntax || n is ParenthesizedLambdaExpressionSyntax).Count() == 0;
newNode = _simplificationService.Expand(newNode,
_speculativeModel,
annotationForReplacedAliasIdentifier: null,
expandInsideNode: null,
expandParameter: expandParameter,
cancellationToken: _cancellationToken);
speculativeTree = originalNode.SyntaxTree.GetRoot(_cancellationToken).ReplaceNode(originalNode, newNode);
newNode = speculativeTree.GetAnnotatedNodes<SyntaxNode>(annotation).First();
_speculativeModel = GetSemanticModelForNode(newNode, _semanticModel);
newNode = base.Visit(newNode)!;
var newSpan = newNode.Span;
newNode = newNode.WithoutAnnotations(annotation);
newNode = _renameAnnotations.WithAdditionalAnnotations(newNode, new RenameNodeSimplificationAnnotation() { OriginalTextSpan = oldSpan });
_renameSpansTracker.AddComplexifiedSpan(_documentId, oldSpan, new TextSpan(oldSpan.Start, newSpan.Length), _modifiedSubSpans);
_modifiedSubSpans = null;
_isProcessingComplexifiedSpans = false;
_speculativeModel = null;
return newNode;
}
private async Task<SyntaxToken> RenameAndAnnotateAsync(SyntaxToken token, SyntaxToken newToken, bool isRenameLocation, bool isOldText)
{
try
{
if (_isProcessingComplexifiedSpans)
{
// Rename Token
if (isRenameLocation)
{
var annotation = _renameAnnotations.GetAnnotations(token).OfType<RenameActionAnnotation>().FirstOrDefault();
if (annotation != null)
{
newToken = RenameToken(token, newToken, annotation.Prefix, annotation.Suffix);
AddModifiedSpan(annotation.OriginalSpan, newToken.Span);
}
else
{
newToken = RenameToken(token, newToken, prefix: null, suffix: null);
}
}
return newToken;
}
var symbols = RenameUtilities.GetSymbolsTouchingPosition(token.Span.Start, _semanticModel, _solution.Workspace, _cancellationToken);
string? suffix = null;
var prefix = isRenameLocation && _renameLocations[token.Span].IsRenamableAccessor
? newToken.ValueText.Substring(0, newToken.ValueText.IndexOf('_') + 1)
: null;
if (symbols.Length == 1)
{
var symbol = symbols[0];
if (symbol.IsConstructor())
{
symbol = symbol.ContainingSymbol;
}
var sourceDefinition = await SymbolFinder.FindSourceDefinitionAsync(symbol, _solution, _cancellationToken).ConfigureAwait(false);
symbol = sourceDefinition ?? symbol;
if (symbol is INamedTypeSymbol namedTypeSymbol)
{
if (namedTypeSymbol.IsImplicitlyDeclared &&
namedTypeSymbol.IsDelegateType() &&
namedTypeSymbol.AssociatedSymbol != null)
{
suffix = "EventHandler";
}
}
// This is a conflicting namespace declaration token. Even if the rename results in conflict with this namespace
// conflict is not shown for the namespace so we are tracking this token
if (!isRenameLocation && symbol is INamespaceSymbol && token.GetPreviousToken().IsKind(SyntaxKind.NamespaceKeyword))
{
return newToken;
}
}
// Rename Token
if (isRenameLocation && !this.AnnotateForComplexification)
{
var oldSpan = token.Span;
newToken = RenameToken(token, newToken, prefix, suffix);
AddModifiedSpan(oldSpan, newToken.Span);
}
var renameDeclarationLocations = await
ConflictResolver.CreateDeclarationLocationAnnotationsAsync(_solution, symbols, _cancellationToken).ConfigureAwait(false);
var isNamespaceDeclarationReference = false;
if (isRenameLocation && token.GetPreviousToken().IsKind(SyntaxKind.NamespaceKeyword))
{
isNamespaceDeclarationReference = true;
}
var isMemberGroupReference = _semanticFactsService.IsInsideNameOfExpression(_semanticModel, token.Parent, _cancellationToken);
var renameAnnotation =
new RenameActionAnnotation(
token.Span,
isRenameLocation,
prefix,
suffix,
renameDeclarationLocations: renameDeclarationLocations,
isOriginalTextLocation: isOldText,
isNamespaceDeclarationReference: isNamespaceDeclarationReference,
isInvocationExpression: false,
isMemberGroupReference: isMemberGroupReference);
newToken = _renameAnnotations.WithAdditionalAnnotations(newToken, renameAnnotation, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = token.Span });
_annotatedIdentifierTokens.Add(token);
if (_renameRenamableSymbolDeclaration != null && _renamableDeclarationLocation == token.GetLocation())
{
newToken = _renameAnnotations.WithAdditionalAnnotations(newToken, _renameRenamableSymbolDeclaration);
}
return newToken;
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private RenameActionAnnotation? GetAnnotationForInvocationExpression(InvocationExpressionSyntax invocationExpression)
{
var identifierToken = default(SyntaxToken);
var expressionOfInvocation = invocationExpression.Expression;
while (expressionOfInvocation != null)
{
switch (expressionOfInvocation.Kind())
{
case SyntaxKind.IdentifierName:
case SyntaxKind.GenericName:
identifierToken = ((SimpleNameSyntax)expressionOfInvocation).Identifier;
break;
case SyntaxKind.SimpleMemberAccessExpression:
identifierToken = ((MemberAccessExpressionSyntax)expressionOfInvocation).Name.Identifier;
break;
case SyntaxKind.QualifiedName:
identifierToken = ((QualifiedNameSyntax)expressionOfInvocation).Right.Identifier;
break;
case SyntaxKind.AliasQualifiedName:
identifierToken = ((AliasQualifiedNameSyntax)expressionOfInvocation).Name.Identifier;
break;
case SyntaxKind.ParenthesizedExpression:
expressionOfInvocation = ((ParenthesizedExpressionSyntax)expressionOfInvocation).Expression;
continue;
}
break;
}
if (identifierToken != default && !_annotatedIdentifierTokens.Contains(identifierToken))
{
var symbolInfo = _semanticModel.GetSymbolInfo(invocationExpression, _cancellationToken);
IEnumerable<ISymbol> symbols;
if (symbolInfo.Symbol == null)
{
return null;
}
else
{
symbols = SpecializedCollections.SingletonEnumerable(symbolInfo.Symbol);
}
var renameDeclarationLocations =
ConflictResolver.CreateDeclarationLocationAnnotationsAsync(
_solution,
symbols,
_cancellationToken)
.WaitAndGetResult_CanCallOnBackground(_cancellationToken);
var renameAnnotation = new RenameActionAnnotation(
identifierToken.Span,
isRenameLocation: false,
prefix: null,
suffix: null,
renameDeclarationLocations: renameDeclarationLocations,
isOriginalTextLocation: false,
isNamespaceDeclarationReference: false,
isInvocationExpression: true,
isMemberGroupReference: false);
return renameAnnotation;
}
return null;
}
public override SyntaxNode? VisitInvocationExpression(InvocationExpressionSyntax node)
{
var result = base.VisitInvocationExpression(node);
RoslynDebug.AssertNotNull(result);
if (_invocationExpressionsNeedingConflictChecks.Contains(node))
{
var renameAnnotation = GetAnnotationForInvocationExpression(node);
if (renameAnnotation != null)
{
result = _renameAnnotations.WithAdditionalAnnotations(result, renameAnnotation);
}
}
return result;
}
private bool IsRenameLocation(SyntaxToken token)
{
if (!_isProcessingComplexifiedSpans)
{
return _renameLocations.ContainsKey(token.Span);
}
else
{
RoslynDebug.Assert(_speculativeModel != null);
if (token.HasAnnotations(AliasAnnotation.Kind))
{
return false;
}
if (token.HasAnnotations(RenameAnnotation.Kind))
{
return _renameAnnotations.GetAnnotations(token).OfType<RenameActionAnnotation>().First().IsRenameLocation;
}
if (token.Parent is SimpleNameSyntax && !token.IsKind(SyntaxKind.GlobalKeyword) && token.Parent.Parent.IsKind(SyntaxKind.AliasQualifiedName, SyntaxKind.QualifiedCref, SyntaxKind.QualifiedName))
{
var symbol = _speculativeModel.GetSymbolInfo(token.Parent, _cancellationToken).Symbol;
if (symbol != null && _renamedSymbol.Kind != SymbolKind.Local && _renamedSymbol.Kind != SymbolKind.RangeVariable &&
(Equals(symbol, _renamedSymbol) || SymbolKey.GetComparer(ignoreCase: true, ignoreAssemblyKeys: false).Equals(symbol.GetSymbolKey(), _renamedSymbol.GetSymbolKey())))
{
return true;
}
}
return false;
}
}
private SyntaxToken UpdateAliasAnnotation(SyntaxToken newToken)
{
if (_aliasSymbol != null && !this.AnnotateForComplexification && newToken.HasAnnotations(AliasAnnotation.Kind))
{
newToken = RenameUtilities.UpdateAliasAnnotation(newToken, _aliasSymbol, _replacementText);
}
return newToken;
}
private SyntaxToken RenameToken(SyntaxToken oldToken, SyntaxToken newToken, string? prefix, string? suffix)
{
var parent = oldToken.Parent!;
var currentNewIdentifier = _isVerbatim ? _replacementText.Substring(1) : _replacementText;
var oldIdentifier = newToken.ValueText;
var isAttributeName = SyntaxFacts.IsAttributeName(parent);
if (isAttributeName)
{
if (oldIdentifier != _renamedSymbol.Name)
{
if (currentNewIdentifier.TryGetWithoutAttributeSuffix(out var withoutSuffix))
{
currentNewIdentifier = withoutSuffix;
}
}
}
else
{
if (!string.IsNullOrEmpty(prefix))
{
currentNewIdentifier = prefix + currentNewIdentifier;
}
if (!string.IsNullOrEmpty(suffix))
{
currentNewIdentifier += suffix;
}
}
// determine the canonical identifier name (unescaped, no unicode escaping, ...)
var valueText = currentNewIdentifier;
var kind = SyntaxFacts.GetKeywordKind(currentNewIdentifier);
if (kind != SyntaxKind.None)
{
valueText = SyntaxFacts.GetText(kind);
}
else
{
var parsedIdentifier = SyntaxFactory.ParseName(currentNewIdentifier);
if (parsedIdentifier.IsKind(SyntaxKind.IdentifierName, out IdentifierNameSyntax? identifierName))
{
valueText = identifierName.Identifier.ValueText;
}
}
// TODO: we can't use escaped unicode characters in xml doc comments, so we need to pass the valuetext as text as well.
// <param name="\u... is invalid.
// if it's an attribute name we don't mess with the escaping because it might change overload resolution
newToken = _isVerbatim || (isAttributeName && oldToken.IsVerbatimIdentifier())
? newToken.CopyAnnotationsTo(SyntaxFactory.VerbatimIdentifier(newToken.LeadingTrivia, currentNewIdentifier, valueText, newToken.TrailingTrivia))
: newToken.CopyAnnotationsTo(SyntaxFactory.Identifier(newToken.LeadingTrivia, SyntaxKind.IdentifierToken, currentNewIdentifier, valueText, newToken.TrailingTrivia));
if (_replacementTextValid)
{
if (newToken.IsVerbatimIdentifier())
{
// a reference location should always be tried to be unescaped, whether it was escaped before rename
// or the replacement itself is escaped.
newToken = newToken.WithAdditionalAnnotations(Simplifier.Annotation);
}
else
{
newToken = CSharpSimplificationHelpers.TryEscapeIdentifierToken(newToken, parent);
}
}
return newToken;
}
private SyntaxToken RenameInStringLiteral(SyntaxToken oldToken, SyntaxToken newToken, ImmutableSortedSet<TextSpan>? subSpansToReplace, Func<SyntaxTriviaList, string, string, SyntaxTriviaList, SyntaxToken> createNewStringLiteral)
{
var originalString = newToken.ToString();
var replacedString = RenameLocations.ReferenceProcessing.ReplaceMatchingSubStrings(originalString, _originalText, _replacementText, subSpansToReplace);
if (replacedString != originalString)
{
var oldSpan = oldToken.Span;
newToken = createNewStringLiteral(newToken.LeadingTrivia, replacedString, replacedString, newToken.TrailingTrivia);
AddModifiedSpan(oldSpan, newToken.Span);
return newToken.CopyAnnotationsTo(_renameAnnotations.WithAdditionalAnnotations(newToken, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = oldSpan }));
}
return newToken;
}
private SyntaxToken RenameInTrivia(SyntaxToken token, IEnumerable<SyntaxTrivia> leadingOrTrailingTriviaList)
{
return token.ReplaceTrivia(leadingOrTrailingTriviaList, (oldTrivia, newTrivia) =>
{
if (newTrivia.IsSingleLineComment() || newTrivia.IsMultiLineComment())
{
return RenameInCommentTrivia(newTrivia);
}
return newTrivia;
});
}
private SyntaxTrivia RenameInCommentTrivia(SyntaxTrivia trivia)
{
var originalString = trivia.ToString();
var replacedString = RenameLocations.ReferenceProcessing.ReplaceMatchingSubStrings(originalString, _originalText, _replacementText);
if (replacedString != originalString)
{
var oldSpan = trivia.Span;
var newTrivia = SyntaxFactory.Comment(replacedString);
AddModifiedSpan(oldSpan, newTrivia.Span);
return trivia.CopyAnnotationsTo(_renameAnnotations.WithAdditionalAnnotations(newTrivia, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = oldSpan }));
}
return trivia;
}
private SyntaxToken RenameWithinToken(SyntaxToken oldToken, SyntaxToken newToken)
{
ImmutableSortedSet<TextSpan>? subSpansToReplace = null;
if (_isProcessingComplexifiedSpans ||
(_isProcessingTrivia == 0 &&
!_stringAndCommentTextSpans.TryGetValue(oldToken.Span, out subSpansToReplace)))
{
return newToken;
}
if (_isRenamingInStrings || subSpansToReplace?.Count > 0)
{
if (newToken.IsKind(SyntaxKind.StringLiteralToken))
{
newToken = RenameInStringLiteral(oldToken, newToken, subSpansToReplace, SyntaxFactory.Literal);
}
else if (newToken.IsKind(SyntaxKind.InterpolatedStringTextToken))
{
newToken = RenameInStringLiteral(oldToken, newToken, subSpansToReplace, (leadingTrivia, text, value, trailingTrivia) =>
SyntaxFactory.Token(newToken.LeadingTrivia, SyntaxKind.InterpolatedStringTextToken, text, value, newToken.TrailingTrivia));
}
}
if (_isRenamingInComments)
{
if (newToken.IsKind(SyntaxKind.XmlTextLiteralToken))
{
newToken = RenameInStringLiteral(oldToken, newToken, subSpansToReplace, SyntaxFactory.XmlTextLiteral);
}
else if (newToken.IsKind(SyntaxKind.IdentifierToken) && newToken.Parent.IsKind(SyntaxKind.XmlName) && newToken.ValueText == _originalText)
{
var newIdentifierToken = SyntaxFactory.Identifier(newToken.LeadingTrivia, _replacementText, newToken.TrailingTrivia);
newToken = newToken.CopyAnnotationsTo(_renameAnnotations.WithAdditionalAnnotations(newIdentifierToken, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = oldToken.Span }));
AddModifiedSpan(oldToken.Span, newToken.Span);
}
if (newToken.HasLeadingTrivia)
{
var updatedToken = RenameInTrivia(oldToken, oldToken.LeadingTrivia);
if (updatedToken != oldToken)
{
newToken = newToken.WithLeadingTrivia(updatedToken.LeadingTrivia);
}
}
if (newToken.HasTrailingTrivia)
{
var updatedToken = RenameInTrivia(oldToken, oldToken.TrailingTrivia);
if (updatedToken != oldToken)
{
newToken = newToken.WithTrailingTrivia(updatedToken.TrailingTrivia);
}
}
}
return newToken;
}
}
#endregion
#region "Declaration Conflicts"
public override bool LocalVariableConflict(
SyntaxToken token,
IEnumerable<ISymbol> newReferencedSymbols)
{
if (token.Parent.IsKind(SyntaxKind.IdentifierName, out ExpressionSyntax? expression) &&
token.Parent.IsParentKind(SyntaxKind.InvocationExpression) &&
token.GetPreviousToken().Kind() != SyntaxKind.DotToken &&
token.GetNextToken().Kind() != SyntaxKind.DotToken)
{
var enclosingMemberDeclaration = expression.FirstAncestorOrSelf<MemberDeclarationSyntax>();
if (enclosingMemberDeclaration != null)
{
var locals = enclosingMemberDeclaration.GetLocalDeclarationMap()[token.ValueText];
if (locals.Length > 0)
{
// This unqualified invocation name matches the name of an existing local
// or parameter. Report a conflict if the matching local/parameter is not
// a delegate type.
var relevantLocals = newReferencedSymbols
.Where(s => s.MatchesKind(SymbolKind.Local, SymbolKind.Parameter) && s.Name == token.ValueText);
if (relevantLocals.Count() != 1)
{
return true;
}
var matchingLocal = relevantLocals.Single();
var invocationTargetsLocalOfDelegateType =
(matchingLocal.IsKind(SymbolKind.Local) && ((ILocalSymbol)matchingLocal).Type.IsDelegateType()) ||
(matchingLocal.IsKind(SymbolKind.Parameter) && ((IParameterSymbol)matchingLocal).Type.IsDelegateType());
return !invocationTargetsLocalOfDelegateType;
}
}
}
return false;
}
public override async Task<ImmutableArray<Location>> ComputeDeclarationConflictsAsync(
string replacementText,
ISymbol renamedSymbol,
ISymbol renameSymbol,
IEnumerable<ISymbol> referencedSymbols,
Solution baseSolution,
Solution newSolution,
IDictionary<Location, Location> reverseMappedLocations,
CancellationToken cancellationToken)
{
try
{
using var _ = ArrayBuilder<Location>.GetInstance(out var conflicts);
// If we're renaming a named type, we can conflict with members w/ our same name. Note:
// this doesn't apply to enums.
if (renamedSymbol is INamedTypeSymbol { TypeKind: not TypeKind.Enum } namedType)
AddSymbolSourceSpans(conflicts, namedType.GetMembers(renamedSymbol.Name), reverseMappedLocations);
// If we're contained in a named type (we may be a named type ourself!) then we have a
// conflict. NOTE(cyrusn): This does not apply to enums.
if (renamedSymbol.ContainingSymbol is INamedTypeSymbol { TypeKind: not TypeKind.Enum } containingNamedType &&
containingNamedType.Name == renamedSymbol.Name)
{
AddSymbolSourceSpans(conflicts, SpecializedCollections.SingletonEnumerable(containingNamedType), reverseMappedLocations);
}
if (renamedSymbol.Kind == SymbolKind.Parameter ||
renamedSymbol.Kind == SymbolKind.Local ||
renamedSymbol.Kind == SymbolKind.RangeVariable)
{
var token = renamedSymbol.Locations.Single().FindToken(cancellationToken);
var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
var visitor = new LocalConflictVisitor(token);
visitor.Visit(memberDeclaration);
conflicts.AddRange(visitor.ConflictingTokens.Select(t => reverseMappedLocations[t.GetLocation()]));
// If this is a parameter symbol for a partial method definition, be sure we visited
// the implementation part's body.
if (renamedSymbol is IParameterSymbol renamedParameterSymbol &&
renamedSymbol.ContainingSymbol is IMethodSymbol methodSymbol &&
methodSymbol.PartialImplementationPart != null)
{
var matchingParameterSymbol = methodSymbol.PartialImplementationPart.Parameters[renamedParameterSymbol.Ordinal];
token = matchingParameterSymbol.Locations.Single().FindToken(cancellationToken);
memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
visitor = new LocalConflictVisitor(token);
visitor.Visit(memberDeclaration);
conflicts.AddRange(visitor.ConflictingTokens.Select(t => reverseMappedLocations[t.GetLocation()]));
}
}
else if (renamedSymbol.Kind == SymbolKind.Label)
{
var token = renamedSymbol.Locations.Single().FindToken(cancellationToken);
var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
var visitor = new LabelConflictVisitor(token);
visitor.Visit(memberDeclaration);
conflicts.AddRange(visitor.ConflictingTokens.Select(t => reverseMappedLocations[t.GetLocation()]));
}
else if (renamedSymbol.Kind == SymbolKind.Method)
{
conflicts.AddRange(DeclarationConflictHelpers.GetMembersWithConflictingSignatures((IMethodSymbol)renamedSymbol, trimOptionalParameters: false).Select(t => reverseMappedLocations[t]));
// we allow renaming overrides of VB property accessors with parameters in C#.
// VB has a special rule that properties are not allowed to have the same name as any of the parameters.
// Because this declaration in C# affects the property declaration in VB, we need to check this VB rule here in C#.
var properties = new List<ISymbol>();
foreach (var referencedSymbol in referencedSymbols)
{
var property = await RenameLocations.ReferenceProcessing.TryGetPropertyFromAccessorOrAnOverrideAsync(
referencedSymbol, baseSolution, cancellationToken).ConfigureAwait(false);
if (property != null)
properties.Add(property);
}
AddConflictingParametersOfProperties(properties.Distinct(), replacementText, conflicts);
}
else if (renamedSymbol.Kind == SymbolKind.Alias)
{
// in C# there can only be one using with the same alias name in the same block (top of file of namespace).
// It's ok to redefine the alias in different blocks.
var location = renamedSymbol.Locations.Single();
var tree = location.SourceTree;
Contract.ThrowIfNull(tree);
var token = await tree.GetTouchingTokenAsync(location.SourceSpan.Start, cancellationToken, findInsideTrivia: true).ConfigureAwait(false);
var currentUsing = (UsingDirectiveSyntax)token.Parent!.Parent!.Parent!;
var namespaceDecl = token.Parent.Ancestors().OfType<BaseNamespaceDeclarationSyntax>().FirstOrDefault();
SyntaxList<UsingDirectiveSyntax> usings;
if (namespaceDecl != null)
{
usings = namespaceDecl.Usings;
}
else
{
var compilationUnit = (CompilationUnitSyntax)await tree.GetRootAsync(cancellationToken).ConfigureAwait(false);
usings = compilationUnit.Usings;
}
foreach (var usingDirective in usings)
{
if (usingDirective.Alias != null && usingDirective != currentUsing)
{
if (usingDirective.Alias.Name.Identifier.ValueText == currentUsing.Alias!.Name.Identifier.ValueText)
conflicts.Add(reverseMappedLocations[usingDirective.Alias.Name.GetLocation()]);
}
}
}
else if (renamedSymbol.Kind == SymbolKind.TypeParameter)
{
foreach (var location in renamedSymbol.Locations)
{
var token = await location.SourceTree!.GetTouchingTokenAsync(location.SourceSpan.Start, cancellationToken, findInsideTrivia: true).ConfigureAwait(false);
var currentTypeParameter = token.Parent!;
foreach (var typeParameter in ((TypeParameterListSyntax)currentTypeParameter.Parent!).Parameters)
{
if (typeParameter != currentTypeParameter && token.ValueText == typeParameter.Identifier.ValueText)
conflicts.Add(reverseMappedLocations[typeParameter.Identifier.GetLocation()]);
}
}
}
// if the renamed symbol is a type member, it's name should not conflict with a type parameter
if (renamedSymbol.ContainingType != null && renamedSymbol.ContainingType.GetMembers(renamedSymbol.Name).Contains(renamedSymbol))
{
var conflictingLocations = renamedSymbol.ContainingType.TypeParameters
.Where(t => t.Name == renamedSymbol.Name)
.SelectMany(t => t.Locations);
foreach (var location in conflictingLocations)
{
var typeParameterToken = location.FindToken(cancellationToken);
conflicts.Add(reverseMappedLocations[typeParameterToken.GetLocation()]);
}
}
return conflicts.ToImmutable();
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
private static async Task<ISymbol?> GetVBPropertyFromAccessorOrAnOverrideAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken)
{
try
{
if (symbol.IsPropertyAccessor())
{
var property = ((IMethodSymbol)symbol).AssociatedSymbol!;
return property.Language == LanguageNames.VisualBasic ? property : null;
}
if (symbol.IsOverride && symbol.GetOverriddenMember() != null)
{
var originalSourceSymbol = await SymbolFinder.FindSourceDefinitionAsync(symbol.GetOverriddenMember(), solution, cancellationToken).ConfigureAwait(false);
if (originalSourceSymbol != null)
{
return await GetVBPropertyFromAccessorOrAnOverrideAsync(originalSourceSymbol, solution, cancellationToken).ConfigureAwait(false);
}
}
return null;
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
private static void AddSymbolSourceSpans(
ArrayBuilder<Location> conflicts, IEnumerable<ISymbol> symbols,
IDictionary<Location, Location> reverseMappedLocations)
{
foreach (var symbol in symbols)
{
foreach (var location in symbol.Locations)
{
// reverseMappedLocations may not contain the location if the location's token
// does not contain the text of it's name (e.g. the getter of "int X { get; }"
// does not contain the text "get_X" so conflicting renames to "get_X" will not
// have added the getter to reverseMappedLocations).
if (location.IsInSource && reverseMappedLocations.ContainsKey(location))
{
conflicts.Add(reverseMappedLocations[location]);
}
}
}
}
public override async Task<ImmutableArray<Location>> ComputeImplicitReferenceConflictsAsync(
ISymbol renameSymbol, ISymbol renamedSymbol, IEnumerable<ReferenceLocation> implicitReferenceLocations, CancellationToken cancellationToken)
{
// Handle renaming of symbols used for foreach
var implicitReferencesMightConflict = renameSymbol.Kind == SymbolKind.Property &&
string.Compare(renameSymbol.Name, "Current", StringComparison.OrdinalIgnoreCase) == 0;
implicitReferencesMightConflict =
implicitReferencesMightConflict ||
(renameSymbol.Kind == SymbolKind.Method &&
(string.Compare(renameSymbol.Name, WellKnownMemberNames.MoveNextMethodName, StringComparison.OrdinalIgnoreCase) == 0 ||
string.Compare(renameSymbol.Name, WellKnownMemberNames.GetEnumeratorMethodName, StringComparison.OrdinalIgnoreCase) == 0 ||
string.Compare(renameSymbol.Name, WellKnownMemberNames.GetAwaiter, StringComparison.OrdinalIgnoreCase) == 0 ||
string.Compare(renameSymbol.Name, WellKnownMemberNames.DeconstructMethodName, StringComparison.OrdinalIgnoreCase) == 0));
// TODO: handle Dispose for using statement and Add methods for collection initializers.
if (implicitReferencesMightConflict)
{
if (renamedSymbol.Name != renameSymbol.Name)
{
foreach (var implicitReferenceLocation in implicitReferenceLocations)
{
var token = await implicitReferenceLocation.Location.SourceTree!.GetTouchingTokenAsync(
implicitReferenceLocation.Location.SourceSpan.Start, cancellationToken, findInsideTrivia: false).ConfigureAwait(false);
switch (token.Kind())
{
case SyntaxKind.ForEachKeyword:
return ImmutableArray.Create(((CommonForEachStatementSyntax)token.Parent!).Expression.GetLocation());
case SyntaxKind.AwaitKeyword:
return ImmutableArray.Create(token.GetLocation());
}
if (token.Parent.IsInDeconstructionLeft(out var deconstructionLeft))
{
return ImmutableArray.Create(deconstructionLeft.GetLocation());
}
}
}
}
return ImmutableArray<Location>.Empty;
}
public override ImmutableArray<Location> ComputePossibleImplicitUsageConflicts(
ISymbol renamedSymbol,
SemanticModel semanticModel,
Location originalDeclarationLocation,
int newDeclarationLocationStartingPosition,
CancellationToken cancellationToken)
{
// TODO: support other implicitly used methods like dispose
if ((renamedSymbol.Name == "MoveNext" || renamedSymbol.Name == "GetEnumerator" || renamedSymbol.Name == "Current") && renamedSymbol.GetAllTypeArguments().Length == 0)
{
// TODO: partial methods currently only show the location where the rename happens as a conflict.
// Consider showing both locations as a conflict.
var baseType = renamedSymbol.ContainingType?.GetBaseTypes().FirstOrDefault();
if (baseType != null)
{
var implicitSymbols = semanticModel.LookupSymbols(
newDeclarationLocationStartingPosition,
baseType,
renamedSymbol.Name)
.Where(sym => !sym.Equals(renamedSymbol));
foreach (var symbol in implicitSymbols)
{
if (symbol.GetAllTypeArguments().Length != 0)
{
continue;
}
if (symbol.Kind == SymbolKind.Method)
{
var method = (IMethodSymbol)symbol;
if (symbol.Name == "MoveNext")
{
if (!method.ReturnsVoid && !method.Parameters.Any() && method.ReturnType.SpecialType == SpecialType.System_Boolean)
{
return ImmutableArray.Create(originalDeclarationLocation);
}
}
else if (symbol.Name == "GetEnumerator")
{
// we are a bit pessimistic here.
// To be sure we would need to check if the returned type is having a MoveNext and Current as required by foreach
if (!method.ReturnsVoid &&
!method.Parameters.Any())
{
return ImmutableArray.Create(originalDeclarationLocation);
}
}
}
else if (symbol.Kind == SymbolKind.Property && symbol.Name == "Current")
{
var property = (IPropertySymbol)symbol;
if (!property.Parameters.Any() && !property.IsWriteOnly)
{
return ImmutableArray.Create(originalDeclarationLocation);
}
}
}
}
}
return ImmutableArray<Location>.Empty;
}
#endregion
public override void TryAddPossibleNameConflicts(ISymbol symbol, string replacementText, ICollection<string> possibleNameConflicts)
{
if (replacementText.EndsWith("Attribute", StringComparison.Ordinal) && replacementText.Length > 9)
{
var conflict = replacementText.Substring(0, replacementText.Length - 9);
if (!possibleNameConflicts.Contains(conflict))
{
possibleNameConflicts.Add(conflict);
}
}
if (symbol.Kind == SymbolKind.Property)
{
foreach (var conflict in new string[] { "_" + replacementText, "get_" + replacementText, "set_" + replacementText })
{
if (!possibleNameConflicts.Contains(conflict))
{
possibleNameConflicts.Add(conflict);
}
}
}
// in C# we also need to add the valueText because it can be different from the text in source
// e.g. it can contain escaped unicode characters. Otherwise conflicts would be detected for
// v\u0061r and var or similar.
var valueText = replacementText;
var kind = SyntaxFacts.GetKeywordKind(replacementText);
if (kind != SyntaxKind.None)
{
valueText = SyntaxFacts.GetText(kind);
}
else
{
var name = SyntaxFactory.ParseName(replacementText);
if (name.Kind() == SyntaxKind.IdentifierName)
{
valueText = ((IdentifierNameSyntax)name).Identifier.ValueText;
}
}
// this also covers the case of an escaped replacementText
if (valueText != replacementText)
{
possibleNameConflicts.Add(valueText);
}
}
/// <summary>
/// Gets the top most enclosing statement or CrefSyntax as target to call MakeExplicit on.
/// It's either the enclosing statement, or if this statement is inside of a lambda expression, the enclosing
/// statement of this lambda.
/// </summary>
/// <param name="token">The token to get the complexification target for.</param>
/// <returns></returns>
public override SyntaxNode? GetExpansionTargetForLocation(SyntaxToken token)
=> GetExpansionTarget(token);
private static SyntaxNode? GetExpansionTarget(SyntaxToken token)
{
// get the directly enclosing statement
var enclosingStatement = token.GetAncestors(n => n is StatementSyntax).FirstOrDefault();
// System.Func<int, int> myFunc = arg => X;
var possibleLambdaExpression = enclosingStatement == null
? token.GetAncestors(n => n is SimpleLambdaExpressionSyntax || n is ParenthesizedLambdaExpressionSyntax).FirstOrDefault()
: null;
if (possibleLambdaExpression != null)
{
var lambdaExpression = ((LambdaExpressionSyntax)possibleLambdaExpression);
if (lambdaExpression.Body is ExpressionSyntax)
{
return lambdaExpression.Body;
}
}
// int M() => X;
var possibleArrowExpressionClause = enclosingStatement == null
? token.GetAncestors<ArrowExpressionClauseSyntax>().FirstOrDefault()
: null;
if (possibleArrowExpressionClause != null)
{
return possibleArrowExpressionClause.Expression;
}
var enclosingNameMemberCrefOrnull = token.GetAncestors(n => n is NameMemberCrefSyntax).LastOrDefault();
if (enclosingNameMemberCrefOrnull != null)
{
if (token.Parent is TypeSyntax && token.Parent.Parent is TypeSyntax)
{
enclosingNameMemberCrefOrnull = null;
}
}
var enclosingXmlNameAttr = token.GetAncestors(n => n is XmlNameAttributeSyntax).FirstOrDefault();
if (enclosingXmlNameAttr != null)
{
return null;
}
var enclosingInitializer = token.GetAncestors<EqualsValueClauseSyntax>().FirstOrDefault();
if (enclosingStatement == null && enclosingInitializer != null && enclosingInitializer.Parent is VariableDeclaratorSyntax)
{
return enclosingInitializer.Value;
}
var attributeSyntax = token.GetAncestor<AttributeSyntax>();
if (attributeSyntax != null)
{
return attributeSyntax;
}
// there seems to be no statement above this one. Let's see if we can at least get an SimpleNameSyntax
return enclosingStatement ?? enclosingNameMemberCrefOrnull ?? token.GetAncestors(n => n is SimpleNameSyntax).FirstOrDefault();
}
#region "Helper Methods"
public override bool IsIdentifierValid(string replacementText, ISyntaxFactsService syntaxFactsService)
{
// Identifiers we never consider valid to rename to.
switch (replacementText)
{
case "var":
case "dynamic":
case "unmanaged":
case "notnull":
return false;
}
var escapedIdentifier = replacementText.StartsWith("@", StringComparison.Ordinal)
? replacementText : "@" + replacementText;
// Make sure we got an identifier.
if (!syntaxFactsService.IsValidIdentifier(escapedIdentifier))
{
// We still don't have an identifier, so let's fail
return false;
}
return true;
}
/// <summary>
/// Gets the semantic model for the given node.
/// If the node belongs to the syntax tree of the original semantic model, then returns originalSemanticModel.
/// Otherwise, returns a speculative model.
/// The assumption for the later case is that span start position of the given node in it's syntax tree is same as
/// the span start of the original node in the original syntax tree.
/// </summary>
public static SemanticModel? GetSemanticModelForNode(SyntaxNode node, SemanticModel originalSemanticModel)
{
if (node.SyntaxTree == originalSemanticModel.SyntaxTree)
{
// This is possible if the previous rename phase didn't rewrite any nodes in this tree.
return originalSemanticModel;
}
var nodeToSpeculate = node.GetAncestorsOrThis(n => SpeculationAnalyzer.CanSpeculateOnNode(n)).LastOrDefault();
if (nodeToSpeculate == null)
{
if (node.IsKind(SyntaxKind.NameMemberCref, out NameMemberCrefSyntax? nameMember))
{
nodeToSpeculate = nameMember.Name;
}
else if (node.IsKind(SyntaxKind.QualifiedCref, out QualifiedCrefSyntax? qualifiedCref))
{
nodeToSpeculate = qualifiedCref.Container;
}
else if (node.IsKind(SyntaxKind.TypeConstraint, out TypeConstraintSyntax? typeConstraint))
{
nodeToSpeculate = typeConstraint.Type;
}
else if (node is BaseTypeSyntax baseType)
{
nodeToSpeculate = baseType.Type;
}
else
{
return null;
}
}
var isInNamespaceOrTypeContext = SyntaxFacts.IsInNamespaceOrTypeContext(node as ExpressionSyntax);
var position = nodeToSpeculate.SpanStart;
return SpeculationAnalyzer.CreateSpeculativeSemanticModelForNode(nodeToSpeculate, originalSemanticModel, position, isInNamespaceOrTypeContext);
}
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Simplification;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Rename;
using Microsoft.CodeAnalysis.Rename.ConflictEngine;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Rename
{
[ExportLanguageService(typeof(IRenameRewriterLanguageService), LanguageNames.CSharp), Shared]
internal class CSharpRenameConflictLanguageService : AbstractRenameRewriterLanguageService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpRenameConflictLanguageService()
{
}
#region "Annotation"
public override SyntaxNode AnnotateAndRename(RenameRewriterParameters parameters)
{
var renameAnnotationRewriter = new RenameRewriter(parameters);
return renameAnnotationRewriter.Visit(parameters.SyntaxRoot)!;
}
private class RenameRewriter : CSharpSyntaxRewriter
{
private readonly DocumentId _documentId;
private readonly RenameAnnotation _renameRenamableSymbolDeclaration;
private readonly Solution _solution;
private readonly string _replacementText;
private readonly string _originalText;
private readonly ICollection<string> _possibleNameConflicts;
private readonly Dictionary<TextSpan, RenameLocation> _renameLocations;
private readonly ISet<TextSpan> _conflictLocations;
private readonly SemanticModel _semanticModel;
private readonly CancellationToken _cancellationToken;
private readonly ISymbol _renamedSymbol;
private readonly IAliasSymbol? _aliasSymbol;
private readonly Location? _renamableDeclarationLocation;
private readonly RenamedSpansTracker _renameSpansTracker;
private readonly bool _isVerbatim;
private readonly bool _replacementTextValid;
private readonly ISimplificationService _simplificationService;
private readonly ISemanticFactsService _semanticFactsService;
private readonly HashSet<SyntaxToken> _annotatedIdentifierTokens = new();
private readonly HashSet<InvocationExpressionSyntax> _invocationExpressionsNeedingConflictChecks = new();
private readonly AnnotationTable<RenameAnnotation> _renameAnnotations;
/// <summary>
/// Flag indicating if we should perform a rename inside string literals.
/// </summary>
private readonly bool _isRenamingInStrings;
/// <summary>
/// Flag indicating if we should perform a rename inside comment trivia.
/// </summary>
private readonly bool _isRenamingInComments;
/// <summary>
/// A map from spans of tokens needing rename within strings or comments to an optional
/// set of specific sub-spans within the token span that
/// have <see cref="_originalText"/> matches and should be renamed.
/// If this sorted set is null, it indicates that sub-spans to rename within the token span
/// are not available, and a regex match should be performed to rename
/// all <see cref="_originalText"/> matches within the span.
/// </summary>
private readonly ImmutableDictionary<TextSpan, ImmutableSortedSet<TextSpan>?> _stringAndCommentTextSpans;
public bool AnnotateForComplexification
{
get
{
return _skipRenameForComplexification > 0 && !_isProcessingComplexifiedSpans;
}
}
private int _skipRenameForComplexification;
private bool _isProcessingComplexifiedSpans;
private List<(TextSpan oldSpan, TextSpan newSpan)>? _modifiedSubSpans;
private SemanticModel? _speculativeModel;
private int _isProcessingTrivia;
private void AddModifiedSpan(TextSpan oldSpan, TextSpan newSpan)
{
newSpan = new TextSpan(oldSpan.Start, newSpan.Length);
if (!_isProcessingComplexifiedSpans)
{
_renameSpansTracker.AddModifiedSpan(_documentId, oldSpan, newSpan);
}
else
{
RoslynDebug.Assert(_modifiedSubSpans != null);
_modifiedSubSpans.Add((oldSpan, newSpan));
}
}
public RenameRewriter(RenameRewriterParameters parameters)
: base(visitIntoStructuredTrivia: true)
{
_documentId = parameters.Document.Id;
_renameRenamableSymbolDeclaration = parameters.RenamedSymbolDeclarationAnnotation;
_solution = parameters.OriginalSolution;
_replacementText = parameters.ReplacementText;
_originalText = parameters.OriginalText;
_possibleNameConflicts = parameters.PossibleNameConflicts;
_renameLocations = parameters.RenameLocations;
_conflictLocations = parameters.ConflictLocationSpans;
_cancellationToken = parameters.CancellationToken;
_semanticModel = parameters.SemanticModel;
_renamedSymbol = parameters.RenameSymbol;
_replacementTextValid = parameters.ReplacementTextValid;
_renameSpansTracker = parameters.RenameSpansTracker;
_isRenamingInStrings = parameters.OptionSet.RenameInStrings;
_isRenamingInComments = parameters.OptionSet.RenameInComments;
_stringAndCommentTextSpans = parameters.StringAndCommentTextSpans;
_renameAnnotations = parameters.RenameAnnotations;
_aliasSymbol = _renamedSymbol as IAliasSymbol;
_renamableDeclarationLocation = _renamedSymbol.Locations.FirstOrDefault(loc => loc.IsInSource && loc.SourceTree == _semanticModel.SyntaxTree);
_isVerbatim = _replacementText.StartsWith("@", StringComparison.Ordinal);
_simplificationService = parameters.Document.Project.LanguageServices.GetRequiredService<ISimplificationService>();
_semanticFactsService = parameters.Document.Project.LanguageServices.GetRequiredService<ISemanticFactsService>();
}
public override SyntaxNode? Visit(SyntaxNode? node)
{
if (node == null)
{
return node;
}
var isInConflictLambdaBody = false;
var lambdas = node.GetAncestorsOrThis(n => n is SimpleLambdaExpressionSyntax || n is ParenthesizedLambdaExpressionSyntax);
if (lambdas.Count() != 0)
{
foreach (var lambda in lambdas)
{
if (_conflictLocations.Any(cf => cf.Contains(lambda.Span)))
{
isInConflictLambdaBody = true;
break;
}
}
}
var shouldComplexifyNode = ShouldComplexifyNode(node, isInConflictLambdaBody);
SyntaxNode result;
// in case the current node was identified as being a complexification target of
// a previous node, we'll handle it accordingly.
if (shouldComplexifyNode)
{
_skipRenameForComplexification++;
result = base.Visit(node)!;
_skipRenameForComplexification--;
result = Complexify(node, result);
}
else
{
result = base.Visit(node)!;
}
return result;
}
private bool ShouldComplexifyNode(SyntaxNode node, bool isInConflictLambdaBody)
{
return !isInConflictLambdaBody &&
_skipRenameForComplexification == 0 &&
!_isProcessingComplexifiedSpans &&
_conflictLocations.Contains(node.Span) &&
(node is AttributeSyntax ||
node is AttributeArgumentSyntax ||
node is ConstructorInitializerSyntax ||
node is ExpressionSyntax ||
node is FieldDeclarationSyntax ||
node is StatementSyntax ||
node is CrefSyntax ||
node is XmlNameAttributeSyntax ||
node is TypeConstraintSyntax ||
node is BaseTypeSyntax);
}
public override SyntaxToken VisitToken(SyntaxToken token)
{
var shouldCheckTrivia = _stringAndCommentTextSpans.ContainsKey(token.Span);
_isProcessingTrivia += shouldCheckTrivia ? 1 : 0;
var newToken = base.VisitToken(token);
_isProcessingTrivia -= shouldCheckTrivia ? 1 : 0;
// Handle Alias annotations
newToken = UpdateAliasAnnotation(newToken);
// Rename matches in strings and comments
newToken = RenameWithinToken(token, newToken);
// We don't want to annotate XmlName with RenameActionAnnotation
if (newToken.Parent.IsKind(SyntaxKind.XmlName))
{
return newToken;
}
var isRenameLocation = IsRenameLocation(token);
// if this is a reference location, or the identifier token's name could possibly
// be a conflict, we need to process this token
var isOldText = token.ValueText == _originalText;
var tokenNeedsConflictCheck =
isRenameLocation ||
token.ValueText == _replacementText ||
isOldText ||
_possibleNameConflicts.Contains(token.ValueText) ||
IsPossiblyDestructorConflict(token) ||
IsPropertyAccessorNameConflict(token);
if (tokenNeedsConflictCheck)
{
newToken = RenameAndAnnotateAsync(token, newToken, isRenameLocation, isOldText).WaitAndGetResult_CanCallOnBackground(_cancellationToken);
if (!_isProcessingComplexifiedSpans)
{
_invocationExpressionsNeedingConflictChecks.AddRange(token.GetAncestors<InvocationExpressionSyntax>());
}
}
return newToken;
}
private bool IsPropertyAccessorNameConflict(SyntaxToken token)
=> IsGetPropertyAccessorNameConflict(token)
|| IsSetPropertyAccessorNameConflict(token)
|| IsInitPropertyAccessorNameConflict(token);
private bool IsGetPropertyAccessorNameConflict(SyntaxToken token)
=> token.IsKind(SyntaxKind.GetKeyword)
&& IsNameConflictWithProperty("get", token.Parent as AccessorDeclarationSyntax);
private bool IsSetPropertyAccessorNameConflict(SyntaxToken token)
=> token.IsKind(SyntaxKind.SetKeyword)
&& IsNameConflictWithProperty("set", token.Parent as AccessorDeclarationSyntax);
private bool IsInitPropertyAccessorNameConflict(SyntaxToken token)
=> token.IsKind(SyntaxKind.InitKeyword)
// using "set" here is intentional. The compiler generates set_PropName for both set and init accessors.
&& IsNameConflictWithProperty("set", token.Parent as AccessorDeclarationSyntax);
private bool IsNameConflictWithProperty(string prefix, AccessorDeclarationSyntax? accessor)
=> accessor?.Parent?.Parent is PropertyDeclarationSyntax property // 3 null checks in one: accessor -> accessor list -> property declaration
&& _replacementText.Equals(prefix + "_" + property.Identifier.Text, StringComparison.Ordinal);
private bool IsPossiblyDestructorConflict(SyntaxToken token)
{
return _replacementText == "Finalize" &&
token.IsKind(SyntaxKind.IdentifierToken) &&
token.Parent.IsKind(SyntaxKind.DestructorDeclaration);
}
private SyntaxNode Complexify(SyntaxNode originalNode, SyntaxNode newNode)
{
_isProcessingComplexifiedSpans = true;
_modifiedSubSpans = new List<(TextSpan oldSpan, TextSpan newSpan)>();
var annotation = new SyntaxAnnotation();
newNode = newNode.WithAdditionalAnnotations(annotation);
var speculativeTree = originalNode.SyntaxTree.GetRoot(_cancellationToken).ReplaceNode(originalNode, newNode);
newNode = speculativeTree.GetAnnotatedNodes<SyntaxNode>(annotation).First();
_speculativeModel = GetSemanticModelForNode(newNode, _semanticModel);
RoslynDebug.Assert(_speculativeModel != null, "expanding a syntax node which cannot be speculated?");
var oldSpan = originalNode.Span;
var expandParameter = originalNode.GetAncestorsOrThis(n => n is SimpleLambdaExpressionSyntax || n is ParenthesizedLambdaExpressionSyntax).Count() == 0;
newNode = _simplificationService.Expand(newNode,
_speculativeModel,
annotationForReplacedAliasIdentifier: null,
expandInsideNode: null,
expandParameter: expandParameter,
cancellationToken: _cancellationToken);
speculativeTree = originalNode.SyntaxTree.GetRoot(_cancellationToken).ReplaceNode(originalNode, newNode);
newNode = speculativeTree.GetAnnotatedNodes<SyntaxNode>(annotation).First();
_speculativeModel = GetSemanticModelForNode(newNode, _semanticModel);
newNode = base.Visit(newNode)!;
var newSpan = newNode.Span;
newNode = newNode.WithoutAnnotations(annotation);
newNode = _renameAnnotations.WithAdditionalAnnotations(newNode, new RenameNodeSimplificationAnnotation() { OriginalTextSpan = oldSpan });
_renameSpansTracker.AddComplexifiedSpan(_documentId, oldSpan, new TextSpan(oldSpan.Start, newSpan.Length), _modifiedSubSpans);
_modifiedSubSpans = null;
_isProcessingComplexifiedSpans = false;
_speculativeModel = null;
return newNode;
}
private async Task<SyntaxToken> RenameAndAnnotateAsync(SyntaxToken token, SyntaxToken newToken, bool isRenameLocation, bool isOldText)
{
try
{
if (_isProcessingComplexifiedSpans)
{
// Rename Token
if (isRenameLocation)
{
var annotation = _renameAnnotations.GetAnnotations(token).OfType<RenameActionAnnotation>().FirstOrDefault();
if (annotation != null)
{
newToken = RenameToken(token, newToken, annotation.Prefix, annotation.Suffix);
AddModifiedSpan(annotation.OriginalSpan, newToken.Span);
}
else
{
newToken = RenameToken(token, newToken, prefix: null, suffix: null);
}
}
return newToken;
}
var symbols = RenameUtilities.GetSymbolsTouchingPosition(token.Span.Start, _semanticModel, _solution.Workspace, _cancellationToken);
string? suffix = null;
var prefix = isRenameLocation && _renameLocations[token.Span].IsRenamableAccessor
? newToken.ValueText.Substring(0, newToken.ValueText.IndexOf('_') + 1)
: null;
if (symbols.Length == 1)
{
var symbol = symbols[0];
if (symbol.IsConstructor())
{
symbol = symbol.ContainingSymbol;
}
var sourceDefinition = await SymbolFinder.FindSourceDefinitionAsync(symbol, _solution, _cancellationToken).ConfigureAwait(false);
symbol = sourceDefinition ?? symbol;
if (symbol is INamedTypeSymbol namedTypeSymbol)
{
if (namedTypeSymbol.IsImplicitlyDeclared &&
namedTypeSymbol.IsDelegateType() &&
namedTypeSymbol.AssociatedSymbol != null)
{
suffix = "EventHandler";
}
}
// This is a conflicting namespace declaration token. Even if the rename results in conflict with this namespace
// conflict is not shown for the namespace so we are tracking this token
if (!isRenameLocation && symbol is INamespaceSymbol && token.GetPreviousToken().IsKind(SyntaxKind.NamespaceKeyword))
{
return newToken;
}
}
// Rename Token
if (isRenameLocation && !this.AnnotateForComplexification)
{
var oldSpan = token.Span;
newToken = RenameToken(token, newToken, prefix, suffix);
AddModifiedSpan(oldSpan, newToken.Span);
}
var renameDeclarationLocations = await
ConflictResolver.CreateDeclarationLocationAnnotationsAsync(_solution, symbols, _cancellationToken).ConfigureAwait(false);
var isNamespaceDeclarationReference = false;
if (isRenameLocation && token.GetPreviousToken().IsKind(SyntaxKind.NamespaceKeyword))
{
isNamespaceDeclarationReference = true;
}
var isMemberGroupReference = _semanticFactsService.IsInsideNameOfExpression(_semanticModel, token.Parent, _cancellationToken);
var renameAnnotation =
new RenameActionAnnotation(
token.Span,
isRenameLocation,
prefix,
suffix,
renameDeclarationLocations: renameDeclarationLocations,
isOriginalTextLocation: isOldText,
isNamespaceDeclarationReference: isNamespaceDeclarationReference,
isInvocationExpression: false,
isMemberGroupReference: isMemberGroupReference);
newToken = _renameAnnotations.WithAdditionalAnnotations(newToken, renameAnnotation, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = token.Span });
_annotatedIdentifierTokens.Add(token);
if (_renameRenamableSymbolDeclaration != null && _renamableDeclarationLocation == token.GetLocation())
{
newToken = _renameAnnotations.WithAdditionalAnnotations(newToken, _renameRenamableSymbolDeclaration);
}
return newToken;
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private RenameActionAnnotation? GetAnnotationForInvocationExpression(InvocationExpressionSyntax invocationExpression)
{
var identifierToken = default(SyntaxToken);
var expressionOfInvocation = invocationExpression.Expression;
while (expressionOfInvocation != null)
{
switch (expressionOfInvocation.Kind())
{
case SyntaxKind.IdentifierName:
case SyntaxKind.GenericName:
identifierToken = ((SimpleNameSyntax)expressionOfInvocation).Identifier;
break;
case SyntaxKind.SimpleMemberAccessExpression:
identifierToken = ((MemberAccessExpressionSyntax)expressionOfInvocation).Name.Identifier;
break;
case SyntaxKind.QualifiedName:
identifierToken = ((QualifiedNameSyntax)expressionOfInvocation).Right.Identifier;
break;
case SyntaxKind.AliasQualifiedName:
identifierToken = ((AliasQualifiedNameSyntax)expressionOfInvocation).Name.Identifier;
break;
case SyntaxKind.ParenthesizedExpression:
expressionOfInvocation = ((ParenthesizedExpressionSyntax)expressionOfInvocation).Expression;
continue;
}
break;
}
if (identifierToken != default && !_annotatedIdentifierTokens.Contains(identifierToken))
{
var symbolInfo = _semanticModel.GetSymbolInfo(invocationExpression, _cancellationToken);
IEnumerable<ISymbol> symbols;
if (symbolInfo.Symbol == null)
{
return null;
}
else
{
symbols = SpecializedCollections.SingletonEnumerable(symbolInfo.Symbol);
}
var renameDeclarationLocations =
ConflictResolver.CreateDeclarationLocationAnnotationsAsync(
_solution,
symbols,
_cancellationToken)
.WaitAndGetResult_CanCallOnBackground(_cancellationToken);
var renameAnnotation = new RenameActionAnnotation(
identifierToken.Span,
isRenameLocation: false,
prefix: null,
suffix: null,
renameDeclarationLocations: renameDeclarationLocations,
isOriginalTextLocation: false,
isNamespaceDeclarationReference: false,
isInvocationExpression: true,
isMemberGroupReference: false);
return renameAnnotation;
}
return null;
}
public override SyntaxNode? VisitInvocationExpression(InvocationExpressionSyntax node)
{
var result = base.VisitInvocationExpression(node);
RoslynDebug.AssertNotNull(result);
if (_invocationExpressionsNeedingConflictChecks.Contains(node))
{
var renameAnnotation = GetAnnotationForInvocationExpression(node);
if (renameAnnotation != null)
{
result = _renameAnnotations.WithAdditionalAnnotations(result, renameAnnotation);
}
}
return result;
}
private bool IsRenameLocation(SyntaxToken token)
{
if (!_isProcessingComplexifiedSpans)
{
return _renameLocations.ContainsKey(token.Span);
}
else
{
RoslynDebug.Assert(_speculativeModel != null);
if (token.HasAnnotations(AliasAnnotation.Kind))
{
return false;
}
if (token.HasAnnotations(RenameAnnotation.Kind))
{
return _renameAnnotations.GetAnnotations(token).OfType<RenameActionAnnotation>().First().IsRenameLocation;
}
if (token.Parent is SimpleNameSyntax && !token.IsKind(SyntaxKind.GlobalKeyword) && token.Parent.Parent.IsKind(SyntaxKind.AliasQualifiedName, SyntaxKind.QualifiedCref, SyntaxKind.QualifiedName))
{
var symbol = _speculativeModel.GetSymbolInfo(token.Parent, _cancellationToken).Symbol;
if (symbol != null && _renamedSymbol.Kind != SymbolKind.Local && _renamedSymbol.Kind != SymbolKind.RangeVariable &&
(Equals(symbol, _renamedSymbol) || SymbolKey.GetComparer(ignoreCase: true, ignoreAssemblyKeys: false).Equals(symbol.GetSymbolKey(), _renamedSymbol.GetSymbolKey())))
{
return true;
}
}
return false;
}
}
private SyntaxToken UpdateAliasAnnotation(SyntaxToken newToken)
{
if (_aliasSymbol != null && !this.AnnotateForComplexification && newToken.HasAnnotations(AliasAnnotation.Kind))
{
newToken = RenameUtilities.UpdateAliasAnnotation(newToken, _aliasSymbol, _replacementText);
}
return newToken;
}
private SyntaxToken RenameToken(SyntaxToken oldToken, SyntaxToken newToken, string? prefix, string? suffix)
{
var parent = oldToken.Parent!;
var currentNewIdentifier = _isVerbatim ? _replacementText.Substring(1) : _replacementText;
var oldIdentifier = newToken.ValueText;
var isAttributeName = SyntaxFacts.IsAttributeName(parent);
if (isAttributeName)
{
if (oldIdentifier != _renamedSymbol.Name)
{
if (currentNewIdentifier.TryGetWithoutAttributeSuffix(out var withoutSuffix))
{
currentNewIdentifier = withoutSuffix;
}
}
}
else
{
if (!string.IsNullOrEmpty(prefix))
{
currentNewIdentifier = prefix + currentNewIdentifier;
}
if (!string.IsNullOrEmpty(suffix))
{
currentNewIdentifier += suffix;
}
}
// determine the canonical identifier name (unescaped, no unicode escaping, ...)
var valueText = currentNewIdentifier;
var kind = SyntaxFacts.GetKeywordKind(currentNewIdentifier);
if (kind != SyntaxKind.None)
{
valueText = SyntaxFacts.GetText(kind);
}
else
{
var parsedIdentifier = SyntaxFactory.ParseName(currentNewIdentifier);
if (parsedIdentifier.IsKind(SyntaxKind.IdentifierName, out IdentifierNameSyntax? identifierName))
{
valueText = identifierName.Identifier.ValueText;
}
}
// TODO: we can't use escaped unicode characters in xml doc comments, so we need to pass the valuetext as text as well.
// <param name="\u... is invalid.
// if it's an attribute name we don't mess with the escaping because it might change overload resolution
newToken = _isVerbatim || (isAttributeName && oldToken.IsVerbatimIdentifier())
? newToken.CopyAnnotationsTo(SyntaxFactory.VerbatimIdentifier(newToken.LeadingTrivia, currentNewIdentifier, valueText, newToken.TrailingTrivia))
: newToken.CopyAnnotationsTo(SyntaxFactory.Identifier(newToken.LeadingTrivia, SyntaxKind.IdentifierToken, currentNewIdentifier, valueText, newToken.TrailingTrivia));
if (_replacementTextValid)
{
if (newToken.IsVerbatimIdentifier())
{
// a reference location should always be tried to be unescaped, whether it was escaped before rename
// or the replacement itself is escaped.
newToken = newToken.WithAdditionalAnnotations(Simplifier.Annotation);
}
else
{
newToken = CSharpSimplificationHelpers.TryEscapeIdentifierToken(newToken, parent);
}
}
return newToken;
}
private SyntaxToken RenameInStringLiteral(SyntaxToken oldToken, SyntaxToken newToken, ImmutableSortedSet<TextSpan>? subSpansToReplace, Func<SyntaxTriviaList, string, string, SyntaxTriviaList, SyntaxToken> createNewStringLiteral)
{
var originalString = newToken.ToString();
var replacedString = RenameLocations.ReferenceProcessing.ReplaceMatchingSubStrings(originalString, _originalText, _replacementText, subSpansToReplace);
if (replacedString != originalString)
{
var oldSpan = oldToken.Span;
newToken = createNewStringLiteral(newToken.LeadingTrivia, replacedString, replacedString, newToken.TrailingTrivia);
AddModifiedSpan(oldSpan, newToken.Span);
return newToken.CopyAnnotationsTo(_renameAnnotations.WithAdditionalAnnotations(newToken, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = oldSpan }));
}
return newToken;
}
private SyntaxToken RenameInTrivia(SyntaxToken token, IEnumerable<SyntaxTrivia> leadingOrTrailingTriviaList)
{
return token.ReplaceTrivia(leadingOrTrailingTriviaList, (oldTrivia, newTrivia) =>
{
if (newTrivia.IsSingleLineComment() || newTrivia.IsMultiLineComment())
{
return RenameInCommentTrivia(newTrivia);
}
return newTrivia;
});
}
private SyntaxTrivia RenameInCommentTrivia(SyntaxTrivia trivia)
{
var originalString = trivia.ToString();
var replacedString = RenameLocations.ReferenceProcessing.ReplaceMatchingSubStrings(originalString, _originalText, _replacementText);
if (replacedString != originalString)
{
var oldSpan = trivia.Span;
var newTrivia = SyntaxFactory.Comment(replacedString);
AddModifiedSpan(oldSpan, newTrivia.Span);
return trivia.CopyAnnotationsTo(_renameAnnotations.WithAdditionalAnnotations(newTrivia, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = oldSpan }));
}
return trivia;
}
private SyntaxToken RenameWithinToken(SyntaxToken oldToken, SyntaxToken newToken)
{
ImmutableSortedSet<TextSpan>? subSpansToReplace = null;
if (_isProcessingComplexifiedSpans ||
(_isProcessingTrivia == 0 &&
!_stringAndCommentTextSpans.TryGetValue(oldToken.Span, out subSpansToReplace)))
{
return newToken;
}
if (_isRenamingInStrings || subSpansToReplace?.Count > 0)
{
if (newToken.IsKind(SyntaxKind.StringLiteralToken))
{
newToken = RenameInStringLiteral(oldToken, newToken, subSpansToReplace, SyntaxFactory.Literal);
}
else if (newToken.IsKind(SyntaxKind.InterpolatedStringTextToken))
{
newToken = RenameInStringLiteral(oldToken, newToken, subSpansToReplace, (leadingTrivia, text, value, trailingTrivia) =>
SyntaxFactory.Token(newToken.LeadingTrivia, SyntaxKind.InterpolatedStringTextToken, text, value, newToken.TrailingTrivia));
}
}
if (_isRenamingInComments)
{
if (newToken.IsKind(SyntaxKind.XmlTextLiteralToken))
{
newToken = RenameInStringLiteral(oldToken, newToken, subSpansToReplace, SyntaxFactory.XmlTextLiteral);
}
else if (newToken.IsKind(SyntaxKind.IdentifierToken) && newToken.Parent.IsKind(SyntaxKind.XmlName) && newToken.ValueText == _originalText)
{
var newIdentifierToken = SyntaxFactory.Identifier(newToken.LeadingTrivia, _replacementText, newToken.TrailingTrivia);
newToken = newToken.CopyAnnotationsTo(_renameAnnotations.WithAdditionalAnnotations(newIdentifierToken, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = oldToken.Span }));
AddModifiedSpan(oldToken.Span, newToken.Span);
}
if (newToken.HasLeadingTrivia)
{
var updatedToken = RenameInTrivia(oldToken, oldToken.LeadingTrivia);
if (updatedToken != oldToken)
{
newToken = newToken.WithLeadingTrivia(updatedToken.LeadingTrivia);
}
}
if (newToken.HasTrailingTrivia)
{
var updatedToken = RenameInTrivia(oldToken, oldToken.TrailingTrivia);
if (updatedToken != oldToken)
{
newToken = newToken.WithTrailingTrivia(updatedToken.TrailingTrivia);
}
}
}
return newToken;
}
}
#endregion
#region "Declaration Conflicts"
public override bool LocalVariableConflict(
SyntaxToken token,
IEnumerable<ISymbol> newReferencedSymbols)
{
if (token.Parent.IsKind(SyntaxKind.IdentifierName, out ExpressionSyntax? expression) &&
token.Parent.IsParentKind(SyntaxKind.InvocationExpression) &&
token.GetPreviousToken().Kind() != SyntaxKind.DotToken &&
token.GetNextToken().Kind() != SyntaxKind.DotToken)
{
var enclosingMemberDeclaration = expression.FirstAncestorOrSelf<MemberDeclarationSyntax>();
if (enclosingMemberDeclaration != null)
{
var locals = enclosingMemberDeclaration.GetLocalDeclarationMap()[token.ValueText];
if (locals.Length > 0)
{
// This unqualified invocation name matches the name of an existing local
// or parameter. Report a conflict if the matching local/parameter is not
// a delegate type.
var relevantLocals = newReferencedSymbols
.Where(s => s.MatchesKind(SymbolKind.Local, SymbolKind.Parameter) && s.Name == token.ValueText);
if (relevantLocals.Count() != 1)
{
return true;
}
var matchingLocal = relevantLocals.Single();
var invocationTargetsLocalOfDelegateType =
(matchingLocal.IsKind(SymbolKind.Local) && ((ILocalSymbol)matchingLocal).Type.IsDelegateType()) ||
(matchingLocal.IsKind(SymbolKind.Parameter) && ((IParameterSymbol)matchingLocal).Type.IsDelegateType());
return !invocationTargetsLocalOfDelegateType;
}
}
}
return false;
}
public override async Task<ImmutableArray<Location>> ComputeDeclarationConflictsAsync(
string replacementText,
ISymbol renamedSymbol,
ISymbol renameSymbol,
IEnumerable<ISymbol> referencedSymbols,
Solution baseSolution,
Solution newSolution,
IDictionary<Location, Location> reverseMappedLocations,
CancellationToken cancellationToken)
{
try
{
using var _ = ArrayBuilder<Location>.GetInstance(out var conflicts);
// If we're renaming a named type, we can conflict with members w/ our same name. Note:
// this doesn't apply to enums.
if (renamedSymbol is INamedTypeSymbol { TypeKind: not TypeKind.Enum } namedType)
AddSymbolSourceSpans(conflicts, namedType.GetMembers(renamedSymbol.Name), reverseMappedLocations);
// If we're contained in a named type (we may be a named type ourself!) then we have a
// conflict. NOTE(cyrusn): This does not apply to enums.
if (renamedSymbol.ContainingSymbol is INamedTypeSymbol { TypeKind: not TypeKind.Enum } containingNamedType &&
containingNamedType.Name == renamedSymbol.Name)
{
AddSymbolSourceSpans(conflicts, SpecializedCollections.SingletonEnumerable(containingNamedType), reverseMappedLocations);
}
if (renamedSymbol.Kind == SymbolKind.Parameter ||
renamedSymbol.Kind == SymbolKind.Local ||
renamedSymbol.Kind == SymbolKind.RangeVariable)
{
var token = renamedSymbol.Locations.Single().FindToken(cancellationToken);
var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
var visitor = new LocalConflictVisitor(token);
visitor.Visit(memberDeclaration);
conflicts.AddRange(visitor.ConflictingTokens.Select(t => reverseMappedLocations[t.GetLocation()]));
// If this is a parameter symbol for a partial method definition, be sure we visited
// the implementation part's body.
if (renamedSymbol is IParameterSymbol renamedParameterSymbol &&
renamedSymbol.ContainingSymbol is IMethodSymbol methodSymbol &&
methodSymbol.PartialImplementationPart != null)
{
var matchingParameterSymbol = methodSymbol.PartialImplementationPart.Parameters[renamedParameterSymbol.Ordinal];
token = matchingParameterSymbol.Locations.Single().FindToken(cancellationToken);
memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
visitor = new LocalConflictVisitor(token);
visitor.Visit(memberDeclaration);
conflicts.AddRange(visitor.ConflictingTokens.Select(t => reverseMappedLocations[t.GetLocation()]));
}
}
else if (renamedSymbol.Kind == SymbolKind.Label)
{
var token = renamedSymbol.Locations.Single().FindToken(cancellationToken);
var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
var visitor = new LabelConflictVisitor(token);
visitor.Visit(memberDeclaration);
conflicts.AddRange(visitor.ConflictingTokens.Select(t => reverseMappedLocations[t.GetLocation()]));
}
else if (renamedSymbol.Kind == SymbolKind.Method)
{
conflicts.AddRange(DeclarationConflictHelpers.GetMembersWithConflictingSignatures((IMethodSymbol)renamedSymbol, trimOptionalParameters: false).Select(t => reverseMappedLocations[t]));
// we allow renaming overrides of VB property accessors with parameters in C#.
// VB has a special rule that properties are not allowed to have the same name as any of the parameters.
// Because this declaration in C# affects the property declaration in VB, we need to check this VB rule here in C#.
var properties = new List<ISymbol>();
foreach (var referencedSymbol in referencedSymbols)
{
var property = await RenameLocations.ReferenceProcessing.TryGetPropertyFromAccessorOrAnOverrideAsync(
referencedSymbol, baseSolution, cancellationToken).ConfigureAwait(false);
if (property != null)
properties.Add(property);
}
AddConflictingParametersOfProperties(properties.Distinct(), replacementText, conflicts);
}
else if (renamedSymbol.Kind == SymbolKind.Alias)
{
// in C# there can only be one using with the same alias name in the same block (top of file of namespace).
// It's ok to redefine the alias in different blocks.
var location = renamedSymbol.Locations.Single();
var tree = location.SourceTree;
Contract.ThrowIfNull(tree);
var token = await tree.GetTouchingTokenAsync(location.SourceSpan.Start, cancellationToken, findInsideTrivia: true).ConfigureAwait(false);
var currentUsing = (UsingDirectiveSyntax)token.Parent!.Parent!.Parent!;
var namespaceDecl = token.Parent.Ancestors().OfType<BaseNamespaceDeclarationSyntax>().FirstOrDefault();
SyntaxList<UsingDirectiveSyntax> usings;
if (namespaceDecl != null)
{
usings = namespaceDecl.Usings;
}
else
{
var compilationUnit = (CompilationUnitSyntax)await tree.GetRootAsync(cancellationToken).ConfigureAwait(false);
usings = compilationUnit.Usings;
}
foreach (var usingDirective in usings)
{
if (usingDirective.Alias != null && usingDirective != currentUsing)
{
if (usingDirective.Alias.Name.Identifier.ValueText == currentUsing.Alias!.Name.Identifier.ValueText)
conflicts.Add(reverseMappedLocations[usingDirective.Alias.Name.GetLocation()]);
}
}
}
else if (renamedSymbol.Kind == SymbolKind.TypeParameter)
{
foreach (var location in renamedSymbol.Locations)
{
var token = await location.SourceTree!.GetTouchingTokenAsync(location.SourceSpan.Start, cancellationToken, findInsideTrivia: true).ConfigureAwait(false);
var currentTypeParameter = token.Parent!;
foreach (var typeParameter in ((TypeParameterListSyntax)currentTypeParameter.Parent!).Parameters)
{
if (typeParameter != currentTypeParameter && token.ValueText == typeParameter.Identifier.ValueText)
conflicts.Add(reverseMappedLocations[typeParameter.Identifier.GetLocation()]);
}
}
}
// if the renamed symbol is a type member, it's name should not conflict with a type parameter
if (renamedSymbol.ContainingType != null && renamedSymbol.ContainingType.GetMembers(renamedSymbol.Name).Contains(renamedSymbol))
{
var conflictingLocations = renamedSymbol.ContainingType.TypeParameters
.Where(t => t.Name == renamedSymbol.Name)
.SelectMany(t => t.Locations);
foreach (var location in conflictingLocations)
{
var typeParameterToken = location.FindToken(cancellationToken);
conflicts.Add(reverseMappedLocations[typeParameterToken.GetLocation()]);
}
}
return conflicts.ToImmutable();
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
private static async Task<ISymbol?> GetVBPropertyFromAccessorOrAnOverrideAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken)
{
try
{
if (symbol.IsPropertyAccessor())
{
var property = ((IMethodSymbol)symbol).AssociatedSymbol!;
return property.Language == LanguageNames.VisualBasic ? property : null;
}
if (symbol.IsOverride && symbol.GetOverriddenMember() != null)
{
var originalSourceSymbol = await SymbolFinder.FindSourceDefinitionAsync(symbol.GetOverriddenMember(), solution, cancellationToken).ConfigureAwait(false);
if (originalSourceSymbol != null)
{
return await GetVBPropertyFromAccessorOrAnOverrideAsync(originalSourceSymbol, solution, cancellationToken).ConfigureAwait(false);
}
}
return null;
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
private static void AddSymbolSourceSpans(
ArrayBuilder<Location> conflicts, IEnumerable<ISymbol> symbols,
IDictionary<Location, Location> reverseMappedLocations)
{
foreach (var symbol in symbols)
{
foreach (var location in symbol.Locations)
{
// reverseMappedLocations may not contain the location if the location's token
// does not contain the text of it's name (e.g. the getter of "int X { get; }"
// does not contain the text "get_X" so conflicting renames to "get_X" will not
// have added the getter to reverseMappedLocations).
if (location.IsInSource && reverseMappedLocations.ContainsKey(location))
{
conflicts.Add(reverseMappedLocations[location]);
}
}
}
}
public override async Task<ImmutableArray<Location>> ComputeImplicitReferenceConflictsAsync(
ISymbol renameSymbol, ISymbol renamedSymbol, IEnumerable<ReferenceLocation> implicitReferenceLocations, CancellationToken cancellationToken)
{
// Handle renaming of symbols used for foreach
var implicitReferencesMightConflict = renameSymbol.Kind == SymbolKind.Property &&
string.Compare(renameSymbol.Name, "Current", StringComparison.OrdinalIgnoreCase) == 0;
implicitReferencesMightConflict =
implicitReferencesMightConflict ||
(renameSymbol.Kind == SymbolKind.Method &&
(string.Compare(renameSymbol.Name, WellKnownMemberNames.MoveNextMethodName, StringComparison.OrdinalIgnoreCase) == 0 ||
string.Compare(renameSymbol.Name, WellKnownMemberNames.GetEnumeratorMethodName, StringComparison.OrdinalIgnoreCase) == 0 ||
string.Compare(renameSymbol.Name, WellKnownMemberNames.GetAwaiter, StringComparison.OrdinalIgnoreCase) == 0 ||
string.Compare(renameSymbol.Name, WellKnownMemberNames.DeconstructMethodName, StringComparison.OrdinalIgnoreCase) == 0));
// TODO: handle Dispose for using statement and Add methods for collection initializers.
if (implicitReferencesMightConflict)
{
if (renamedSymbol.Name != renameSymbol.Name)
{
foreach (var implicitReferenceLocation in implicitReferenceLocations)
{
var token = await implicitReferenceLocation.Location.SourceTree!.GetTouchingTokenAsync(
implicitReferenceLocation.Location.SourceSpan.Start, cancellationToken, findInsideTrivia: false).ConfigureAwait(false);
switch (token.Kind())
{
case SyntaxKind.ForEachKeyword:
return ImmutableArray.Create(((CommonForEachStatementSyntax)token.Parent!).Expression.GetLocation());
case SyntaxKind.AwaitKeyword:
return ImmutableArray.Create(token.GetLocation());
}
if (token.Parent.IsInDeconstructionLeft(out var deconstructionLeft))
{
return ImmutableArray.Create(deconstructionLeft.GetLocation());
}
}
}
}
return ImmutableArray<Location>.Empty;
}
public override ImmutableArray<Location> ComputePossibleImplicitUsageConflicts(
ISymbol renamedSymbol,
SemanticModel semanticModel,
Location originalDeclarationLocation,
int newDeclarationLocationStartingPosition,
CancellationToken cancellationToken)
{
// TODO: support other implicitly used methods like dispose
if ((renamedSymbol.Name == "MoveNext" || renamedSymbol.Name == "GetEnumerator" || renamedSymbol.Name == "Current") && renamedSymbol.GetAllTypeArguments().Length == 0)
{
// TODO: partial methods currently only show the location where the rename happens as a conflict.
// Consider showing both locations as a conflict.
var baseType = renamedSymbol.ContainingType?.GetBaseTypes().FirstOrDefault();
if (baseType != null)
{
var implicitSymbols = semanticModel.LookupSymbols(
newDeclarationLocationStartingPosition,
baseType,
renamedSymbol.Name)
.Where(sym => !sym.Equals(renamedSymbol));
foreach (var symbol in implicitSymbols)
{
if (symbol.GetAllTypeArguments().Length != 0)
{
continue;
}
if (symbol.Kind == SymbolKind.Method)
{
var method = (IMethodSymbol)symbol;
if (symbol.Name == "MoveNext")
{
if (!method.ReturnsVoid && !method.Parameters.Any() && method.ReturnType.SpecialType == SpecialType.System_Boolean)
{
return ImmutableArray.Create(originalDeclarationLocation);
}
}
else if (symbol.Name == "GetEnumerator")
{
// we are a bit pessimistic here.
// To be sure we would need to check if the returned type is having a MoveNext and Current as required by foreach
if (!method.ReturnsVoid &&
!method.Parameters.Any())
{
return ImmutableArray.Create(originalDeclarationLocation);
}
}
}
else if (symbol.Kind == SymbolKind.Property && symbol.Name == "Current")
{
var property = (IPropertySymbol)symbol;
if (!property.Parameters.Any() && !property.IsWriteOnly)
{
return ImmutableArray.Create(originalDeclarationLocation);
}
}
}
}
}
return ImmutableArray<Location>.Empty;
}
#endregion
public override void TryAddPossibleNameConflicts(ISymbol symbol, string replacementText, ICollection<string> possibleNameConflicts)
{
if (replacementText.EndsWith("Attribute", StringComparison.Ordinal) && replacementText.Length > 9)
{
var conflict = replacementText.Substring(0, replacementText.Length - 9);
if (!possibleNameConflicts.Contains(conflict))
{
possibleNameConflicts.Add(conflict);
}
}
if (symbol.Kind == SymbolKind.Property)
{
foreach (var conflict in new string[] { "_" + replacementText, "get_" + replacementText, "set_" + replacementText })
{
if (!possibleNameConflicts.Contains(conflict))
{
possibleNameConflicts.Add(conflict);
}
}
}
// in C# we also need to add the valueText because it can be different from the text in source
// e.g. it can contain escaped unicode characters. Otherwise conflicts would be detected for
// v\u0061r and var or similar.
var valueText = replacementText;
var kind = SyntaxFacts.GetKeywordKind(replacementText);
if (kind != SyntaxKind.None)
{
valueText = SyntaxFacts.GetText(kind);
}
else
{
var name = SyntaxFactory.ParseName(replacementText);
if (name.Kind() == SyntaxKind.IdentifierName)
{
valueText = ((IdentifierNameSyntax)name).Identifier.ValueText;
}
}
// this also covers the case of an escaped replacementText
if (valueText != replacementText)
{
possibleNameConflicts.Add(valueText);
}
}
/// <summary>
/// Gets the top most enclosing statement or CrefSyntax as target to call MakeExplicit on.
/// It's either the enclosing statement, or if this statement is inside of a lambda expression, the enclosing
/// statement of this lambda.
/// </summary>
/// <param name="token">The token to get the complexification target for.</param>
/// <returns></returns>
public override SyntaxNode? GetExpansionTargetForLocation(SyntaxToken token)
=> GetExpansionTarget(token);
private static SyntaxNode? GetExpansionTarget(SyntaxToken token)
{
// get the directly enclosing statement
var enclosingStatement = token.GetAncestors(n => n is StatementSyntax).FirstOrDefault();
// System.Func<int, int> myFunc = arg => X;
var possibleLambdaExpression = enclosingStatement == null
? token.GetAncestors(n => n is SimpleLambdaExpressionSyntax || n is ParenthesizedLambdaExpressionSyntax).FirstOrDefault()
: null;
if (possibleLambdaExpression != null)
{
var lambdaExpression = ((LambdaExpressionSyntax)possibleLambdaExpression);
if (lambdaExpression.Body is ExpressionSyntax)
{
return lambdaExpression.Body;
}
}
// int M() => X;
var possibleArrowExpressionClause = enclosingStatement == null
? token.GetAncestors<ArrowExpressionClauseSyntax>().FirstOrDefault()
: null;
if (possibleArrowExpressionClause != null)
{
return possibleArrowExpressionClause.Expression;
}
var enclosingNameMemberCrefOrnull = token.GetAncestors(n => n is NameMemberCrefSyntax).LastOrDefault();
if (enclosingNameMemberCrefOrnull != null)
{
if (token.Parent is TypeSyntax && token.Parent.Parent is TypeSyntax)
{
enclosingNameMemberCrefOrnull = null;
}
}
var enclosingXmlNameAttr = token.GetAncestors(n => n is XmlNameAttributeSyntax).FirstOrDefault();
if (enclosingXmlNameAttr != null)
{
return null;
}
var enclosingInitializer = token.GetAncestors<EqualsValueClauseSyntax>().FirstOrDefault();
if (enclosingStatement == null && enclosingInitializer != null && enclosingInitializer.Parent is VariableDeclaratorSyntax)
{
return enclosingInitializer.Value;
}
var attributeSyntax = token.GetAncestor<AttributeSyntax>();
if (attributeSyntax != null)
{
return attributeSyntax;
}
// there seems to be no statement above this one. Let's see if we can at least get an SimpleNameSyntax
return enclosingStatement ?? enclosingNameMemberCrefOrnull ?? token.GetAncestors(n => n is SimpleNameSyntax).FirstOrDefault();
}
#region "Helper Methods"
public override bool IsIdentifierValid(string replacementText, ISyntaxFactsService syntaxFactsService)
{
// Identifiers we never consider valid to rename to.
switch (replacementText)
{
case "var":
case "dynamic":
case "unmanaged":
case "notnull":
return false;
}
var escapedIdentifier = replacementText.StartsWith("@", StringComparison.Ordinal)
? replacementText : "@" + replacementText;
// Make sure we got an identifier.
if (!syntaxFactsService.IsValidIdentifier(escapedIdentifier))
{
// We still don't have an identifier, so let's fail
return false;
}
return true;
}
/// <summary>
/// Gets the semantic model for the given node.
/// If the node belongs to the syntax tree of the original semantic model, then returns originalSemanticModel.
/// Otherwise, returns a speculative model.
/// The assumption for the later case is that span start position of the given node in it's syntax tree is same as
/// the span start of the original node in the original syntax tree.
/// </summary>
public static SemanticModel? GetSemanticModelForNode(SyntaxNode node, SemanticModel originalSemanticModel)
{
if (node.SyntaxTree == originalSemanticModel.SyntaxTree)
{
// This is possible if the previous rename phase didn't rewrite any nodes in this tree.
return originalSemanticModel;
}
var nodeToSpeculate = node.GetAncestorsOrThis(n => SpeculationAnalyzer.CanSpeculateOnNode(n)).LastOrDefault();
if (nodeToSpeculate == null)
{
if (node.IsKind(SyntaxKind.NameMemberCref, out NameMemberCrefSyntax? nameMember))
{
nodeToSpeculate = nameMember.Name;
}
else if (node.IsKind(SyntaxKind.QualifiedCref, out QualifiedCrefSyntax? qualifiedCref))
{
nodeToSpeculate = qualifiedCref.Container;
}
else if (node.IsKind(SyntaxKind.TypeConstraint, out TypeConstraintSyntax? typeConstraint))
{
nodeToSpeculate = typeConstraint.Type;
}
else if (node is BaseTypeSyntax baseType)
{
nodeToSpeculate = baseType.Type;
}
else
{
return null;
}
}
var isInNamespaceOrTypeContext = SyntaxFacts.IsInNamespaceOrTypeContext(node as ExpressionSyntax);
var position = nodeToSpeculate.SpanStart;
return SpeculationAnalyzer.CreateSpeculativeSemanticModelForNode(nodeToSpeculate, originalSemanticModel, position, isInNamespaceOrTypeContext);
}
#endregion
}
}
| 1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/CSharpTest/OrganizeImports/OrganizeUsingsTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.Workspaces.UnitTests.OrganizeImports
{
[UseExportProvider]
public class OrganizeUsingsTests
{
protected static async Task CheckAsync(
string initial, string final,
bool placeSystemNamespaceFirst = false,
bool separateImportGroups = false)
{
using var workspace = new AdhocWorkspace();
var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp);
var document = project.AddDocument("Document", initial.NormalizeLineEndings());
var newOptions = workspace.Options.WithChangedOption(new OptionKey(GenerationOptions.PlaceSystemNamespaceFirst, document.Project.Language), placeSystemNamespaceFirst);
newOptions = newOptions.WithChangedOption(new OptionKey(GenerationOptions.SeparateImportDirectiveGroups, document.Project.Language), separateImportGroups);
document = document.WithSolutionOptions(newOptions);
var newRoot = await (await Formatter.OrganizeImportsAsync(document, CancellationToken.None)).GetRequiredSyntaxRootAsync(default);
Assert.Equal(final.NormalizeLineEndings(), newRoot.ToFullString());
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task EmptyFile()
=> await CheckAsync(string.Empty, string.Empty);
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task SingleUsingStatement()
{
var initial = @"using A;";
var final = initial;
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task AliasesAtBottom()
{
var initial =
@"using A = B;
using C;
using D = E;
using F;";
var final =
@"using C;
using F;
using A = B;
using D = E;
";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task UsingStaticsBetweenUsingsAndAliases()
{
var initial =
@"using static System.Convert;
using A = B;
using C;
using Z;
using D = E;
using static System.Console;
using F;";
var final =
@"using C;
using F;
using Z;
using static System.Console;
using static System.Convert;
using A = B;
using D = E;
";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task NestedStatements()
{
var initial =
@"using B;
using A;
namespace N
{
using D;
using C;
namespace N1
{
using F;
using E;
}
namespace N2
{
using H;
using G;
}
}
namespace N3
{
using J;
using I;
namespace N4
{
using L;
using K;
}
namespace N5
{
using N;
using M;
}
}";
var final =
@"using A;
using B;
namespace N
{
using C;
using D;
namespace N1
{
using E;
using F;
}
namespace N2
{
using G;
using H;
}
}
namespace N3
{
using I;
using J;
namespace N4
{
using K;
using L;
}
namespace N5
{
using M;
using N;
}
}";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task FileScopedNamespace()
{
var initial =
@"using B;
using A;
namespace N;
using D;
using C;
";
var final =
@"using A;
using B;
namespace N;
using C;
using D;
";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task SpecialCaseSystem()
{
var initial =
@"using M2;
using M1;
using System.Linq;
using System;";
var final =
@"using System;
using System.Linq;
using M1;
using M2;
";
await CheckAsync(initial, final, placeSystemNamespaceFirst: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task SpecialCaseSystemWithUsingStatic()
{
var initial =
@"using M2;
using M1;
using System.Linq;
using System;
using static Microsoft.Win32.Registry;
using static System.BitConverter;";
var final =
@"using System;
using System.Linq;
using M1;
using M2;
using static System.BitConverter;
using static Microsoft.Win32.Registry;
";
await CheckAsync(initial, final, placeSystemNamespaceFirst: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoNotSpecialCaseSystem()
{
var initial =
@"using M2;
using M1;
using System.Linq;
using System;";
var final =
@"using M1;
using M2;
using System;
using System.Linq;
";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoNotSpecialCaseSystemWithUsingStatics()
{
var initial =
@"using M2;
using M1;
using System.Linq;
using System;
using static Microsoft.Win32.Registry;
using static System.BitConverter;";
var final =
@"using M1;
using M2;
using System;
using System.Linq;
using static Microsoft.Win32.Registry;
using static System.BitConverter;";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task IndentationAfterSorting()
{
var initial =
@"namespace A
{
using V.W;
using U;
using X.Y.Z;
class B { }
}
namespace U { }
namespace V.W { }
namespace X.Y.Z { }";
var final =
@"namespace A
{
using U;
using V.W;
using X.Y.Z;
class B { }
}
namespace U { }
namespace V.W { }
namespace X.Y.Z { }";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoNotTouchCommentsAtBeginningOfFile1()
{
var initial =
@"// Copyright (c) Microsoft Corporation. All rights reserved.
using B;
// I like namespace A
using A;
namespace A { }
namespace B { }";
var final =
@"// Copyright (c) Microsoft Corporation. All rights reserved.
// I like namespace A
using A;
using B;
namespace A { }
namespace B { }";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoNotTouchCommentsAtBeginningOfFile2()
{
var initial =
@"/* Copyright (c) Microsoft Corporation. All rights reserved. */
using B;
/* I like namespace A */
using A;
namespace A { }
namespace B { }";
var final =
@"/* Copyright (c) Microsoft Corporation. All rights reserved. */
/* I like namespace A */
using A;
using B;
namespace A { }
namespace B { }";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoNotTouchCommentsAtBeginningOfFile3()
{
var initial =
@"// Copyright (c) Microsoft Corporation. All rights reserved.
using B;
/// I like namespace A
using A;
namespace A { }
namespace B { }";
var final =
@"// Copyright (c) Microsoft Corporation. All rights reserved.
/// I like namespace A
using A;
using B;
namespace A { }
namespace B { }";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
[WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")]
public async Task DoNotTouchCommentsAtBeginningOfFile4()
{
var initial =
@"/// Copyright (c) Microsoft Corporation. All rights reserved.
using B;
/// I like namespace A
using A;
namespace A { }
namespace B { }";
var final =
@"/// Copyright (c) Microsoft Corporation. All rights reserved.
/// I like namespace A
using A;
using B;
namespace A { }
namespace B { }";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
[WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")]
public async Task DoNotTouchCommentsAtBeginningOfFile5()
{
var initial =
@"/** Copyright (c) Microsoft Corporation. All rights reserved.
*/
using B;
/// I like namespace A
using A;
namespace A { }
namespace B { }";
var final =
@"/** Copyright (c) Microsoft Corporation. All rights reserved.
*/
/// I like namespace A
using A;
using B;
namespace A { }
namespace B { }";
await CheckAsync(initial, final);
}
[WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")]
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoTouchCommentsAtBeginningOfFile1()
{
var initial =
@"// Copyright (c) Microsoft Corporation. All rights reserved.
using B;
// I like namespace A
using A;
namespace A { }
namespace B { }";
var final =
@"// Copyright (c) Microsoft Corporation. All rights reserved.
// I like namespace A
using A;
using B;
namespace A { }
namespace B { }";
await CheckAsync(initial, final);
}
[WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")]
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoTouchCommentsAtBeginningOfFile2()
{
var initial =
@"/* Copyright (c) Microsoft Corporation. All rights reserved. */
using B;
/* I like namespace A */
using A;
namespace A { }
namespace B { }";
var final =
@"/* Copyright (c) Microsoft Corporation. All rights reserved. */
/* I like namespace A */
using A;
using B;
namespace A { }
namespace B { }";
await CheckAsync(initial, final);
}
[WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")]
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoTouchCommentsAtBeginningOfFile3()
{
var initial =
@"/// Copyright (c) Microsoft Corporation. All rights reserved.
using B;
/// I like namespace A
using A;
namespace A { }
namespace B { }";
var final =
@"/// I like namespace A
using A;
/// Copyright (c) Microsoft Corporation. All rights reserved.
using B;
namespace A { }
namespace B { }";
await CheckAsync(initial, final);
}
[WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")]
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task CommentsNotAtTheStartOfTheFile1()
{
var initial =
@"namespace N
{
// attached to System.Text
using System.Text;
// attached to System
using System;
}";
var final =
@"namespace N
{
// attached to System
using System;
// attached to System.Text
using System.Text;
}";
await CheckAsync(initial, final);
}
[WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")]
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task CommentsNotAtTheStartOfTheFile2()
{
var initial =
@"namespace N
{
// not attached to System.Text
using System.Text;
// attached to System
using System;
}";
var final =
@"namespace N
{
// not attached to System.Text
// attached to System
using System;
using System.Text;
}";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoNotSortIfEndIfBlocks()
{
var initial =
@"using D;
#if MYCONFIG
using C;
#else
using B;
#endif
using A;
namespace A { }
namespace B { }
namespace C { }
namespace D { }";
var final = initial;
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task ExternAliases()
{
var initial =
@"extern alias Z;
extern alias Y;
extern alias X;
using C;
using U = C.L.T;
using O = A.J;
using A;
using W = A.J.R;
using N = B.K;
using V = B.K.S;
using M = C.L;
using B;
namespace A
{
namespace J
{
class R { }
}
}
namespace B
{
namespace K
{
struct S { }
}
}
namespace C
{
namespace L
{
struct T { }
}
}";
var final =
@"extern alias X;
extern alias Y;
extern alias Z;
using A;
using B;
using C;
using M = C.L;
using N = B.K;
using O = A.J;
using U = C.L.T;
using V = B.K.S;
using W = A.J.R;
namespace A
{
namespace J
{
class R { }
}
}
namespace B
{
namespace K
{
struct S { }
}
}
namespace C
{
namespace L
{
struct T { }
}
}";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DuplicateUsings()
{
var initial =
@"using A;
using A;";
var final = initial;
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task InlineComments()
{
var initial =
@"/*00*/using/*01*/D/*02*/;/*03*/
/*04*/using/*05*/C/*06*/;/*07*/
/*08*/using/*09*/A/*10*/;/*11*/
/*12*/using/*13*/B/*14*/;/*15*/
/*16*/";
var final =
@"/*08*/using/*09*/A/*10*/;/*11*/
/*12*/using/*13*/B/*14*/;/*15*/
/*04*/using/*05*/C/*06*/;/*07*/
/*00*/using/*01*/D/*02*/;/*03*/
/*16*/";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task AllOnOneLine()
{
var initial =
@"using C; using B; using A;";
var final =
@"using A;
using B;
using C; ";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task InsideRegionBlock()
{
var initial =
@"#region Using directives
using C;
using A;
using B;
#endregion
class Class1
{
}";
var final =
@"#region Using directives
using A;
using B;
using C;
#endregion
class Class1
{
}";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task NestedRegionBlock()
{
var initial =
@"using C;
#region Z
using A;
#endregion
using B;";
var final = initial;
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task MultipleRegionBlocks()
{
var initial =
@"#region Using directives
using C;
#region Z
using A;
#endregion
using B;
#endregion";
var final = initial;
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task InterleavedNewlines()
{
var initial =
@"using B;
using A;
using C;
class D { }";
var final =
@"using A;
using B;
using C;
class D { }";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task InsideIfEndIfBlock()
{
var initial =
@"#if !X
using B;
using A;
using C;
#endif";
var final =
@"#if !X
using A;
using B;
using C;
#endif";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task IfEndIfBlockAbove()
{
var initial =
@"#if !X
using C;
using B;
using F;
#endif
using D;
using A;
using E;";
var final = initial;
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task IfEndIfBlockMiddle()
{
var initial =
@"using D;
using A;
using H;
#if !X
using C;
using B;
using I;
#endif
using F;
using E;
using G;";
var final = initial;
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task IfEndIfBlockBelow()
{
var initial =
@"using D;
using A;
using E;
#if !X
using C;
using B;
using F;
#endif";
var final = initial;
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task Korean()
{
var initial =
@"using 하;
using 파;
using 타;
using 카;
using 차;
using 자;
using 아;
using 사;
using 바;
using 마;
using 라;
using 다;
using 나;
using 가;";
var final =
@"using 가;
using 나;
using 다;
using 라;
using 마;
using 바;
using 사;
using 아;
using 자;
using 차;
using 카;
using 타;
using 파;
using 하;
";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoNotSpecialCaseSystem1()
{
var initial =
@"using B;
using System.Collections.Generic;
using C;
using _System;
using SystemZ;
using D.System;
using System;
using System.Collections;
using A;";
var final =
@"using _System;
using A;
using B;
using C;
using D.System;
using System;
using System.Collections;
using System.Collections.Generic;
using SystemZ;
";
await CheckAsync(initial, final, placeSystemNamespaceFirst: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoNotSpecialCaseSystem2()
{
var initial =
@"extern alias S;
extern alias R;
extern alias T;
using B;
using System.Collections.Generic;
using C;
using _System;
using SystemZ;
using Y = System.UInt32;
using Z = System.Int32;
using D.System;
using System;
using N = System;
using M = System.Collections;
using System.Collections;
using A;";
var final =
@"extern alias R;
extern alias S;
extern alias T;
using _System;
using A;
using B;
using C;
using D.System;
using System;
using System.Collections;
using System.Collections.Generic;
using SystemZ;
using M = System.Collections;
using N = System;
using Y = System.UInt32;
using Z = System.Int32;
";
await CheckAsync(initial, final, placeSystemNamespaceFirst: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task CaseSensitivity1()
{
var initial =
@"using Bb;
using B;
using bB;
using b;
using Aa;
using a;
using A;
using aa;
using aA;
using AA;
using bb;
using BB;
using bBb;
using bbB;
using あ;
using ア;
using ア;
using ああ;
using あア;
using あア;
using アあ;
using cC;
using Cc;
using アア;
using アア;
using アあ;
using アア;
using アア;
using BBb;
using BbB;
using bBB;
using BBB;
using c;
using C;
using bbb;
using Bbb;
using cc;
using cC;
using CC;
// If Kana is sensitive あ != ア, if Kana is insensitive あ == ア.
// If Width is sensitiveア != ア, if Width is insensitive ア == ア.";
var final =
@"using a;
using A;
using aa;
using aA;
using Aa;
using AA;
using b;
using B;
using bb;
using bB;
using Bb;
using BB;
using bbb;
using bbB;
using bBb;
using bBB;
using Bbb;
using BbB;
using BBb;
using BBB;
using c;
using C;
using cc;
using cC;
using cC;
using Cc;
using CC;
using ア;
using ア;
using あ;
using アア;
using アア;
using アア;
using アア;
using アあ;
using アあ;
using あア;
using あア;
using ああ;
// If Kana is sensitive あ != ア, if Kana is insensitive あ == ア.
// If Width is sensitiveア != ア, if Width is insensitive ア == ア.";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task CaseSensitivity2()
{
var initial =
@"using あ;
using ア;
using ア;
using ああ;
using あア;
using あア;
using アあ;
using アア;
using アア;
using アあ;
using アア;
using アア;";
var final =
@"using ア;
using ア;
using あ;
using アア;
using アア;
using アア;
using アア;
using アあ;
using アあ;
using あア;
using あア;
using ああ;
";
await CheckAsync(initial, final);
}
[WorkItem(20988, "https://github.com/dotnet/roslyn/issues/20988")]
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task TestGrouping()
{
var initial =
@"// Banner
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
using IntList = System.Collections.Generic.List<int>;
using static System.Console;";
var final =
@"// Banner
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
using static System.Console;
using IntList = System.Collections.Generic.List<int>;
";
await CheckAsync(initial, final, placeSystemNamespaceFirst: true, separateImportGroups: true);
}
[WorkItem(20988, "https://github.com/dotnet/roslyn/issues/20988")]
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task TestGrouping2()
{
// Make sure we don't insert extra newlines if they're already there.
var initial =
@"// Banner
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
using static System.Console;
using IntList = System.Collections.Generic.List<int>;
";
var final =
@"// Banner
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
using static System.Console;
using IntList = System.Collections.Generic.List<int>;
";
await CheckAsync(initial, final, placeSystemNamespaceFirst: true, separateImportGroups: 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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.Workspaces.UnitTests.OrganizeImports
{
[UseExportProvider]
public class OrganizeUsingsTests
{
protected static async Task CheckAsync(
string initial, string final,
bool placeSystemNamespaceFirst = false,
bool separateImportGroups = false)
{
using var workspace = new AdhocWorkspace();
var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp);
var document = project.AddDocument("Document", initial.NormalizeLineEndings());
var newOptions = workspace.Options.WithChangedOption(new OptionKey(GenerationOptions.PlaceSystemNamespaceFirst, document.Project.Language), placeSystemNamespaceFirst);
newOptions = newOptions.WithChangedOption(new OptionKey(GenerationOptions.SeparateImportDirectiveGroups, document.Project.Language), separateImportGroups);
document = document.WithSolutionOptions(newOptions);
var newRoot = await (await Formatter.OrganizeImportsAsync(document, CancellationToken.None)).GetRequiredSyntaxRootAsync(default);
Assert.Equal(final.NormalizeLineEndings(), newRoot.ToFullString());
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task EmptyFile()
=> await CheckAsync(string.Empty, string.Empty);
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task SingleUsingStatement()
{
var initial = @"using A;";
var final = initial;
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task AliasesAtBottom()
{
var initial =
@"using A = B;
using C;
using D = E;
using F;";
var final =
@"using C;
using F;
using A = B;
using D = E;
";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task UsingStaticsBetweenUsingsAndAliases()
{
var initial =
@"using static System.Convert;
using A = B;
using C;
using Z;
using D = E;
using static System.Console;
using F;";
var final =
@"using C;
using F;
using Z;
using static System.Console;
using static System.Convert;
using A = B;
using D = E;
";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task NestedStatements()
{
var initial =
@"using B;
using A;
namespace N
{
using D;
using C;
namespace N1
{
using F;
using E;
}
namespace N2
{
using H;
using G;
}
}
namespace N3
{
using J;
using I;
namespace N4
{
using L;
using K;
}
namespace N5
{
using N;
using M;
}
}";
var final =
@"using A;
using B;
namespace N
{
using C;
using D;
namespace N1
{
using E;
using F;
}
namespace N2
{
using G;
using H;
}
}
namespace N3
{
using I;
using J;
namespace N4
{
using K;
using L;
}
namespace N5
{
using M;
using N;
}
}";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task FileScopedNamespace()
{
var initial =
@"using B;
using A;
namespace N;
using D;
using C;
";
var final =
@"using A;
using B;
namespace N;
using C;
using D;
";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task SpecialCaseSystem()
{
var initial =
@"using M2;
using M1;
using System.Linq;
using System;";
var final =
@"using System;
using System.Linq;
using M1;
using M2;
";
await CheckAsync(initial, final, placeSystemNamespaceFirst: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task SpecialCaseSystemWithUsingStatic()
{
var initial =
@"using M2;
using M1;
using System.Linq;
using System;
using static Microsoft.Win32.Registry;
using static System.BitConverter;";
var final =
@"using System;
using System.Linq;
using M1;
using M2;
using static System.BitConverter;
using static Microsoft.Win32.Registry;
";
await CheckAsync(initial, final, placeSystemNamespaceFirst: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoNotSpecialCaseSystem()
{
var initial =
@"using M2;
using M1;
using System.Linq;
using System;";
var final =
@"using M1;
using M2;
using System;
using System.Linq;
";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoNotSpecialCaseSystemWithUsingStatics()
{
var initial =
@"using M2;
using M1;
using System.Linq;
using System;
using static Microsoft.Win32.Registry;
using static System.BitConverter;";
var final =
@"using M1;
using M2;
using System;
using System.Linq;
using static Microsoft.Win32.Registry;
using static System.BitConverter;";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task IndentationAfterSorting()
{
var initial =
@"namespace A
{
using V.W;
using U;
using X.Y.Z;
class B { }
}
namespace U { }
namespace V.W { }
namespace X.Y.Z { }";
var final =
@"namespace A
{
using U;
using V.W;
using X.Y.Z;
class B { }
}
namespace U { }
namespace V.W { }
namespace X.Y.Z { }";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoNotTouchCommentsAtBeginningOfFile1()
{
var initial =
@"// Copyright (c) Microsoft Corporation. All rights reserved.
using B;
// I like namespace A
using A;
namespace A { }
namespace B { }";
var final =
@"// Copyright (c) Microsoft Corporation. All rights reserved.
// I like namespace A
using A;
using B;
namespace A { }
namespace B { }";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoNotTouchCommentsAtBeginningOfFile2()
{
var initial =
@"/* Copyright (c) Microsoft Corporation. All rights reserved. */
using B;
/* I like namespace A */
using A;
namespace A { }
namespace B { }";
var final =
@"/* Copyright (c) Microsoft Corporation. All rights reserved. */
/* I like namespace A */
using A;
using B;
namespace A { }
namespace B { }";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoNotTouchCommentsAtBeginningOfFile3()
{
var initial =
@"// Copyright (c) Microsoft Corporation. All rights reserved.
using B;
/// I like namespace A
using A;
namespace A { }
namespace B { }";
var final =
@"// Copyright (c) Microsoft Corporation. All rights reserved.
/// I like namespace A
using A;
using B;
namespace A { }
namespace B { }";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
[WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")]
public async Task DoNotTouchCommentsAtBeginningOfFile4()
{
var initial =
@"/// Copyright (c) Microsoft Corporation. All rights reserved.
using B;
/// I like namespace A
using A;
namespace A { }
namespace B { }";
var final =
@"/// Copyright (c) Microsoft Corporation. All rights reserved.
/// I like namespace A
using A;
using B;
namespace A { }
namespace B { }";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
[WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")]
public async Task DoNotTouchCommentsAtBeginningOfFile5()
{
var initial =
@"/** Copyright (c) Microsoft Corporation. All rights reserved.
*/
using B;
/// I like namespace A
using A;
namespace A { }
namespace B { }";
var final =
@"/** Copyright (c) Microsoft Corporation. All rights reserved.
*/
/// I like namespace A
using A;
using B;
namespace A { }
namespace B { }";
await CheckAsync(initial, final);
}
[WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")]
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoTouchCommentsAtBeginningOfFile1()
{
var initial =
@"// Copyright (c) Microsoft Corporation. All rights reserved.
using B;
// I like namespace A
using A;
namespace A { }
namespace B { }";
var final =
@"// Copyright (c) Microsoft Corporation. All rights reserved.
// I like namespace A
using A;
using B;
namespace A { }
namespace B { }";
await CheckAsync(initial, final);
}
[WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")]
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoTouchCommentsAtBeginningOfFile2()
{
var initial =
@"/* Copyright (c) Microsoft Corporation. All rights reserved. */
using B;
/* I like namespace A */
using A;
namespace A { }
namespace B { }";
var final =
@"/* Copyright (c) Microsoft Corporation. All rights reserved. */
/* I like namespace A */
using A;
using B;
namespace A { }
namespace B { }";
await CheckAsync(initial, final);
}
[WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")]
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoTouchCommentsAtBeginningOfFile3()
{
var initial =
@"/// Copyright (c) Microsoft Corporation. All rights reserved.
using B;
/// I like namespace A
using A;
namespace A { }
namespace B { }";
var final =
@"/// I like namespace A
using A;
/// Copyright (c) Microsoft Corporation. All rights reserved.
using B;
namespace A { }
namespace B { }";
await CheckAsync(initial, final);
}
[WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")]
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task CommentsNotAtTheStartOfTheFile1()
{
var initial =
@"namespace N
{
// attached to System.Text
using System.Text;
// attached to System
using System;
}";
var final =
@"namespace N
{
// attached to System
using System;
// attached to System.Text
using System.Text;
}";
await CheckAsync(initial, final);
}
[WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")]
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task CommentsNotAtTheStartOfTheFile2()
{
var initial =
@"namespace N
{
// not attached to System.Text
using System.Text;
// attached to System
using System;
}";
var final =
@"namespace N
{
// not attached to System.Text
// attached to System
using System;
using System.Text;
}";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoNotSortIfEndIfBlocks()
{
var initial =
@"using D;
#if MYCONFIG
using C;
#else
using B;
#endif
using A;
namespace A { }
namespace B { }
namespace C { }
namespace D { }";
var final = initial;
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task ExternAliases()
{
var initial =
@"extern alias Z;
extern alias Y;
extern alias X;
using C;
using U = C.L.T;
using O = A.J;
using A;
using W = A.J.R;
using N = B.K;
using V = B.K.S;
using M = C.L;
using B;
namespace A
{
namespace J
{
class R { }
}
}
namespace B
{
namespace K
{
struct S { }
}
}
namespace C
{
namespace L
{
struct T { }
}
}";
var final =
@"extern alias X;
extern alias Y;
extern alias Z;
using A;
using B;
using C;
using M = C.L;
using N = B.K;
using O = A.J;
using U = C.L.T;
using V = B.K.S;
using W = A.J.R;
namespace A
{
namespace J
{
class R { }
}
}
namespace B
{
namespace K
{
struct S { }
}
}
namespace C
{
namespace L
{
struct T { }
}
}";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DuplicateUsings()
{
var initial =
@"using A;
using A;";
var final = initial;
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task InlineComments()
{
var initial =
@"/*00*/using/*01*/D/*02*/;/*03*/
/*04*/using/*05*/C/*06*/;/*07*/
/*08*/using/*09*/A/*10*/;/*11*/
/*12*/using/*13*/B/*14*/;/*15*/
/*16*/";
var final =
@"/*08*/using/*09*/A/*10*/;/*11*/
/*12*/using/*13*/B/*14*/;/*15*/
/*04*/using/*05*/C/*06*/;/*07*/
/*00*/using/*01*/D/*02*/;/*03*/
/*16*/";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task AllOnOneLine()
{
var initial =
@"using C; using B; using A;";
var final =
@"using A;
using B;
using C; ";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task InsideRegionBlock()
{
var initial =
@"#region Using directives
using C;
using A;
using B;
#endregion
class Class1
{
}";
var final =
@"#region Using directives
using A;
using B;
using C;
#endregion
class Class1
{
}";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task NestedRegionBlock()
{
var initial =
@"using C;
#region Z
using A;
#endregion
using B;";
var final = initial;
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task MultipleRegionBlocks()
{
var initial =
@"#region Using directives
using C;
#region Z
using A;
#endregion
using B;
#endregion";
var final = initial;
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task InterleavedNewlines()
{
var initial =
@"using B;
using A;
using C;
class D { }";
var final =
@"using A;
using B;
using C;
class D { }";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task InsideIfEndIfBlock()
{
var initial =
@"#if !X
using B;
using A;
using C;
#endif";
var final =
@"#if !X
using A;
using B;
using C;
#endif";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task IfEndIfBlockAbove()
{
var initial =
@"#if !X
using C;
using B;
using F;
#endif
using D;
using A;
using E;";
var final = initial;
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task IfEndIfBlockMiddle()
{
var initial =
@"using D;
using A;
using H;
#if !X
using C;
using B;
using I;
#endif
using F;
using E;
using G;";
var final = initial;
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task IfEndIfBlockBelow()
{
var initial =
@"using D;
using A;
using E;
#if !X
using C;
using B;
using F;
#endif";
var final = initial;
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task Korean()
{
var initial =
@"using 하;
using 파;
using 타;
using 카;
using 차;
using 자;
using 아;
using 사;
using 바;
using 마;
using 라;
using 다;
using 나;
using 가;";
var final =
@"using 가;
using 나;
using 다;
using 라;
using 마;
using 바;
using 사;
using 아;
using 자;
using 차;
using 카;
using 타;
using 파;
using 하;
";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoNotSpecialCaseSystem1()
{
var initial =
@"using B;
using System.Collections.Generic;
using C;
using _System;
using SystemZ;
using D.System;
using System;
using System.Collections;
using A;";
var final =
@"using _System;
using A;
using B;
using C;
using D.System;
using System;
using System.Collections;
using System.Collections.Generic;
using SystemZ;
";
await CheckAsync(initial, final, placeSystemNamespaceFirst: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoNotSpecialCaseSystem2()
{
var initial =
@"extern alias S;
extern alias R;
extern alias T;
using B;
using System.Collections.Generic;
using C;
using _System;
using SystemZ;
using Y = System.UInt32;
using Z = System.Int32;
using D.System;
using System;
using N = System;
using M = System.Collections;
using System.Collections;
using A;";
var final =
@"extern alias R;
extern alias S;
extern alias T;
using _System;
using A;
using B;
using C;
using D.System;
using System;
using System.Collections;
using System.Collections.Generic;
using SystemZ;
using M = System.Collections;
using N = System;
using Y = System.UInt32;
using Z = System.Int32;
";
await CheckAsync(initial, final, placeSystemNamespaceFirst: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task CaseSensitivity1()
{
var initial =
@"using Bb;
using B;
using bB;
using b;
using Aa;
using a;
using A;
using aa;
using aA;
using AA;
using bb;
using BB;
using bBb;
using bbB;
using あ;
using ア;
using ア;
using ああ;
using あア;
using あア;
using アあ;
using cC;
using Cc;
using アア;
using アア;
using アあ;
using アア;
using アア;
using BBb;
using BbB;
using bBB;
using BBB;
using c;
using C;
using bbb;
using Bbb;
using cc;
using cC;
using CC;
// If Kana is sensitive あ != ア, if Kana is insensitive あ == ア.
// If Width is sensitiveア != ア, if Width is insensitive ア == ア.";
var final =
@"using a;
using A;
using aa;
using aA;
using Aa;
using AA;
using b;
using B;
using bb;
using bB;
using Bb;
using BB;
using bbb;
using bbB;
using bBb;
using bBB;
using Bbb;
using BbB;
using BBb;
using BBB;
using c;
using C;
using cc;
using cC;
using cC;
using Cc;
using CC;
using ア;
using ア;
using あ;
using アア;
using アア;
using アア;
using アア;
using アあ;
using アあ;
using あア;
using あア;
using ああ;
// If Kana is sensitive あ != ア, if Kana is insensitive あ == ア.
// If Width is sensitiveア != ア, if Width is insensitive ア == ア.";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task CaseSensitivity2()
{
var initial =
@"using あ;
using ア;
using ア;
using ああ;
using あア;
using あア;
using アあ;
using アア;
using アア;
using アあ;
using アア;
using アア;";
var final =
@"using ア;
using ア;
using あ;
using アア;
using アア;
using アア;
using アア;
using アあ;
using アあ;
using あア;
using あア;
using ああ;
";
await CheckAsync(initial, final);
}
[WorkItem(20988, "https://github.com/dotnet/roslyn/issues/20988")]
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task TestGrouping()
{
var initial =
@"// Banner
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
using IntList = System.Collections.Generic.List<int>;
using static System.Console;";
var final =
@"// Banner
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
using static System.Console;
using IntList = System.Collections.Generic.List<int>;
";
await CheckAsync(initial, final, placeSystemNamespaceFirst: true, separateImportGroups: true);
}
[WorkItem(20988, "https://github.com/dotnet/roslyn/issues/20988")]
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task TestGrouping2()
{
// Make sure we don't insert extra newlines if they're already there.
var initial =
@"// Banner
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
using static System.Console;
using IntList = System.Collections.Generic.List<int>;
";
var final =
@"// Banner
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
using static System.Console;
using IntList = System.Collections.Generic.List<int>;
";
await CheckAsync(initial, final, placeSystemNamespaceFirst: true, separateImportGroups: true);
}
}
}
| 1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/Core/Portable/Recommendations/AbstractRecommendationServiceRunner.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery;
namespace Microsoft.CodeAnalysis.Recommendations
{
internal abstract class AbstractRecommendationServiceRunner<TSyntaxContext>
where TSyntaxContext : SyntaxContext
{
protected readonly TSyntaxContext _context;
protected readonly bool _filterOutOfScopeLocals;
protected readonly CancellationToken _cancellationToken;
private readonly StringComparer _stringComparerForLanguage;
public AbstractRecommendationServiceRunner(
TSyntaxContext context,
bool filterOutOfScopeLocals,
CancellationToken cancellationToken)
{
_context = context;
_stringComparerForLanguage = _context.GetLanguageService<ISyntaxFactsService>().StringComparer;
_filterOutOfScopeLocals = filterOutOfScopeLocals;
_cancellationToken = cancellationToken;
}
public abstract RecommendedSymbols GetRecommendedSymbols();
public abstract bool TryGetExplicitTypeOfLambdaParameter(SyntaxNode lambdaSyntax, int ordinalInLambda, [NotNullWhen(returnValue: true)] out ITypeSymbol explicitLambdaParameterType);
// This code is to help give intellisense in the following case:
// query.Include(a => a.SomeProperty).ThenInclude(a => a.
// where there are more than one overloads of ThenInclude accepting different types of parameters.
private ImmutableArray<ISymbol> GetMemberSymbolsForParameter(IParameterSymbol parameter, int position, bool useBaseReferenceAccessibility, bool unwrapNullable)
{
var symbols = TryGetMemberSymbolsForLambdaParameter(parameter, position);
return symbols.IsDefault
? GetMemberSymbols(parameter.Type, position, excludeInstance: false, useBaseReferenceAccessibility, unwrapNullable)
: symbols;
}
private ImmutableArray<ISymbol> TryGetMemberSymbolsForLambdaParameter(IParameterSymbol parameter, int position)
{
// Use normal lookup path for this/base parameters.
if (parameter.IsThis)
return default;
// Starting from a. in the example, looking for a => a.
if (parameter.ContainingSymbol is not IMethodSymbol { MethodKind: MethodKind.AnonymousFunction } owningMethod)
return default;
// Cannot proceed without DeclaringSyntaxReferences.
// We expect that there is a single DeclaringSyntaxReferences in the scenario.
// If anything changes on the compiler side, the approach should be revised.
if (owningMethod.DeclaringSyntaxReferences.Length != 1)
return default;
var syntaxFactsService = _context.GetLanguageService<ISyntaxFactsService>();
// Check that a => a. belongs to an invocation.
// Find its' ordinal in the invocation, e.g. ThenInclude(a => a.Something, a=> a.
var lambdaSyntax = owningMethod.DeclaringSyntaxReferences.Single().GetSyntax(_cancellationToken);
if (!(syntaxFactsService.IsAnonymousFunction(lambdaSyntax) &&
syntaxFactsService.IsArgument(lambdaSyntax.Parent) &&
syntaxFactsService.IsInvocationExpression(lambdaSyntax.Parent.Parent.Parent)))
{
return default;
}
var invocationExpression = lambdaSyntax.Parent.Parent.Parent;
var arguments = syntaxFactsService.GetArgumentsOfInvocationExpression(invocationExpression);
var argumentName = syntaxFactsService.GetNameForArgument(lambdaSyntax.Parent);
var ordinalInInvocation = arguments.IndexOf(lambdaSyntax.Parent);
var expressionOfInvocationExpression = syntaxFactsService.GetExpressionOfInvocationExpression(invocationExpression);
var parameterTypeSymbols = ImmutableArray<ITypeSymbol>.Empty;
if (TryGetExplicitTypeOfLambdaParameter(lambdaSyntax, parameter.Ordinal, out var explicitLambdaParameterType))
{
parameterTypeSymbols = ImmutableArray.Create(explicitLambdaParameterType);
}
else
{
// Get all members potentially matching the invocation expression.
// We filter them out based on ordinality later.
var candidateSymbols = _context.SemanticModel.GetMemberGroup(expressionOfInvocationExpression, _cancellationToken);
// parameter.Ordinal is the ordinal within (a,b,c) => b.
// For candidate symbols of (a,b,c) => b., get types of all possible b.
parameterTypeSymbols = GetTypeSymbols(candidateSymbols, argumentName, ordinalInInvocation, ordinalInLambda: parameter.Ordinal);
// The parameterTypeSymbols may include type parameters, and we want their substituted types if available.
parameterTypeSymbols = SubstituteTypeParameters(parameterTypeSymbols, invocationExpression);
}
// For each type of b., return all suitable members. Also, ensure we consider the actual type of the
// parameter the compiler inferred as it may have made a completely suitable inference for it.
return parameterTypeSymbols
.Concat(parameter.Type)
.SelectMany(parameterTypeSymbol => GetMemberSymbols(parameterTypeSymbol, position, excludeInstance: false, useBaseReferenceAccessibility: false, unwrapNullable: false))
.ToImmutableArray();
}
private ImmutableArray<ITypeSymbol> SubstituteTypeParameters(ImmutableArray<ITypeSymbol> parameterTypeSymbols, SyntaxNode invocationExpression)
{
if (!parameterTypeSymbols.Any(t => t.IsKind(SymbolKind.TypeParameter)))
{
return parameterTypeSymbols;
}
var invocationSymbols = _context.SemanticModel.GetSymbolInfo(invocationExpression).GetAllSymbols();
if (invocationSymbols.Length == 0)
{
return parameterTypeSymbols;
}
using var _ = ArrayBuilder<ITypeSymbol>.GetInstance(out var concreteTypes);
foreach (var invocationSymbol in invocationSymbols)
{
var typeParameters = invocationSymbol.GetTypeParameters();
var typeArguments = invocationSymbol.GetTypeArguments();
foreach (var parameterTypeSymbol in parameterTypeSymbols)
{
if (parameterTypeSymbol.IsKind<ITypeParameterSymbol>(SymbolKind.TypeParameter, out var typeParameter))
{
// The typeParameter could be from the containing type, so it may not be
// present in this method's list of typeParameters.
var index = typeParameters.IndexOf(typeParameter);
var concreteType = typeArguments.ElementAtOrDefault(index);
// If we couldn't find the concrete type, still consider the typeParameter
// as is to provide members of any types it is constrained to (including object)
concreteTypes.Add(concreteType ?? typeParameter);
}
else
{
concreteTypes.Add(parameterTypeSymbol);
}
}
}
return concreteTypes.ToImmutable();
}
/// <summary>
/// Tries to get a type of its' <paramref name="ordinalInLambda"/> lambda parameter of <paramref name="ordinalInInvocation"/> argument for each candidate symbol.
/// </summary>
/// <param name="candidateSymbols">symbols corresponding to <see cref="Expression{Func}"/> or <see cref="Func{some_args, TResult}"/>
/// Here, some_args can be multi-variables lambdas as well, e.g. f((a,b) => a+b, (a,b,c)=>a*b*c.Length)
/// </param>
/// <param name="ordinalInInvocation">ordinal of the arguments of function: (a,b) or (a,b,c) in the example above</param>
/// <param name="ordinalInLambda">ordinal of the lambda parameters, e.g. a, b or c.</param>
/// <returns></returns>
private ImmutableArray<ITypeSymbol> GetTypeSymbols(ImmutableArray<ISymbol> candidateSymbols, string argumentName, int ordinalInInvocation, int ordinalInLambda)
{
var expressionSymbol = _context.SemanticModel.Compilation.GetTypeByMetadataName(typeof(Expression<>).FullName);
var builder = ArrayBuilder<ITypeSymbol>.GetInstance();
foreach (var candidateSymbol in candidateSymbols)
{
if (candidateSymbol is IMethodSymbol method)
{
if (!TryGetMatchingParameterTypeForArgument(method, argumentName, ordinalInInvocation, out var type))
{
continue;
}
// If type is <see cref="Expression{TDelegate}"/>, ignore <see cref="Expression"/> and use TDelegate.
// Ignore this check if expressionSymbol is null, e.g. semantic model is broken or incomplete or if the framework does not contain <see cref="Expression"/>.
if (expressionSymbol != null &&
type is INamedTypeSymbol expressionSymbolNamedTypeCandidate &&
expressionSymbolNamedTypeCandidate.OriginalDefinition.Equals(expressionSymbol))
{
var allTypeArguments = type.GetAllTypeArguments();
if (allTypeArguments.Length != 1)
{
continue;
}
type = allTypeArguments[0];
}
if (type.IsDelegateType())
{
var methods = type.GetMembers(WellKnownMemberNames.DelegateInvokeName);
if (methods.Length != 1)
{
continue;
}
var parameters = methods[0].GetParameters();
if (parameters.Length <= ordinalInLambda)
{
continue;
}
builder.Add(parameters[ordinalInLambda].Type);
}
}
}
return builder.ToImmutableAndFree().Distinct();
}
private bool TryGetMatchingParameterTypeForArgument(IMethodSymbol method, string argumentName, int ordinalInInvocation, out ITypeSymbol parameterType)
{
if (!string.IsNullOrEmpty(argumentName))
{
parameterType = method.Parameters.FirstOrDefault(p => _stringComparerForLanguage.Equals(p.Name, argumentName))?.Type;
return parameterType != null;
}
// We don't know the argument name, so have to find the parameter based on position
if (method.IsParams() && (ordinalInInvocation >= method.Parameters.Length - 1))
{
if (method.Parameters.LastOrDefault()?.Type is IArrayTypeSymbol arrayType)
{
parameterType = arrayType.ElementType;
return true;
}
else
{
parameterType = null;
return false;
}
}
if (ordinalInInvocation < method.Parameters.Length)
{
parameterType = method.Parameters[ordinalInInvocation].Type;
return true;
}
parameterType = null;
return false;
}
protected ImmutableArray<ISymbol> GetSymbolsForNamespaceDeclarationNameContext<TNamespaceDeclarationSyntax>()
where TNamespaceDeclarationSyntax : SyntaxNode
{
var declarationSyntax = _context.TargetToken.GetAncestor<TNamespaceDeclarationSyntax>();
if (declarationSyntax == null)
return ImmutableArray<ISymbol>.Empty;
var semanticModel = _context.SemanticModel;
var containingNamespaceSymbol = semanticModel.Compilation.GetCompilationNamespace(
semanticModel.GetEnclosingNamespace(declarationSyntax.SpanStart, _cancellationToken));
var symbols = semanticModel.LookupNamespacesAndTypes(declarationSyntax.SpanStart, containingNamespaceSymbol)
.WhereAsArray(recommendationSymbol => IsNonIntersectingNamespace(recommendationSymbol, declarationSyntax));
return symbols;
}
protected static bool IsNonIntersectingNamespace(ISymbol recommendationSymbol, SyntaxNode declarationSyntax)
{
//
// Apart from filtering out non-namespace symbols, this also filters out the symbol
// currently being declared. For example...
//
// namespace X$$
//
// ...X won't show in the completion list (unless it is also declared elsewhere).
//
// In addition, in VB, it will filter out Bar from the sample below...
//
// Namespace Goo.$$
// Namespace Bar
// End Namespace
// End Namespace
//
// ...unless, again, it's also declared elsewhere.
//
return recommendationSymbol.IsNamespace() &&
recommendationSymbol.Locations.Any(
candidateLocation => !(declarationSyntax.SyntaxTree == candidateLocation.SourceTree &&
declarationSyntax.Span.IntersectsWith(candidateLocation.SourceSpan)));
}
protected ImmutableArray<ISymbol> GetMemberSymbols(
ISymbol container,
int position,
bool excludeInstance,
bool useBaseReferenceAccessibility,
bool unwrapNullable)
{
// For a normal parameter, we have a specialized codepath we use to ensure we properly get lambda parameter
// information that the compiler may fail to give.
if (container is IParameterSymbol parameter)
return GetMemberSymbolsForParameter(parameter, position, useBaseReferenceAccessibility, unwrapNullable);
if (container is not INamespaceOrTypeSymbol namespaceOrType)
return ImmutableArray<ISymbol>.Empty;
if (unwrapNullable && namespaceOrType is ITypeSymbol typeSymbol)
{
namespaceOrType = typeSymbol.RemoveNullableIfPresent();
}
return useBaseReferenceAccessibility
? _context.SemanticModel.LookupBaseMembers(position)
: LookupSymbolsInContainer(namespaceOrType, position, excludeInstance);
}
protected ImmutableArray<ISymbol> LookupSymbolsInContainer(
INamespaceOrTypeSymbol container, int position, bool excludeInstance)
{
return excludeInstance
? _context.SemanticModel.LookupStaticMembers(position, container)
: SuppressDefaultTupleElements(
container,
_context.SemanticModel.LookupSymbols(position, container, includeReducedExtensionMethods: true));
}
/// <summary>
/// If container is a tuple type, any of its tuple element which has a friendly name will cause
/// the suppression of the corresponding default name (ItemN).
/// In that case, Rest is also removed.
/// </summary>
protected static ImmutableArray<ISymbol> SuppressDefaultTupleElements(
INamespaceOrTypeSymbol container, ImmutableArray<ISymbol> symbols)
{
var namedType = container as INamedTypeSymbol;
if (namedType?.IsTupleType != true)
{
// container is not a tuple
return symbols;
}
//return tuple elements followed by other members that are not fields
return ImmutableArray<ISymbol>.CastUp(namedType.TupleElements).
Concat(symbols.WhereAsArray(s => s.Kind != SymbolKind.Field));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery;
namespace Microsoft.CodeAnalysis.Recommendations
{
internal abstract class AbstractRecommendationServiceRunner<TSyntaxContext>
where TSyntaxContext : SyntaxContext
{
protected readonly TSyntaxContext _context;
protected readonly bool _filterOutOfScopeLocals;
protected readonly CancellationToken _cancellationToken;
private readonly StringComparer _stringComparerForLanguage;
public AbstractRecommendationServiceRunner(
TSyntaxContext context,
bool filterOutOfScopeLocals,
CancellationToken cancellationToken)
{
_context = context;
_stringComparerForLanguage = _context.GetLanguageService<ISyntaxFactsService>().StringComparer;
_filterOutOfScopeLocals = filterOutOfScopeLocals;
_cancellationToken = cancellationToken;
}
public abstract RecommendedSymbols GetRecommendedSymbols();
public abstract bool TryGetExplicitTypeOfLambdaParameter(SyntaxNode lambdaSyntax, int ordinalInLambda, [NotNullWhen(returnValue: true)] out ITypeSymbol explicitLambdaParameterType);
// This code is to help give intellisense in the following case:
// query.Include(a => a.SomeProperty).ThenInclude(a => a.
// where there are more than one overloads of ThenInclude accepting different types of parameters.
private ImmutableArray<ISymbol> GetMemberSymbolsForParameter(IParameterSymbol parameter, int position, bool useBaseReferenceAccessibility, bool unwrapNullable)
{
var symbols = TryGetMemberSymbolsForLambdaParameter(parameter, position);
return symbols.IsDefault
? GetMemberSymbols(parameter.Type, position, excludeInstance: false, useBaseReferenceAccessibility, unwrapNullable)
: symbols;
}
private ImmutableArray<ISymbol> TryGetMemberSymbolsForLambdaParameter(IParameterSymbol parameter, int position)
{
// Use normal lookup path for this/base parameters.
if (parameter.IsThis)
return default;
// Starting from a. in the example, looking for a => a.
if (parameter.ContainingSymbol is not IMethodSymbol { MethodKind: MethodKind.AnonymousFunction } owningMethod)
return default;
// Cannot proceed without DeclaringSyntaxReferences.
// We expect that there is a single DeclaringSyntaxReferences in the scenario.
// If anything changes on the compiler side, the approach should be revised.
if (owningMethod.DeclaringSyntaxReferences.Length != 1)
return default;
var syntaxFactsService = _context.GetLanguageService<ISyntaxFactsService>();
// Check that a => a. belongs to an invocation.
// Find its' ordinal in the invocation, e.g. ThenInclude(a => a.Something, a=> a.
var lambdaSyntax = owningMethod.DeclaringSyntaxReferences.Single().GetSyntax(_cancellationToken);
if (!(syntaxFactsService.IsAnonymousFunction(lambdaSyntax) &&
syntaxFactsService.IsArgument(lambdaSyntax.Parent) &&
syntaxFactsService.IsInvocationExpression(lambdaSyntax.Parent.Parent.Parent)))
{
return default;
}
var invocationExpression = lambdaSyntax.Parent.Parent.Parent;
var arguments = syntaxFactsService.GetArgumentsOfInvocationExpression(invocationExpression);
var argumentName = syntaxFactsService.GetNameForArgument(lambdaSyntax.Parent);
var ordinalInInvocation = arguments.IndexOf(lambdaSyntax.Parent);
var expressionOfInvocationExpression = syntaxFactsService.GetExpressionOfInvocationExpression(invocationExpression);
var parameterTypeSymbols = ImmutableArray<ITypeSymbol>.Empty;
if (TryGetExplicitTypeOfLambdaParameter(lambdaSyntax, parameter.Ordinal, out var explicitLambdaParameterType))
{
parameterTypeSymbols = ImmutableArray.Create(explicitLambdaParameterType);
}
else
{
// Get all members potentially matching the invocation expression.
// We filter them out based on ordinality later.
var candidateSymbols = _context.SemanticModel.GetMemberGroup(expressionOfInvocationExpression, _cancellationToken);
// parameter.Ordinal is the ordinal within (a,b,c) => b.
// For candidate symbols of (a,b,c) => b., get types of all possible b.
parameterTypeSymbols = GetTypeSymbols(candidateSymbols, argumentName, ordinalInInvocation, ordinalInLambda: parameter.Ordinal);
// The parameterTypeSymbols may include type parameters, and we want their substituted types if available.
parameterTypeSymbols = SubstituteTypeParameters(parameterTypeSymbols, invocationExpression);
}
// For each type of b., return all suitable members. Also, ensure we consider the actual type of the
// parameter the compiler inferred as it may have made a completely suitable inference for it.
return parameterTypeSymbols
.Concat(parameter.Type)
.SelectMany(parameterTypeSymbol => GetMemberSymbols(parameterTypeSymbol, position, excludeInstance: false, useBaseReferenceAccessibility: false, unwrapNullable: false))
.ToImmutableArray();
}
private ImmutableArray<ITypeSymbol> SubstituteTypeParameters(ImmutableArray<ITypeSymbol> parameterTypeSymbols, SyntaxNode invocationExpression)
{
if (!parameterTypeSymbols.Any(t => t.IsKind(SymbolKind.TypeParameter)))
{
return parameterTypeSymbols;
}
var invocationSymbols = _context.SemanticModel.GetSymbolInfo(invocationExpression).GetAllSymbols();
if (invocationSymbols.Length == 0)
{
return parameterTypeSymbols;
}
using var _ = ArrayBuilder<ITypeSymbol>.GetInstance(out var concreteTypes);
foreach (var invocationSymbol in invocationSymbols)
{
var typeParameters = invocationSymbol.GetTypeParameters();
var typeArguments = invocationSymbol.GetTypeArguments();
foreach (var parameterTypeSymbol in parameterTypeSymbols)
{
if (parameterTypeSymbol.IsKind<ITypeParameterSymbol>(SymbolKind.TypeParameter, out var typeParameter))
{
// The typeParameter could be from the containing type, so it may not be
// present in this method's list of typeParameters.
var index = typeParameters.IndexOf(typeParameter);
var concreteType = typeArguments.ElementAtOrDefault(index);
// If we couldn't find the concrete type, still consider the typeParameter
// as is to provide members of any types it is constrained to (including object)
concreteTypes.Add(concreteType ?? typeParameter);
}
else
{
concreteTypes.Add(parameterTypeSymbol);
}
}
}
return concreteTypes.ToImmutable();
}
/// <summary>
/// Tries to get a type of its' <paramref name="ordinalInLambda"/> lambda parameter of <paramref name="ordinalInInvocation"/> argument for each candidate symbol.
/// </summary>
/// <param name="candidateSymbols">symbols corresponding to <see cref="Expression{Func}"/> or <see cref="Func{some_args, TResult}"/>
/// Here, some_args can be multi-variables lambdas as well, e.g. f((a,b) => a+b, (a,b,c)=>a*b*c.Length)
/// </param>
/// <param name="ordinalInInvocation">ordinal of the arguments of function: (a,b) or (a,b,c) in the example above</param>
/// <param name="ordinalInLambda">ordinal of the lambda parameters, e.g. a, b or c.</param>
/// <returns></returns>
private ImmutableArray<ITypeSymbol> GetTypeSymbols(ImmutableArray<ISymbol> candidateSymbols, string argumentName, int ordinalInInvocation, int ordinalInLambda)
{
var expressionSymbol = _context.SemanticModel.Compilation.GetTypeByMetadataName(typeof(Expression<>).FullName);
var builder = ArrayBuilder<ITypeSymbol>.GetInstance();
foreach (var candidateSymbol in candidateSymbols)
{
if (candidateSymbol is IMethodSymbol method)
{
if (!TryGetMatchingParameterTypeForArgument(method, argumentName, ordinalInInvocation, out var type))
{
continue;
}
// If type is <see cref="Expression{TDelegate}"/>, ignore <see cref="Expression"/> and use TDelegate.
// Ignore this check if expressionSymbol is null, e.g. semantic model is broken or incomplete or if the framework does not contain <see cref="Expression"/>.
if (expressionSymbol != null &&
type is INamedTypeSymbol expressionSymbolNamedTypeCandidate &&
expressionSymbolNamedTypeCandidate.OriginalDefinition.Equals(expressionSymbol))
{
var allTypeArguments = type.GetAllTypeArguments();
if (allTypeArguments.Length != 1)
{
continue;
}
type = allTypeArguments[0];
}
if (type.IsDelegateType())
{
var methods = type.GetMembers(WellKnownMemberNames.DelegateInvokeName);
if (methods.Length != 1)
{
continue;
}
var parameters = methods[0].GetParameters();
if (parameters.Length <= ordinalInLambda)
{
continue;
}
builder.Add(parameters[ordinalInLambda].Type);
}
}
}
return builder.ToImmutableAndFree().Distinct();
}
private bool TryGetMatchingParameterTypeForArgument(IMethodSymbol method, string argumentName, int ordinalInInvocation, out ITypeSymbol parameterType)
{
if (!string.IsNullOrEmpty(argumentName))
{
parameterType = method.Parameters.FirstOrDefault(p => _stringComparerForLanguage.Equals(p.Name, argumentName))?.Type;
return parameterType != null;
}
// We don't know the argument name, so have to find the parameter based on position
if (method.IsParams() && (ordinalInInvocation >= method.Parameters.Length - 1))
{
if (method.Parameters.LastOrDefault()?.Type is IArrayTypeSymbol arrayType)
{
parameterType = arrayType.ElementType;
return true;
}
else
{
parameterType = null;
return false;
}
}
if (ordinalInInvocation < method.Parameters.Length)
{
parameterType = method.Parameters[ordinalInInvocation].Type;
return true;
}
parameterType = null;
return false;
}
protected ImmutableArray<ISymbol> GetSymbolsForNamespaceDeclarationNameContext<TNamespaceDeclarationSyntax>()
where TNamespaceDeclarationSyntax : SyntaxNode
{
var declarationSyntax = _context.TargetToken.GetAncestor<TNamespaceDeclarationSyntax>();
if (declarationSyntax == null)
return ImmutableArray<ISymbol>.Empty;
var semanticModel = _context.SemanticModel;
var containingNamespaceSymbol = semanticModel.Compilation.GetCompilationNamespace(
semanticModel.GetEnclosingNamespace(declarationSyntax.SpanStart, _cancellationToken));
var symbols = semanticModel.LookupNamespacesAndTypes(declarationSyntax.SpanStart, containingNamespaceSymbol)
.WhereAsArray(recommendationSymbol => IsNonIntersectingNamespace(recommendationSymbol, declarationSyntax));
return symbols;
}
protected static bool IsNonIntersectingNamespace(ISymbol recommendationSymbol, SyntaxNode declarationSyntax)
{
//
// Apart from filtering out non-namespace symbols, this also filters out the symbol
// currently being declared. For example...
//
// namespace X$$
//
// ...X won't show in the completion list (unless it is also declared elsewhere).
//
// In addition, in VB, it will filter out Bar from the sample below...
//
// Namespace Goo.$$
// Namespace Bar
// End Namespace
// End Namespace
//
// ...unless, again, it's also declared elsewhere.
//
return recommendationSymbol.IsNamespace() &&
recommendationSymbol.Locations.Any(
candidateLocation => !(declarationSyntax.SyntaxTree == candidateLocation.SourceTree &&
declarationSyntax.Span.IntersectsWith(candidateLocation.SourceSpan)));
}
protected ImmutableArray<ISymbol> GetMemberSymbols(
ISymbol container,
int position,
bool excludeInstance,
bool useBaseReferenceAccessibility,
bool unwrapNullable)
{
// For a normal parameter, we have a specialized codepath we use to ensure we properly get lambda parameter
// information that the compiler may fail to give.
if (container is IParameterSymbol parameter)
return GetMemberSymbolsForParameter(parameter, position, useBaseReferenceAccessibility, unwrapNullable);
if (container is not INamespaceOrTypeSymbol namespaceOrType)
return ImmutableArray<ISymbol>.Empty;
if (unwrapNullable && namespaceOrType is ITypeSymbol typeSymbol)
{
namespaceOrType = typeSymbol.RemoveNullableIfPresent();
}
return useBaseReferenceAccessibility
? _context.SemanticModel.LookupBaseMembers(position)
: LookupSymbolsInContainer(namespaceOrType, position, excludeInstance);
}
protected ImmutableArray<ISymbol> LookupSymbolsInContainer(
INamespaceOrTypeSymbol container, int position, bool excludeInstance)
{
return excludeInstance
? _context.SemanticModel.LookupStaticMembers(position, container)
: SuppressDefaultTupleElements(
container,
_context.SemanticModel.LookupSymbols(position, container, includeReducedExtensionMethods: true));
}
/// <summary>
/// If container is a tuple type, any of its tuple element which has a friendly name will cause
/// the suppression of the corresponding default name (ItemN).
/// In that case, Rest is also removed.
/// </summary>
protected static ImmutableArray<ISymbol> SuppressDefaultTupleElements(
INamespaceOrTypeSymbol container, ImmutableArray<ISymbol> symbols)
{
var namedType = container as INamedTypeSymbol;
if (namedType?.IsTupleType != true)
{
// container is not a tuple
return symbols;
}
//return tuple elements followed by other members that are not fields
return ImmutableArray<ISymbol>.CastUp(namedType.TupleElements).
Concat(symbols.WhereAsArray(s => s.Kind != SymbolKind.Field));
}
}
}
| 1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/SyntaxNodeExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static partial class SyntaxNodeExtensions
{
public static void Deconstruct(this SyntaxNode node, out SyntaxKind kind)
{
kind = node.Kind();
}
public static bool IsKind<TNode>([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind, [NotNullWhen(returnValue: true)] out TNode? result)
where TNode : SyntaxNode
{
if (node.IsKind(kind))
{
result = (TNode)node;
return true;
}
result = null;
return false;
}
public static bool IsParentKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind)
=> CodeAnalysis.CSharpExtensions.IsKind(node?.Parent, kind);
public static bool IsParentKind<TNode>([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind, [NotNullWhen(returnValue: true)] out TNode? result)
where TNode : SyntaxNode
{
if (node.IsParentKind(kind))
{
result = (TNode)node.Parent!;
return true;
}
result = null;
return false;
}
public static bool IsParentKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2)
=> IsKind(node?.Parent, kind1, kind2);
public static bool IsParentKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3)
=> IsKind(node?.Parent, kind1, kind2, kind3);
public static bool IsParentKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4)
=> IsKind(node?.Parent, kind1, kind2, kind3, kind4);
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2;
}
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3;
}
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4;
}
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5;
}
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6;
}
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6, SyntaxKind kind7)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6 || csharpKind == kind7;
}
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6, SyntaxKind kind7, SyntaxKind kind8)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6 || csharpKind == kind7 || csharpKind == kind8;
}
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6, SyntaxKind kind7, SyntaxKind kind8, SyntaxKind kind9, SyntaxKind kind10)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6 || csharpKind == kind7 || csharpKind == kind8 || csharpKind == kind9 || csharpKind == kind10;
}
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6, SyntaxKind kind7, SyntaxKind kind8, SyntaxKind kind9, SyntaxKind kind10, SyntaxKind kind11)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6 || csharpKind == kind7 || csharpKind == kind8 || csharpKind == kind9 || csharpKind == kind10 || csharpKind == kind11;
}
public static IEnumerable<SyntaxTrivia> GetAllPrecedingTriviaToPreviousToken(
this SyntaxNode node, SourceText? sourceText = null,
bool includePreviousTokenTrailingTriviaOnlyIfOnSameLine = false)
=> node.GetFirstToken().GetAllPrecedingTriviaToPreviousToken(
sourceText, includePreviousTokenTrailingTriviaOnlyIfOnSameLine);
/// <summary>
/// Returns all of the trivia to the left of this token up to the previous token (concatenates
/// the previous token's trailing trivia and this token's leading trivia).
/// </summary>
public static IEnumerable<SyntaxTrivia> GetAllPrecedingTriviaToPreviousToken(
this SyntaxToken token, SourceText? sourceText = null,
bool includePreviousTokenTrailingTriviaOnlyIfOnSameLine = false)
{
var prevToken = token.GetPreviousToken(includeSkipped: true);
if (prevToken.Kind() == SyntaxKind.None)
{
return token.LeadingTrivia;
}
Contract.ThrowIfTrue(sourceText == null && includePreviousTokenTrailingTriviaOnlyIfOnSameLine, "If we are including previous token trailing trivia, we need the text too.");
if (includePreviousTokenTrailingTriviaOnlyIfOnSameLine &&
!sourceText!.AreOnSameLine(prevToken, token))
{
return token.LeadingTrivia;
}
return prevToken.TrailingTrivia.Concat(token.LeadingTrivia);
}
public static bool IsAnyArgumentList([NotNullWhen(returnValue: true)] this SyntaxNode? node)
{
return node.IsKind(SyntaxKind.ArgumentList) ||
node.IsKind(SyntaxKind.AttributeArgumentList) ||
node.IsKind(SyntaxKind.BracketedArgumentList) ||
node.IsKind(SyntaxKind.TypeArgumentList);
}
public static (SyntaxToken openBrace, SyntaxToken closeBrace) GetBraces(this SyntaxNode? node)
{
switch (node)
{
case NamespaceDeclarationSyntax namespaceNode:
return (namespaceNode.OpenBraceToken, namespaceNode.CloseBraceToken);
case BaseTypeDeclarationSyntax baseTypeNode:
return (baseTypeNode.OpenBraceToken, baseTypeNode.CloseBraceToken);
case AccessorListSyntax accessorListNode:
return (accessorListNode.OpenBraceToken, accessorListNode.CloseBraceToken);
case BlockSyntax blockNode:
return (blockNode.OpenBraceToken, blockNode.CloseBraceToken);
case SwitchStatementSyntax switchStatementNode:
return (switchStatementNode.OpenBraceToken, switchStatementNode.CloseBraceToken);
case AnonymousObjectCreationExpressionSyntax anonymousObjectCreationExpression:
return (anonymousObjectCreationExpression.OpenBraceToken, anonymousObjectCreationExpression.CloseBraceToken);
case InitializerExpressionSyntax initializeExpressionNode:
return (initializeExpressionNode.OpenBraceToken, initializeExpressionNode.CloseBraceToken);
case SwitchExpressionSyntax switchExpression:
return (switchExpression.OpenBraceToken, switchExpression.CloseBraceToken);
case PropertyPatternClauseSyntax property:
return (property.OpenBraceToken, property.CloseBraceToken);
case WithExpressionSyntax withExpr:
return (withExpr.Initializer.OpenBraceToken, withExpr.Initializer.CloseBraceToken);
case ImplicitObjectCreationExpressionSyntax { Initializer: { } initializer }:
return (initializer.OpenBraceToken, initializer.CloseBraceToken);
}
return default;
}
public static bool IsEmbeddedStatementOwner([NotNullWhen(returnValue: true)] this SyntaxNode? node)
{
return node is DoStatementSyntax ||
node is ElseClauseSyntax ||
node is FixedStatementSyntax ||
node is CommonForEachStatementSyntax ||
node is ForStatementSyntax ||
node is IfStatementSyntax ||
node is LabeledStatementSyntax ||
node is LockStatementSyntax ||
node is UsingStatementSyntax ||
node is WhileStatementSyntax;
}
public static StatementSyntax? GetEmbeddedStatement(this SyntaxNode? node)
=> node switch
{
DoStatementSyntax n => n.Statement,
ElseClauseSyntax n => n.Statement,
FixedStatementSyntax n => n.Statement,
CommonForEachStatementSyntax n => n.Statement,
ForStatementSyntax n => n.Statement,
IfStatementSyntax n => n.Statement,
LabeledStatementSyntax n => n.Statement,
LockStatementSyntax n => n.Statement,
UsingStatementSyntax n => n.Statement,
WhileStatementSyntax n => n.Statement,
_ => null,
};
public static BaseParameterListSyntax? GetParameterList(this SyntaxNode? declaration)
=> declaration?.Kind() switch
{
SyntaxKind.DelegateDeclaration => ((DelegateDeclarationSyntax)declaration).ParameterList,
SyntaxKind.MethodDeclaration => ((MethodDeclarationSyntax)declaration).ParameterList,
SyntaxKind.OperatorDeclaration => ((OperatorDeclarationSyntax)declaration).ParameterList,
SyntaxKind.ConversionOperatorDeclaration => ((ConversionOperatorDeclarationSyntax)declaration).ParameterList,
SyntaxKind.ConstructorDeclaration => ((ConstructorDeclarationSyntax)declaration).ParameterList,
SyntaxKind.DestructorDeclaration => ((DestructorDeclarationSyntax)declaration).ParameterList,
SyntaxKind.IndexerDeclaration => ((IndexerDeclarationSyntax)declaration).ParameterList,
SyntaxKind.ParenthesizedLambdaExpression => ((ParenthesizedLambdaExpressionSyntax)declaration).ParameterList,
SyntaxKind.LocalFunctionStatement => ((LocalFunctionStatementSyntax)declaration).ParameterList,
SyntaxKind.AnonymousMethodExpression => ((AnonymousMethodExpressionSyntax)declaration).ParameterList,
SyntaxKind.RecordDeclaration or SyntaxKind.RecordStructDeclaration => ((RecordDeclarationSyntax)declaration).ParameterList,
_ => null,
};
public static SyntaxList<AttributeListSyntax> GetAttributeLists(this SyntaxNode? declaration)
=> declaration switch
{
MemberDeclarationSyntax memberDecl => memberDecl.AttributeLists,
AccessorDeclarationSyntax accessor => accessor.AttributeLists,
ParameterSyntax parameter => parameter.AttributeLists,
CompilationUnitSyntax compilationUnit => compilationUnit.AttributeLists,
_ => default,
};
public static ConditionalAccessExpressionSyntax? GetParentConditionalAccessExpression(this SyntaxNode? node)
{
// Walk upwards based on the grammar/parser rules around ?. expressions (can be seen in
// LanguageParser.ParseConsequenceSyntax).
// These are the parts of the expression that the ?... expression can end with. Specifically:
//
// 1. x?.y.M() // invocation
// 2. x?.y[...]; // element access
// 3. x?.y.z // member access
// 4. x?.y // member binding
// 5. x?[y] // element binding
var current = node;
if ((current.IsParentKind(SyntaxKind.SimpleMemberAccessExpression, out MemberAccessExpressionSyntax? memberAccess) && memberAccess.Name == current) ||
(current.IsParentKind(SyntaxKind.MemberBindingExpression, out MemberBindingExpressionSyntax? memberBinding) && memberBinding.Name == current))
{
current = current.Parent;
}
// Effectively, if we're on the RHS of the ? we have to walk up the RHS spine first until we hit the first
// conditional access.
while (current.IsKind(
SyntaxKind.InvocationExpression,
SyntaxKind.ElementAccessExpression,
SyntaxKind.SimpleMemberAccessExpression,
SyntaxKind.MemberBindingExpression,
SyntaxKind.ElementBindingExpression) &&
current.Parent is not ConditionalAccessExpressionSyntax)
{
current = current.Parent;
}
// Two cases we have to care about:
//
// 1. a?.b.$$c.d and
// 2. a?.b.$$c.d?.e...
//
// Note that `a?.b.$$c.d?.e.f?.g.h.i` falls into the same bucket as two. i.e. the parts after `.e` are
// lower in the tree and are not seen as we walk upwards.
//
//
// To get the root ?. (the one after the `a`) we have to potentially consume the first ?. on the RHS of the
// right spine (i.e. the one after `d`). Once we do this, we then see if that itself is on the RHS of a
// another conditional, and if so we hten return the one on the left. i.e. for '2' this goes in this direction:
//
// a?.b.$$c.d?.e // it will do:
// ----->
// <---------
//
// Note that this only one CAE consumption on both sides. GetRootConditionalAccessExpression can be used to
// get the root parent in a case like:
//
// x?.y?.z?.a?.b.$$c.d?.e.f?.g.h.i // it will do:
// ----->
// <---------
// <---
// <---
// <---
if (current.IsParentKind(SyntaxKind.ConditionalAccessExpression, out ConditionalAccessExpressionSyntax? conditional) &&
conditional.Expression == current)
{
current = conditional;
}
if (current.IsParentKind(SyntaxKind.ConditionalAccessExpression, out conditional) &&
conditional.WhenNotNull == current)
{
current = conditional;
}
return current as ConditionalAccessExpressionSyntax;
}
/// <summary>
/// <inheritdoc cref="ISyntaxFacts.GetRootConditionalAccessExpression(SyntaxNode)"/>
/// </summary>>
public static ConditionalAccessExpressionSyntax? GetRootConditionalAccessExpression(this SyntaxNode? node)
{
// Once we've walked up the entire RHS, now we continually walk up the conditional accesses until we're at
// the root. For example, if we have `a?.b` and we're on the `.b`, this will give `a?.b`. Similarly with
// `a?.b?.c` if we're on either `.b` or `.c` this will result in `a?.b?.c` (i.e. the root of this CAE
// sequence).
var current = node.GetParentConditionalAccessExpression();
while (current.IsParentKind(SyntaxKind.ConditionalAccessExpression, out ConditionalAccessExpressionSyntax? conditional) &&
conditional.WhenNotNull == current)
{
current = conditional;
}
return current;
}
public static ConditionalAccessExpressionSyntax? GetInnerMostConditionalAccessExpression(this SyntaxNode node)
{
if (!(node is ConditionalAccessExpressionSyntax))
{
return null;
}
var result = (ConditionalAccessExpressionSyntax)node;
while (result.WhenNotNull is ConditionalAccessExpressionSyntax)
{
result = (ConditionalAccessExpressionSyntax)result.WhenNotNull;
}
return result;
}
public static bool IsAsyncSupportingFunctionSyntax([NotNullWhen(returnValue: true)] this SyntaxNode? node)
{
return node.IsKind(SyntaxKind.MethodDeclaration)
|| node.IsAnyLambdaOrAnonymousMethod()
|| node.IsKind(SyntaxKind.LocalFunctionStatement);
}
public static bool IsAnyLambda([NotNullWhen(returnValue: true)] this SyntaxNode? node)
{
return
node.IsKind(SyntaxKind.ParenthesizedLambdaExpression) ||
node.IsKind(SyntaxKind.SimpleLambdaExpression);
}
public static bool IsAnyLambdaOrAnonymousMethod([NotNullWhen(returnValue: true)] this SyntaxNode? node)
=> node.IsAnyLambda() || node.IsKind(SyntaxKind.AnonymousMethodExpression);
public static bool IsAnyAssignExpression(this SyntaxNode node)
=> SyntaxFacts.IsAssignmentExpression(node.Kind());
public static bool IsCompoundAssignExpression(this SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.CoalesceAssignmentExpression:
case SyntaxKind.AddAssignmentExpression:
case SyntaxKind.SubtractAssignmentExpression:
case SyntaxKind.MultiplyAssignmentExpression:
case SyntaxKind.DivideAssignmentExpression:
case SyntaxKind.ModuloAssignmentExpression:
case SyntaxKind.AndAssignmentExpression:
case SyntaxKind.ExclusiveOrAssignmentExpression:
case SyntaxKind.OrAssignmentExpression:
case SyntaxKind.LeftShiftAssignmentExpression:
case SyntaxKind.RightShiftAssignmentExpression:
return true;
}
return false;
}
public static bool IsLeftSideOfAssignExpression([NotNullWhen(returnValue: true)] this SyntaxNode? node)
=> node.IsParentKind(SyntaxKind.SimpleAssignmentExpression, out AssignmentExpressionSyntax? assignment) &&
assignment.Left == node;
public static bool IsLeftSideOfAnyAssignExpression([NotNullWhen(true)] this SyntaxNode? node)
{
return node?.Parent != null &&
node.Parent.IsAnyAssignExpression() &&
((AssignmentExpressionSyntax)node.Parent).Left == node;
}
public static bool IsRightSideOfAnyAssignExpression([NotNullWhen(true)] this SyntaxNode? node)
{
return node?.Parent != null &&
node.Parent.IsAnyAssignExpression() &&
((AssignmentExpressionSyntax)node.Parent).Right == node;
}
public static bool IsLeftSideOfCompoundAssignExpression([NotNullWhen(true)] this SyntaxNode? node)
{
return node?.Parent != null &&
node.Parent.IsCompoundAssignExpression() &&
((AssignmentExpressionSyntax)node.Parent).Left == node;
}
/// <summary>
/// Returns the list of using directives that affect <paramref name="node"/>. The list will be returned in
/// top down order.
/// </summary>
public static IEnumerable<UsingDirectiveSyntax> GetEnclosingUsingDirectives(this SyntaxNode node)
{
return node.GetAncestorOrThis<CompilationUnitSyntax>()!.Usings
.Concat(node.GetAncestorsOrThis<BaseNamespaceDeclarationSyntax>()
.Reverse()
.SelectMany(n => n.Usings));
}
public static IEnumerable<ExternAliasDirectiveSyntax> GetEnclosingExternAliasDirectives(this SyntaxNode node)
{
return node.GetAncestorOrThis<CompilationUnitSyntax>()!.Externs
.Concat(node.GetAncestorsOrThis<BaseNamespaceDeclarationSyntax>()
.Reverse()
.SelectMany(n => n.Externs));
}
public static bool IsUnsafeContext(this SyntaxNode node)
{
if (node.GetAncestor<UnsafeStatementSyntax>() != null)
{
return true;
}
return node.GetAncestors<MemberDeclarationSyntax>().Any(
m => m.GetModifiers().Any(SyntaxKind.UnsafeKeyword));
}
public static bool IsInStaticContext(this SyntaxNode node)
{
// this/base calls are always static.
if (node.FirstAncestorOrSelf<ConstructorInitializerSyntax>() != null)
{
return true;
}
var memberDeclaration = node.FirstAncestorOrSelf<MemberDeclarationSyntax>();
if (memberDeclaration == null)
{
return false;
}
switch (memberDeclaration.Kind())
{
case SyntaxKind.MethodDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.EventDeclaration:
case SyntaxKind.IndexerDeclaration:
return memberDeclaration.GetModifiers().Any(SyntaxKind.StaticKeyword);
case SyntaxKind.PropertyDeclaration:
return memberDeclaration.GetModifiers().Any(SyntaxKind.StaticKeyword) ||
node.IsFoundUnder((PropertyDeclarationSyntax p) => p.Initializer);
case SyntaxKind.FieldDeclaration:
case SyntaxKind.EventFieldDeclaration:
// Inside a field one can only access static members of a type (unless it's top-level).
return !memberDeclaration.Parent.IsKind(SyntaxKind.CompilationUnit);
case SyntaxKind.DestructorDeclaration:
return false;
}
// Global statements are not a static context.
if (node.FirstAncestorOrSelf<GlobalStatementSyntax>() != null)
{
return false;
}
// any other location is considered static
return true;
}
public static BaseNamespaceDeclarationSyntax? GetInnermostNamespaceDeclarationWithUsings(this SyntaxNode contextNode)
{
var usingDirectiveAncestor = contextNode.GetAncestor<UsingDirectiveSyntax>();
if (usingDirectiveAncestor == null)
{
return contextNode.GetAncestorsOrThis<BaseNamespaceDeclarationSyntax>().FirstOrDefault(n => n.Usings.Count > 0);
}
else
{
// We are inside a using directive. In this case, we should find and return the first 'parent' namespace with usings.
var containingNamespace = usingDirectiveAncestor.GetAncestor<BaseNamespaceDeclarationSyntax>();
if (containingNamespace == null)
{
// We are inside a top level using directive (i.e. one that's directly in the compilation unit).
return null;
}
else
{
return containingNamespace.GetAncestors<BaseNamespaceDeclarationSyntax>().FirstOrDefault(n => n.Usings.Count > 0);
}
}
}
public static bool IsBreakableConstruct(this SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.DoStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.SwitchStatement:
case SyntaxKind.ForStatement:
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
return true;
}
return false;
}
public static bool IsContinuableConstruct(this SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.DoStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.ForStatement:
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
return true;
}
return false;
}
public static bool IsReturnableConstruct(this SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.AnonymousMethodExpression:
case SyntaxKind.SimpleLambdaExpression:
case SyntaxKind.ParenthesizedLambdaExpression:
case SyntaxKind.LocalFunctionStatement:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.InitAccessorDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
return true;
}
return false;
}
public static bool SpansPreprocessorDirective<TSyntaxNode>(this IEnumerable<TSyntaxNode> list) where TSyntaxNode : SyntaxNode
=> CSharpSyntaxFacts.Instance.SpansPreprocessorDirective(list);
[return: NotNullIfNotNull("node")]
public static TNode? ConvertToSingleLine<TNode>(this TNode? node, bool useElasticTrivia = false)
where TNode : SyntaxNode
{
if (node == null)
{
return node;
}
var rewriter = new SingleLineRewriter(useElasticTrivia);
return (TNode)rewriter.Visit(node);
}
/// <summary>
/// Returns true if the passed in node contains an interleaved pp directive.
///
/// i.e. The following returns false:
///
/// void Goo() {
/// #if true
/// #endif
/// }
///
/// #if true
/// void Goo() {
/// }
/// #endif
///
/// but these return true:
///
/// #if true
/// void Goo() {
/// #endif
/// }
///
/// void Goo() {
/// #if true
/// }
/// #endif
///
/// #if true
/// void Goo() {
/// #else
/// }
/// #endif
///
/// i.e. the method returns true if it contains a PP directive that belongs to a grouping
/// constructs (like #if/#endif or #region/#endregion), but the grouping construct isn't
/// entirely contained within the span of the node.
/// </summary>
public static bool ContainsInterleavedDirective(this SyntaxNode syntaxNode, CancellationToken cancellationToken)
=> CSharpSyntaxFacts.Instance.ContainsInterleavedDirective(syntaxNode, cancellationToken);
/// <summary>
/// Similar to <see cref="ContainsInterleavedDirective(SyntaxNode, CancellationToken)"/> except that the span to check
/// for interleaved directives can be specified separately to the node passed in.
/// </summary>
public static bool ContainsInterleavedDirective(this SyntaxNode syntaxNode, TextSpan span, CancellationToken cancellationToken)
=> CSharpSyntaxFacts.Instance.ContainsInterleavedDirective(span, syntaxNode, cancellationToken);
public static bool ContainsInterleavedDirective(
this SyntaxToken token,
TextSpan textSpan,
CancellationToken cancellationToken)
{
return
ContainsInterleavedDirective(textSpan, token.LeadingTrivia, cancellationToken) ||
ContainsInterleavedDirective(textSpan, token.TrailingTrivia, cancellationToken);
}
private static bool ContainsInterleavedDirective(
TextSpan textSpan,
SyntaxTriviaList list,
CancellationToken cancellationToken)
{
foreach (var trivia in list)
{
if (textSpan.Contains(trivia.Span))
{
if (ContainsInterleavedDirective(textSpan, trivia, cancellationToken))
{
return true;
}
}
}
return false;
}
private static bool ContainsInterleavedDirective(
TextSpan textSpan,
SyntaxTrivia trivia,
CancellationToken cancellationToken)
{
if (trivia.HasStructure)
{
var structure = trivia.GetStructure()!;
if (trivia.GetStructure().IsKind(SyntaxKind.RegionDirectiveTrivia,
SyntaxKind.EndRegionDirectiveTrivia,
SyntaxKind.IfDirectiveTrivia,
SyntaxKind.EndIfDirectiveTrivia))
{
var match = ((DirectiveTriviaSyntax)structure).GetMatchingDirective(cancellationToken);
if (match != null)
{
var matchSpan = match.Span;
if (!textSpan.Contains(matchSpan.Start))
{
// The match for this pp directive is outside
// this node.
return true;
}
}
}
else if (trivia.GetStructure().IsKind(SyntaxKind.ElseDirectiveTrivia, SyntaxKind.ElifDirectiveTrivia))
{
var directives = ((DirectiveTriviaSyntax)structure).GetMatchingConditionalDirectives(cancellationToken);
if (directives != null && directives.Count > 0)
{
if (!textSpan.Contains(directives[0].SpanStart) ||
!textSpan.Contains(directives[directives.Count - 1].SpanStart))
{
// This else/elif belongs to a pp span that isn't
// entirely within this node.
return true;
}
}
}
}
return false;
}
/// <summary>
/// Breaks up the list of provided nodes, based on how they are interspersed with pp
/// directives, into groups. Within these groups nodes can be moved around safely, without
/// breaking any pp constructs.
/// </summary>
public static IList<IList<TSyntaxNode>> SplitNodesOnPreprocessorBoundaries<TSyntaxNode>(
this IEnumerable<TSyntaxNode> nodes,
CancellationToken cancellationToken)
where TSyntaxNode : SyntaxNode
{
var result = new List<IList<TSyntaxNode>>();
var currentGroup = new List<TSyntaxNode>();
foreach (var node in nodes)
{
var hasUnmatchedInteriorDirective = node.ContainsInterleavedDirective(cancellationToken);
var hasLeadingDirective = node.GetLeadingTrivia().Any(t => SyntaxFacts.IsPreprocessorDirective(t.Kind()));
if (hasUnmatchedInteriorDirective)
{
// we have a #if/#endif/#region/#endregion/#else/#elif in
// this node that belongs to a span of pp directives that
// is not entirely contained within the node. i.e.:
//
// void Goo() {
// #if ...
// }
//
// This node cannot be moved at all. It is in a group that
// only contains itself (and thus can never be moved).
// add whatever group we've built up to now. And reset the
// next group to empty.
result.Add(currentGroup);
currentGroup = new List<TSyntaxNode>();
result.Add(new List<TSyntaxNode> { node });
}
else if (hasLeadingDirective)
{
// We have a PP directive before us. i.e.:
//
// #if ...
// void Goo() {
//
// That means we start a new group that is contained between
// the above directive and the following directive.
// add whatever group we've built up to now. And reset the
// next group to empty.
result.Add(currentGroup);
currentGroup = new List<TSyntaxNode>();
currentGroup.Add(node);
}
else
{
// simple case. just add ourselves to the current group
currentGroup.Add(node);
}
}
// add the remainder of the final group.
result.Add(currentGroup);
// Now, filter out any empty groups.
result = result.Where(group => !group.IsEmpty()).ToList();
return result;
}
public static ImmutableArray<SyntaxTrivia> GetLeadingBlankLines<TSyntaxNode>(this TSyntaxNode node) where TSyntaxNode : SyntaxNode
=> CSharpSyntaxFacts.Instance.GetLeadingBlankLines(node);
public static TSyntaxNode GetNodeWithoutLeadingBlankLines<TSyntaxNode>(this TSyntaxNode node) where TSyntaxNode : SyntaxNode
=> CSharpSyntaxFacts.Instance.GetNodeWithoutLeadingBlankLines(node);
public static TSyntaxNode GetNodeWithoutLeadingBlankLines<TSyntaxNode>(this TSyntaxNode node, out ImmutableArray<SyntaxTrivia> strippedTrivia) where TSyntaxNode : SyntaxNode
=> CSharpSyntaxFacts.Instance.GetNodeWithoutLeadingBlankLines(node, out strippedTrivia);
public static ImmutableArray<SyntaxTrivia> GetLeadingBannerAndPreprocessorDirectives<TSyntaxNode>(this TSyntaxNode node) where TSyntaxNode : SyntaxNode
=> CSharpSyntaxFacts.Instance.GetLeadingBannerAndPreprocessorDirectives(node);
public static TSyntaxNode GetNodeWithoutLeadingBannerAndPreprocessorDirectives<TSyntaxNode>(this TSyntaxNode node) where TSyntaxNode : SyntaxNode
=> CSharpSyntaxFacts.Instance.GetNodeWithoutLeadingBannerAndPreprocessorDirectives(node);
public static TSyntaxNode GetNodeWithoutLeadingBannerAndPreprocessorDirectives<TSyntaxNode>(this TSyntaxNode node, out ImmutableArray<SyntaxTrivia> strippedTrivia) where TSyntaxNode : SyntaxNode
=> CSharpSyntaxFacts.Instance.GetNodeWithoutLeadingBannerAndPreprocessorDirectives(node, out strippedTrivia);
public static bool IsVariableDeclaratorValue(this SyntaxNode node)
=> node.IsParentKind(SyntaxKind.EqualsValueClause, out EqualsValueClauseSyntax? equalsValue) &&
equalsValue.IsParentKind(SyntaxKind.VariableDeclarator) &&
equalsValue.Value == node;
public static BlockSyntax? FindInnermostCommonBlock(this IEnumerable<SyntaxNode> nodes)
=> nodes.FindInnermostCommonNode<BlockSyntax>();
public static IEnumerable<SyntaxNode> GetAncestorsOrThis(this SyntaxNode? node, Func<SyntaxNode, bool> predicate)
{
var current = node;
while (current != null)
{
if (predicate(current))
{
yield return current;
}
current = current.Parent;
}
}
/// <summary>
/// Returns child node or token that contains given position.
/// </summary>
/// <remarks>
/// This is a copy of <see cref="SyntaxNode.ChildThatContainsPosition"/> that also returns the index of the child node.
/// </remarks>
internal static SyntaxNodeOrToken ChildThatContainsPosition(this SyntaxNode self, int position, out int childIndex)
{
var childList = self.ChildNodesAndTokens();
var left = 0;
var right = childList.Count - 1;
while (left <= right)
{
var middle = left + ((right - left) / 2);
var node = childList[middle];
var span = node.FullSpan;
if (position < span.Start)
{
right = middle - 1;
}
else if (position >= span.End)
{
left = middle + 1;
}
else
{
childIndex = middle;
return node;
}
}
// we could check up front that index is within FullSpan,
// but we wan to optimize for the common case where position is valid.
Debug.Assert(!self.FullSpan.Contains(position), "Position is valid. How could we not find a child?");
throw new ArgumentOutOfRangeException(nameof(position));
}
public static (SyntaxToken openParen, SyntaxToken closeParen) GetParentheses(this SyntaxNode node)
{
switch (node)
{
case ParenthesizedExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case MakeRefExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case RefTypeExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case RefValueExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case CheckedExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case DefaultExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case TypeOfExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case SizeOfExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case ArgumentListSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case CastExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case WhileStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case DoStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case ForStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case CommonForEachStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case UsingStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case FixedStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case LockStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case IfStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case SwitchStatementSyntax n when n.OpenParenToken != default: return (n.OpenParenToken, n.CloseParenToken);
case TupleExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case CatchDeclarationSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case AttributeArgumentListSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case ConstructorConstraintSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case ParameterListSyntax n: return (n.OpenParenToken, n.CloseParenToken);
default: return default;
}
}
public static (SyntaxToken openBracket, SyntaxToken closeBracket) GetBrackets(this SyntaxNode node)
{
switch (node)
{
case ArrayRankSpecifierSyntax n: return (n.OpenBracketToken, n.CloseBracketToken);
case BracketedArgumentListSyntax n: return (n.OpenBracketToken, n.CloseBracketToken);
case ImplicitArrayCreationExpressionSyntax n: return (n.OpenBracketToken, n.CloseBracketToken);
case AttributeListSyntax n: return (n.OpenBracketToken, n.CloseBracketToken);
case BracketedParameterListSyntax n: return (n.OpenBracketToken, n.CloseBracketToken);
default: return default;
}
}
public static SyntaxTokenList GetModifiers(this SyntaxNode? member)
{
switch (member)
{
case MemberDeclarationSyntax memberDecl: return memberDecl.Modifiers;
case AccessorDeclarationSyntax accessor: return accessor.Modifiers;
case AnonymousFunctionExpressionSyntax anonymous: return anonymous.Modifiers;
case LocalFunctionStatementSyntax localFunction: return localFunction.Modifiers;
case LocalDeclarationStatementSyntax localDeclaration: return localDeclaration.Modifiers;
}
return default;
}
public static SyntaxNode? WithModifiers(this SyntaxNode? member, SyntaxTokenList modifiers)
{
switch (member)
{
case MemberDeclarationSyntax memberDecl: return memberDecl.WithModifiers(modifiers);
case AccessorDeclarationSyntax accessor: return accessor.WithModifiers(modifiers);
case AnonymousFunctionExpressionSyntax anonymous: return anonymous.WithModifiers(modifiers);
case LocalFunctionStatementSyntax localFunction: return localFunction.WithModifiers(modifiers);
case LocalDeclarationStatementSyntax localDeclaration: return localDeclaration.WithModifiers(modifiers);
}
return null;
}
public static bool CheckTopLevel(this SyntaxNode node, TextSpan span)
{
switch (node)
{
case BlockSyntax block:
return block.ContainsInBlockBody(span);
case ArrowExpressionClauseSyntax expressionBodiedMember:
return expressionBodiedMember.ContainsInExpressionBodiedMemberBody(span);
case FieldDeclarationSyntax field:
{
foreach (var variable in field.Declaration.Variables)
{
if (variable.Initializer != null && variable.Initializer.Span.Contains(span))
{
return true;
}
}
break;
}
case GlobalStatementSyntax _:
return true;
case ConstructorInitializerSyntax constructorInitializer:
return constructorInitializer.ContainsInArgument(span);
}
return false;
}
public static bool ContainsInArgument(this ConstructorInitializerSyntax initializer, TextSpan textSpan)
{
if (initializer == null)
{
return false;
}
return initializer.ArgumentList.Arguments.Any(a => a.Span.Contains(textSpan));
}
public static bool ContainsInBlockBody(this BlockSyntax block, TextSpan textSpan)
{
if (block == null)
{
return false;
}
var blockSpan = TextSpan.FromBounds(block.OpenBraceToken.Span.End, block.CloseBraceToken.SpanStart);
return blockSpan.Contains(textSpan);
}
public static bool ContainsInExpressionBodiedMemberBody(this ArrowExpressionClauseSyntax expressionBodiedMember, TextSpan textSpan)
{
if (expressionBodiedMember == null)
{
return false;
}
var expressionBodiedMemberBody = TextSpan.FromBounds(expressionBodiedMember.Expression.SpanStart, expressionBodiedMember.Expression.Span.End);
return expressionBodiedMemberBody.Contains(textSpan);
}
public static IEnumerable<MemberDeclarationSyntax> GetMembers(this SyntaxNode? node)
{
switch (node)
{
case CompilationUnitSyntax compilation:
return compilation.Members;
case BaseNamespaceDeclarationSyntax @namespace:
return @namespace.Members;
case TypeDeclarationSyntax type:
return type.Members;
case EnumDeclarationSyntax @enum:
return @enum.Members;
}
return SpecializedCollections.EmptyEnumerable<MemberDeclarationSyntax>();
}
public static bool IsInExpressionTree(
[NotNullWhen(returnValue: true)] this SyntaxNode? node,
SemanticModel semanticModel,
[NotNullWhen(returnValue: true)] INamedTypeSymbol? expressionTypeOpt,
CancellationToken cancellationToken)
{
if (expressionTypeOpt != null)
{
for (var current = node; current != null; current = current.Parent)
{
if (current.IsAnyLambda())
{
var typeInfo = semanticModel.GetTypeInfo(current, cancellationToken);
if (expressionTypeOpt.Equals(typeInfo.ConvertedType?.OriginalDefinition))
return true;
}
else if (current is SelectOrGroupClauseSyntax ||
current is OrderingSyntax)
{
var info = semanticModel.GetSymbolInfo(current, cancellationToken);
if (TakesExpressionTree(info, expressionTypeOpt))
return true;
}
else if (current is QueryClauseSyntax queryClause)
{
var info = semanticModel.GetQueryClauseInfo(queryClause, cancellationToken);
if (TakesExpressionTree(info.CastInfo, expressionTypeOpt) ||
TakesExpressionTree(info.OperationInfo, expressionTypeOpt))
{
return true;
}
}
}
}
return false;
static bool TakesExpressionTree(SymbolInfo info, INamedTypeSymbol expressionType)
{
foreach (var symbol in info.GetAllSymbols())
{
if (symbol is IMethodSymbol method &&
method.Parameters.Length > 0 &&
expressionType.Equals(method.Parameters[0].Type?.OriginalDefinition))
{
return true;
}
}
return false;
}
}
public static bool IsInDeconstructionLeft(
[NotNullWhen(returnValue: true)] this SyntaxNode? node,
[NotNullWhen(returnValue: true)] out SyntaxNode? deconstructionLeft)
{
SyntaxNode? previous = null;
for (var current = node; current != null; current = current.Parent)
{
if ((current is AssignmentExpressionSyntax assignment && previous == assignment.Left && assignment.IsDeconstruction()) ||
(current is ForEachVariableStatementSyntax @foreach && previous == @foreach.Variable))
{
deconstructionLeft = previous;
return true;
}
if (current is StatementSyntax)
{
break;
}
previous = current;
}
deconstructionLeft = null;
return false;
}
public static bool IsTopLevelOfUsingAliasDirective(this SyntaxToken node)
=> node switch
{
{ Parent: NameEqualsSyntax { Parent: UsingDirectiveSyntax _ } } => true,
{ Parent: IdentifierNameSyntax { Parent: UsingDirectiveSyntax _ } } => true,
_ => false
};
public static T WithCommentsFrom<T>(this T node, SyntaxToken leadingToken, SyntaxToken trailingToken)
where T : SyntaxNode
=> node.WithCommentsFrom(
SyntaxNodeOrTokenExtensions.GetTrivia(leadingToken),
SyntaxNodeOrTokenExtensions.GetTrivia(trailingToken));
public static T WithCommentsFrom<T>(
this T node,
IEnumerable<SyntaxToken> leadingTokens,
IEnumerable<SyntaxToken> trailingTokens)
where T : SyntaxNode
=> node.WithCommentsFrom(leadingTokens.GetTrivia(), trailingTokens.GetTrivia());
public static T WithCommentsFrom<T>(
this T node,
IEnumerable<SyntaxTrivia> leadingTrivia,
IEnumerable<SyntaxTrivia> trailingTrivia,
params SyntaxNodeOrToken[] trailingNodesOrTokens)
where T : SyntaxNode
=> node
.WithLeadingTrivia(leadingTrivia.Concat(node.GetLeadingTrivia()).FilterComments(addElasticMarker: false))
.WithTrailingTrivia(
node.GetTrailingTrivia().Concat(SyntaxNodeOrTokenExtensions.GetTrivia(trailingNodesOrTokens).Concat(trailingTrivia)).FilterComments(addElasticMarker: false));
public static T KeepCommentsAndAddElasticMarkers<T>(this T node) where T : SyntaxNode
=> node
.WithTrailingTrivia(node.GetTrailingTrivia().FilterComments(addElasticMarker: true))
.WithLeadingTrivia(node.GetLeadingTrivia().FilterComments(addElasticMarker: true));
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static partial class SyntaxNodeExtensions
{
public static void Deconstruct(this SyntaxNode node, out SyntaxKind kind)
{
kind = node.Kind();
}
public static bool IsKind<TNode>([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind, [NotNullWhen(returnValue: true)] out TNode? result)
where TNode : SyntaxNode
{
if (node.IsKind(kind))
{
result = (TNode)node;
return true;
}
result = null;
return false;
}
public static bool IsParentKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind)
=> CodeAnalysis.CSharpExtensions.IsKind(node?.Parent, kind);
public static bool IsParentKind<TNode>([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind, [NotNullWhen(returnValue: true)] out TNode? result)
where TNode : SyntaxNode
{
if (node.IsParentKind(kind))
{
result = (TNode)node.Parent!;
return true;
}
result = null;
return false;
}
public static bool IsParentKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2)
=> IsKind(node?.Parent, kind1, kind2);
public static bool IsParentKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3)
=> IsKind(node?.Parent, kind1, kind2, kind3);
public static bool IsParentKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4)
=> IsKind(node?.Parent, kind1, kind2, kind3, kind4);
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2;
}
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3;
}
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4;
}
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5;
}
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6;
}
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6, SyntaxKind kind7)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6 || csharpKind == kind7;
}
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6, SyntaxKind kind7, SyntaxKind kind8)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6 || csharpKind == kind7 || csharpKind == kind8;
}
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6, SyntaxKind kind7, SyntaxKind kind8, SyntaxKind kind9, SyntaxKind kind10)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6 || csharpKind == kind7 || csharpKind == kind8 || csharpKind == kind9 || csharpKind == kind10;
}
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6, SyntaxKind kind7, SyntaxKind kind8, SyntaxKind kind9, SyntaxKind kind10, SyntaxKind kind11)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6 || csharpKind == kind7 || csharpKind == kind8 || csharpKind == kind9 || csharpKind == kind10 || csharpKind == kind11;
}
public static IEnumerable<SyntaxTrivia> GetAllPrecedingTriviaToPreviousToken(
this SyntaxNode node, SourceText? sourceText = null,
bool includePreviousTokenTrailingTriviaOnlyIfOnSameLine = false)
=> node.GetFirstToken().GetAllPrecedingTriviaToPreviousToken(
sourceText, includePreviousTokenTrailingTriviaOnlyIfOnSameLine);
/// <summary>
/// Returns all of the trivia to the left of this token up to the previous token (concatenates
/// the previous token's trailing trivia and this token's leading trivia).
/// </summary>
public static IEnumerable<SyntaxTrivia> GetAllPrecedingTriviaToPreviousToken(
this SyntaxToken token, SourceText? sourceText = null,
bool includePreviousTokenTrailingTriviaOnlyIfOnSameLine = false)
{
var prevToken = token.GetPreviousToken(includeSkipped: true);
if (prevToken.Kind() == SyntaxKind.None)
{
return token.LeadingTrivia;
}
Contract.ThrowIfTrue(sourceText == null && includePreviousTokenTrailingTriviaOnlyIfOnSameLine, "If we are including previous token trailing trivia, we need the text too.");
if (includePreviousTokenTrailingTriviaOnlyIfOnSameLine &&
!sourceText!.AreOnSameLine(prevToken, token))
{
return token.LeadingTrivia;
}
return prevToken.TrailingTrivia.Concat(token.LeadingTrivia);
}
public static bool IsAnyArgumentList([NotNullWhen(returnValue: true)] this SyntaxNode? node)
{
return node.IsKind(SyntaxKind.ArgumentList) ||
node.IsKind(SyntaxKind.AttributeArgumentList) ||
node.IsKind(SyntaxKind.BracketedArgumentList) ||
node.IsKind(SyntaxKind.TypeArgumentList);
}
public static (SyntaxToken openBrace, SyntaxToken closeBrace) GetBraces(this SyntaxNode? node)
{
switch (node)
{
case NamespaceDeclarationSyntax namespaceNode:
return (namespaceNode.OpenBraceToken, namespaceNode.CloseBraceToken);
case BaseTypeDeclarationSyntax baseTypeNode:
return (baseTypeNode.OpenBraceToken, baseTypeNode.CloseBraceToken);
case AccessorListSyntax accessorListNode:
return (accessorListNode.OpenBraceToken, accessorListNode.CloseBraceToken);
case BlockSyntax blockNode:
return (blockNode.OpenBraceToken, blockNode.CloseBraceToken);
case SwitchStatementSyntax switchStatementNode:
return (switchStatementNode.OpenBraceToken, switchStatementNode.CloseBraceToken);
case AnonymousObjectCreationExpressionSyntax anonymousObjectCreationExpression:
return (anonymousObjectCreationExpression.OpenBraceToken, anonymousObjectCreationExpression.CloseBraceToken);
case InitializerExpressionSyntax initializeExpressionNode:
return (initializeExpressionNode.OpenBraceToken, initializeExpressionNode.CloseBraceToken);
case SwitchExpressionSyntax switchExpression:
return (switchExpression.OpenBraceToken, switchExpression.CloseBraceToken);
case PropertyPatternClauseSyntax property:
return (property.OpenBraceToken, property.CloseBraceToken);
case WithExpressionSyntax withExpr:
return (withExpr.Initializer.OpenBraceToken, withExpr.Initializer.CloseBraceToken);
case ImplicitObjectCreationExpressionSyntax { Initializer: { } initializer }:
return (initializer.OpenBraceToken, initializer.CloseBraceToken);
}
return default;
}
public static bool IsEmbeddedStatementOwner([NotNullWhen(returnValue: true)] this SyntaxNode? node)
{
return node is DoStatementSyntax ||
node is ElseClauseSyntax ||
node is FixedStatementSyntax ||
node is CommonForEachStatementSyntax ||
node is ForStatementSyntax ||
node is IfStatementSyntax ||
node is LabeledStatementSyntax ||
node is LockStatementSyntax ||
node is UsingStatementSyntax ||
node is WhileStatementSyntax;
}
public static StatementSyntax? GetEmbeddedStatement(this SyntaxNode? node)
=> node switch
{
DoStatementSyntax n => n.Statement,
ElseClauseSyntax n => n.Statement,
FixedStatementSyntax n => n.Statement,
CommonForEachStatementSyntax n => n.Statement,
ForStatementSyntax n => n.Statement,
IfStatementSyntax n => n.Statement,
LabeledStatementSyntax n => n.Statement,
LockStatementSyntax n => n.Statement,
UsingStatementSyntax n => n.Statement,
WhileStatementSyntax n => n.Statement,
_ => null,
};
public static BaseParameterListSyntax? GetParameterList(this SyntaxNode? declaration)
=> declaration?.Kind() switch
{
SyntaxKind.DelegateDeclaration => ((DelegateDeclarationSyntax)declaration).ParameterList,
SyntaxKind.MethodDeclaration => ((MethodDeclarationSyntax)declaration).ParameterList,
SyntaxKind.OperatorDeclaration => ((OperatorDeclarationSyntax)declaration).ParameterList,
SyntaxKind.ConversionOperatorDeclaration => ((ConversionOperatorDeclarationSyntax)declaration).ParameterList,
SyntaxKind.ConstructorDeclaration => ((ConstructorDeclarationSyntax)declaration).ParameterList,
SyntaxKind.DestructorDeclaration => ((DestructorDeclarationSyntax)declaration).ParameterList,
SyntaxKind.IndexerDeclaration => ((IndexerDeclarationSyntax)declaration).ParameterList,
SyntaxKind.ParenthesizedLambdaExpression => ((ParenthesizedLambdaExpressionSyntax)declaration).ParameterList,
SyntaxKind.LocalFunctionStatement => ((LocalFunctionStatementSyntax)declaration).ParameterList,
SyntaxKind.AnonymousMethodExpression => ((AnonymousMethodExpressionSyntax)declaration).ParameterList,
SyntaxKind.RecordDeclaration or SyntaxKind.RecordStructDeclaration => ((RecordDeclarationSyntax)declaration).ParameterList,
_ => null,
};
public static SyntaxList<AttributeListSyntax> GetAttributeLists(this SyntaxNode? declaration)
=> declaration switch
{
MemberDeclarationSyntax memberDecl => memberDecl.AttributeLists,
AccessorDeclarationSyntax accessor => accessor.AttributeLists,
ParameterSyntax parameter => parameter.AttributeLists,
CompilationUnitSyntax compilationUnit => compilationUnit.AttributeLists,
_ => default,
};
public static ConditionalAccessExpressionSyntax? GetParentConditionalAccessExpression(this SyntaxNode? node)
{
// Walk upwards based on the grammar/parser rules around ?. expressions (can be seen in
// LanguageParser.ParseConsequenceSyntax).
// These are the parts of the expression that the ?... expression can end with. Specifically:
//
// 1. x?.y.M() // invocation
// 2. x?.y[...]; // element access
// 3. x?.y.z // member access
// 4. x?.y // member binding
// 5. x?[y] // element binding
var current = node;
if ((current.IsParentKind(SyntaxKind.SimpleMemberAccessExpression, out MemberAccessExpressionSyntax? memberAccess) && memberAccess.Name == current) ||
(current.IsParentKind(SyntaxKind.MemberBindingExpression, out MemberBindingExpressionSyntax? memberBinding) && memberBinding.Name == current))
{
current = current.Parent;
}
// Effectively, if we're on the RHS of the ? we have to walk up the RHS spine first until we hit the first
// conditional access.
while (current.IsKind(
SyntaxKind.InvocationExpression,
SyntaxKind.ElementAccessExpression,
SyntaxKind.SimpleMemberAccessExpression,
SyntaxKind.MemberBindingExpression,
SyntaxKind.ElementBindingExpression) &&
current.Parent is not ConditionalAccessExpressionSyntax)
{
current = current.Parent;
}
// Two cases we have to care about:
//
// 1. a?.b.$$c.d and
// 2. a?.b.$$c.d?.e...
//
// Note that `a?.b.$$c.d?.e.f?.g.h.i` falls into the same bucket as two. i.e. the parts after `.e` are
// lower in the tree and are not seen as we walk upwards.
//
//
// To get the root ?. (the one after the `a`) we have to potentially consume the first ?. on the RHS of the
// right spine (i.e. the one after `d`). Once we do this, we then see if that itself is on the RHS of a
// another conditional, and if so we hten return the one on the left. i.e. for '2' this goes in this direction:
//
// a?.b.$$c.d?.e // it will do:
// ----->
// <---------
//
// Note that this only one CAE consumption on both sides. GetRootConditionalAccessExpression can be used to
// get the root parent in a case like:
//
// x?.y?.z?.a?.b.$$c.d?.e.f?.g.h.i // it will do:
// ----->
// <---------
// <---
// <---
// <---
if (current.IsParentKind(SyntaxKind.ConditionalAccessExpression, out ConditionalAccessExpressionSyntax? conditional) &&
conditional.Expression == current)
{
current = conditional;
}
if (current.IsParentKind(SyntaxKind.ConditionalAccessExpression, out conditional) &&
conditional.WhenNotNull == current)
{
current = conditional;
}
return current as ConditionalAccessExpressionSyntax;
}
/// <summary>
/// <inheritdoc cref="ISyntaxFacts.GetRootConditionalAccessExpression(SyntaxNode)"/>
/// </summary>>
public static ConditionalAccessExpressionSyntax? GetRootConditionalAccessExpression(this SyntaxNode? node)
{
// Once we've walked up the entire RHS, now we continually walk up the conditional accesses until we're at
// the root. For example, if we have `a?.b` and we're on the `.b`, this will give `a?.b`. Similarly with
// `a?.b?.c` if we're on either `.b` or `.c` this will result in `a?.b?.c` (i.e. the root of this CAE
// sequence).
var current = node.GetParentConditionalAccessExpression();
while (current.IsParentKind(SyntaxKind.ConditionalAccessExpression, out ConditionalAccessExpressionSyntax? conditional) &&
conditional.WhenNotNull == current)
{
current = conditional;
}
return current;
}
public static ConditionalAccessExpressionSyntax? GetInnerMostConditionalAccessExpression(this SyntaxNode node)
{
if (!(node is ConditionalAccessExpressionSyntax))
{
return null;
}
var result = (ConditionalAccessExpressionSyntax)node;
while (result.WhenNotNull is ConditionalAccessExpressionSyntax)
{
result = (ConditionalAccessExpressionSyntax)result.WhenNotNull;
}
return result;
}
public static bool IsAsyncSupportingFunctionSyntax([NotNullWhen(returnValue: true)] this SyntaxNode? node)
{
return node.IsKind(SyntaxKind.MethodDeclaration)
|| node.IsAnyLambdaOrAnonymousMethod()
|| node.IsKind(SyntaxKind.LocalFunctionStatement);
}
public static bool IsAnyLambda([NotNullWhen(returnValue: true)] this SyntaxNode? node)
{
return
node.IsKind(SyntaxKind.ParenthesizedLambdaExpression) ||
node.IsKind(SyntaxKind.SimpleLambdaExpression);
}
public static bool IsAnyLambdaOrAnonymousMethod([NotNullWhen(returnValue: true)] this SyntaxNode? node)
=> node.IsAnyLambda() || node.IsKind(SyntaxKind.AnonymousMethodExpression);
public static bool IsAnyAssignExpression(this SyntaxNode node)
=> SyntaxFacts.IsAssignmentExpression(node.Kind());
public static bool IsCompoundAssignExpression(this SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.CoalesceAssignmentExpression:
case SyntaxKind.AddAssignmentExpression:
case SyntaxKind.SubtractAssignmentExpression:
case SyntaxKind.MultiplyAssignmentExpression:
case SyntaxKind.DivideAssignmentExpression:
case SyntaxKind.ModuloAssignmentExpression:
case SyntaxKind.AndAssignmentExpression:
case SyntaxKind.ExclusiveOrAssignmentExpression:
case SyntaxKind.OrAssignmentExpression:
case SyntaxKind.LeftShiftAssignmentExpression:
case SyntaxKind.RightShiftAssignmentExpression:
return true;
}
return false;
}
public static bool IsLeftSideOfAssignExpression([NotNullWhen(returnValue: true)] this SyntaxNode? node)
=> node.IsParentKind(SyntaxKind.SimpleAssignmentExpression, out AssignmentExpressionSyntax? assignment) &&
assignment.Left == node;
public static bool IsLeftSideOfAnyAssignExpression([NotNullWhen(true)] this SyntaxNode? node)
{
return node?.Parent != null &&
node.Parent.IsAnyAssignExpression() &&
((AssignmentExpressionSyntax)node.Parent).Left == node;
}
public static bool IsRightSideOfAnyAssignExpression([NotNullWhen(true)] this SyntaxNode? node)
{
return node?.Parent != null &&
node.Parent.IsAnyAssignExpression() &&
((AssignmentExpressionSyntax)node.Parent).Right == node;
}
public static bool IsLeftSideOfCompoundAssignExpression([NotNullWhen(true)] this SyntaxNode? node)
{
return node?.Parent != null &&
node.Parent.IsCompoundAssignExpression() &&
((AssignmentExpressionSyntax)node.Parent).Left == node;
}
/// <summary>
/// Returns the list of using directives that affect <paramref name="node"/>. The list will be returned in
/// top down order.
/// </summary>
public static IEnumerable<UsingDirectiveSyntax> GetEnclosingUsingDirectives(this SyntaxNode node)
{
return node.GetAncestorOrThis<CompilationUnitSyntax>()!.Usings
.Concat(node.GetAncestorsOrThis<BaseNamespaceDeclarationSyntax>()
.Reverse()
.SelectMany(n => n.Usings));
}
public static IEnumerable<ExternAliasDirectiveSyntax> GetEnclosingExternAliasDirectives(this SyntaxNode node)
{
return node.GetAncestorOrThis<CompilationUnitSyntax>()!.Externs
.Concat(node.GetAncestorsOrThis<BaseNamespaceDeclarationSyntax>()
.Reverse()
.SelectMany(n => n.Externs));
}
public static bool IsUnsafeContext(this SyntaxNode node)
{
if (node.GetAncestor<UnsafeStatementSyntax>() != null)
{
return true;
}
return node.GetAncestors<MemberDeclarationSyntax>().Any(
m => m.GetModifiers().Any(SyntaxKind.UnsafeKeyword));
}
public static bool IsInStaticContext(this SyntaxNode node)
{
// this/base calls are always static.
if (node.FirstAncestorOrSelf<ConstructorInitializerSyntax>() != null)
{
return true;
}
var memberDeclaration = node.FirstAncestorOrSelf<MemberDeclarationSyntax>();
if (memberDeclaration == null)
{
return false;
}
switch (memberDeclaration.Kind())
{
case SyntaxKind.MethodDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.EventDeclaration:
case SyntaxKind.IndexerDeclaration:
return memberDeclaration.GetModifiers().Any(SyntaxKind.StaticKeyword);
case SyntaxKind.PropertyDeclaration:
return memberDeclaration.GetModifiers().Any(SyntaxKind.StaticKeyword) ||
node.IsFoundUnder((PropertyDeclarationSyntax p) => p.Initializer);
case SyntaxKind.FieldDeclaration:
case SyntaxKind.EventFieldDeclaration:
// Inside a field one can only access static members of a type (unless it's top-level).
return !memberDeclaration.Parent.IsKind(SyntaxKind.CompilationUnit);
case SyntaxKind.DestructorDeclaration:
return false;
}
// Global statements are not a static context.
if (node.FirstAncestorOrSelf<GlobalStatementSyntax>() != null)
{
return false;
}
// any other location is considered static
return true;
}
public static BaseNamespaceDeclarationSyntax? GetInnermostNamespaceDeclarationWithUsings(this SyntaxNode contextNode)
{
var usingDirectiveAncestor = contextNode.GetAncestor<UsingDirectiveSyntax>();
if (usingDirectiveAncestor == null)
{
return contextNode.GetAncestorsOrThis<BaseNamespaceDeclarationSyntax>().FirstOrDefault(n => n.Usings.Count > 0);
}
else
{
// We are inside a using directive. In this case, we should find and return the first 'parent' namespace with usings.
var containingNamespace = usingDirectiveAncestor.GetAncestor<BaseNamespaceDeclarationSyntax>();
if (containingNamespace == null)
{
// We are inside a top level using directive (i.e. one that's directly in the compilation unit).
return null;
}
else
{
return containingNamespace.GetAncestors<BaseNamespaceDeclarationSyntax>().FirstOrDefault(n => n.Usings.Count > 0);
}
}
}
public static bool IsBreakableConstruct(this SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.DoStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.SwitchStatement:
case SyntaxKind.ForStatement:
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
return true;
}
return false;
}
public static bool IsContinuableConstruct(this SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.DoStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.ForStatement:
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
return true;
}
return false;
}
public static bool IsReturnableConstruct(this SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.AnonymousMethodExpression:
case SyntaxKind.SimpleLambdaExpression:
case SyntaxKind.ParenthesizedLambdaExpression:
case SyntaxKind.LocalFunctionStatement:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.InitAccessorDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
return true;
}
return false;
}
public static bool SpansPreprocessorDirective<TSyntaxNode>(this IEnumerable<TSyntaxNode> list) where TSyntaxNode : SyntaxNode
=> CSharpSyntaxFacts.Instance.SpansPreprocessorDirective(list);
[return: NotNullIfNotNull("node")]
public static TNode? ConvertToSingleLine<TNode>(this TNode? node, bool useElasticTrivia = false)
where TNode : SyntaxNode
{
if (node == null)
{
return node;
}
var rewriter = new SingleLineRewriter(useElasticTrivia);
return (TNode)rewriter.Visit(node);
}
/// <summary>
/// Returns true if the passed in node contains an interleaved pp directive.
///
/// i.e. The following returns false:
///
/// void Goo() {
/// #if true
/// #endif
/// }
///
/// #if true
/// void Goo() {
/// }
/// #endif
///
/// but these return true:
///
/// #if true
/// void Goo() {
/// #endif
/// }
///
/// void Goo() {
/// #if true
/// }
/// #endif
///
/// #if true
/// void Goo() {
/// #else
/// }
/// #endif
///
/// i.e. the method returns true if it contains a PP directive that belongs to a grouping
/// constructs (like #if/#endif or #region/#endregion), but the grouping construct isn't
/// entirely contained within the span of the node.
/// </summary>
public static bool ContainsInterleavedDirective(this SyntaxNode syntaxNode, CancellationToken cancellationToken)
=> CSharpSyntaxFacts.Instance.ContainsInterleavedDirective(syntaxNode, cancellationToken);
/// <summary>
/// Similar to <see cref="ContainsInterleavedDirective(SyntaxNode, CancellationToken)"/> except that the span to check
/// for interleaved directives can be specified separately to the node passed in.
/// </summary>
public static bool ContainsInterleavedDirective(this SyntaxNode syntaxNode, TextSpan span, CancellationToken cancellationToken)
=> CSharpSyntaxFacts.Instance.ContainsInterleavedDirective(span, syntaxNode, cancellationToken);
public static bool ContainsInterleavedDirective(
this SyntaxToken token,
TextSpan textSpan,
CancellationToken cancellationToken)
{
return
ContainsInterleavedDirective(textSpan, token.LeadingTrivia, cancellationToken) ||
ContainsInterleavedDirective(textSpan, token.TrailingTrivia, cancellationToken);
}
private static bool ContainsInterleavedDirective(
TextSpan textSpan,
SyntaxTriviaList list,
CancellationToken cancellationToken)
{
foreach (var trivia in list)
{
if (textSpan.Contains(trivia.Span))
{
if (ContainsInterleavedDirective(textSpan, trivia, cancellationToken))
{
return true;
}
}
}
return false;
}
private static bool ContainsInterleavedDirective(
TextSpan textSpan,
SyntaxTrivia trivia,
CancellationToken cancellationToken)
{
if (trivia.HasStructure)
{
var structure = trivia.GetStructure()!;
if (trivia.GetStructure().IsKind(SyntaxKind.RegionDirectiveTrivia,
SyntaxKind.EndRegionDirectiveTrivia,
SyntaxKind.IfDirectiveTrivia,
SyntaxKind.EndIfDirectiveTrivia))
{
var match = ((DirectiveTriviaSyntax)structure).GetMatchingDirective(cancellationToken);
if (match != null)
{
var matchSpan = match.Span;
if (!textSpan.Contains(matchSpan.Start))
{
// The match for this pp directive is outside
// this node.
return true;
}
}
}
else if (trivia.GetStructure().IsKind(SyntaxKind.ElseDirectiveTrivia, SyntaxKind.ElifDirectiveTrivia))
{
var directives = ((DirectiveTriviaSyntax)structure).GetMatchingConditionalDirectives(cancellationToken);
if (directives != null && directives.Count > 0)
{
if (!textSpan.Contains(directives[0].SpanStart) ||
!textSpan.Contains(directives[directives.Count - 1].SpanStart))
{
// This else/elif belongs to a pp span that isn't
// entirely within this node.
return true;
}
}
}
}
return false;
}
/// <summary>
/// Breaks up the list of provided nodes, based on how they are interspersed with pp
/// directives, into groups. Within these groups nodes can be moved around safely, without
/// breaking any pp constructs.
/// </summary>
public static IList<IList<TSyntaxNode>> SplitNodesOnPreprocessorBoundaries<TSyntaxNode>(
this IEnumerable<TSyntaxNode> nodes,
CancellationToken cancellationToken)
where TSyntaxNode : SyntaxNode
{
var result = new List<IList<TSyntaxNode>>();
var currentGroup = new List<TSyntaxNode>();
foreach (var node in nodes)
{
var hasUnmatchedInteriorDirective = node.ContainsInterleavedDirective(cancellationToken);
var hasLeadingDirective = node.GetLeadingTrivia().Any(t => SyntaxFacts.IsPreprocessorDirective(t.Kind()));
if (hasUnmatchedInteriorDirective)
{
// we have a #if/#endif/#region/#endregion/#else/#elif in
// this node that belongs to a span of pp directives that
// is not entirely contained within the node. i.e.:
//
// void Goo() {
// #if ...
// }
//
// This node cannot be moved at all. It is in a group that
// only contains itself (and thus can never be moved).
// add whatever group we've built up to now. And reset the
// next group to empty.
result.Add(currentGroup);
currentGroup = new List<TSyntaxNode>();
result.Add(new List<TSyntaxNode> { node });
}
else if (hasLeadingDirective)
{
// We have a PP directive before us. i.e.:
//
// #if ...
// void Goo() {
//
// That means we start a new group that is contained between
// the above directive and the following directive.
// add whatever group we've built up to now. And reset the
// next group to empty.
result.Add(currentGroup);
currentGroup = new List<TSyntaxNode>();
currentGroup.Add(node);
}
else
{
// simple case. just add ourselves to the current group
currentGroup.Add(node);
}
}
// add the remainder of the final group.
result.Add(currentGroup);
// Now, filter out any empty groups.
result = result.Where(group => !group.IsEmpty()).ToList();
return result;
}
public static ImmutableArray<SyntaxTrivia> GetLeadingBlankLines<TSyntaxNode>(this TSyntaxNode node) where TSyntaxNode : SyntaxNode
=> CSharpSyntaxFacts.Instance.GetLeadingBlankLines(node);
public static TSyntaxNode GetNodeWithoutLeadingBlankLines<TSyntaxNode>(this TSyntaxNode node) where TSyntaxNode : SyntaxNode
=> CSharpSyntaxFacts.Instance.GetNodeWithoutLeadingBlankLines(node);
public static TSyntaxNode GetNodeWithoutLeadingBlankLines<TSyntaxNode>(this TSyntaxNode node, out ImmutableArray<SyntaxTrivia> strippedTrivia) where TSyntaxNode : SyntaxNode
=> CSharpSyntaxFacts.Instance.GetNodeWithoutLeadingBlankLines(node, out strippedTrivia);
public static ImmutableArray<SyntaxTrivia> GetLeadingBannerAndPreprocessorDirectives<TSyntaxNode>(this TSyntaxNode node) where TSyntaxNode : SyntaxNode
=> CSharpSyntaxFacts.Instance.GetLeadingBannerAndPreprocessorDirectives(node);
public static TSyntaxNode GetNodeWithoutLeadingBannerAndPreprocessorDirectives<TSyntaxNode>(this TSyntaxNode node) where TSyntaxNode : SyntaxNode
=> CSharpSyntaxFacts.Instance.GetNodeWithoutLeadingBannerAndPreprocessorDirectives(node);
public static TSyntaxNode GetNodeWithoutLeadingBannerAndPreprocessorDirectives<TSyntaxNode>(this TSyntaxNode node, out ImmutableArray<SyntaxTrivia> strippedTrivia) where TSyntaxNode : SyntaxNode
=> CSharpSyntaxFacts.Instance.GetNodeWithoutLeadingBannerAndPreprocessorDirectives(node, out strippedTrivia);
public static bool IsVariableDeclaratorValue(this SyntaxNode node)
=> node.IsParentKind(SyntaxKind.EqualsValueClause, out EqualsValueClauseSyntax? equalsValue) &&
equalsValue.IsParentKind(SyntaxKind.VariableDeclarator) &&
equalsValue.Value == node;
public static BlockSyntax? FindInnermostCommonBlock(this IEnumerable<SyntaxNode> nodes)
=> nodes.FindInnermostCommonNode<BlockSyntax>();
public static IEnumerable<SyntaxNode> GetAncestorsOrThis(this SyntaxNode? node, Func<SyntaxNode, bool> predicate)
{
var current = node;
while (current != null)
{
if (predicate(current))
{
yield return current;
}
current = current.Parent;
}
}
/// <summary>
/// Returns child node or token that contains given position.
/// </summary>
/// <remarks>
/// This is a copy of <see cref="SyntaxNode.ChildThatContainsPosition"/> that also returns the index of the child node.
/// </remarks>
internal static SyntaxNodeOrToken ChildThatContainsPosition(this SyntaxNode self, int position, out int childIndex)
{
var childList = self.ChildNodesAndTokens();
var left = 0;
var right = childList.Count - 1;
while (left <= right)
{
var middle = left + ((right - left) / 2);
var node = childList[middle];
var span = node.FullSpan;
if (position < span.Start)
{
right = middle - 1;
}
else if (position >= span.End)
{
left = middle + 1;
}
else
{
childIndex = middle;
return node;
}
}
// we could check up front that index is within FullSpan,
// but we wan to optimize for the common case where position is valid.
Debug.Assert(!self.FullSpan.Contains(position), "Position is valid. How could we not find a child?");
throw new ArgumentOutOfRangeException(nameof(position));
}
public static (SyntaxToken openParen, SyntaxToken closeParen) GetParentheses(this SyntaxNode node)
{
switch (node)
{
case ParenthesizedExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case MakeRefExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case RefTypeExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case RefValueExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case CheckedExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case DefaultExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case TypeOfExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case SizeOfExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case ArgumentListSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case CastExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case WhileStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case DoStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case ForStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case CommonForEachStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case UsingStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case FixedStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case LockStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case IfStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case SwitchStatementSyntax n when n.OpenParenToken != default: return (n.OpenParenToken, n.CloseParenToken);
case TupleExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case CatchDeclarationSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case AttributeArgumentListSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case ConstructorConstraintSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case ParameterListSyntax n: return (n.OpenParenToken, n.CloseParenToken);
default: return default;
}
}
public static (SyntaxToken openBracket, SyntaxToken closeBracket) GetBrackets(this SyntaxNode node)
{
switch (node)
{
case ArrayRankSpecifierSyntax n: return (n.OpenBracketToken, n.CloseBracketToken);
case BracketedArgumentListSyntax n: return (n.OpenBracketToken, n.CloseBracketToken);
case ImplicitArrayCreationExpressionSyntax n: return (n.OpenBracketToken, n.CloseBracketToken);
case AttributeListSyntax n: return (n.OpenBracketToken, n.CloseBracketToken);
case BracketedParameterListSyntax n: return (n.OpenBracketToken, n.CloseBracketToken);
default: return default;
}
}
public static SyntaxTokenList GetModifiers(this SyntaxNode? member)
{
switch (member)
{
case MemberDeclarationSyntax memberDecl: return memberDecl.Modifiers;
case AccessorDeclarationSyntax accessor: return accessor.Modifiers;
case AnonymousFunctionExpressionSyntax anonymous: return anonymous.Modifiers;
case LocalFunctionStatementSyntax localFunction: return localFunction.Modifiers;
case LocalDeclarationStatementSyntax localDeclaration: return localDeclaration.Modifiers;
}
return default;
}
public static SyntaxNode? WithModifiers(this SyntaxNode? member, SyntaxTokenList modifiers)
{
switch (member)
{
case MemberDeclarationSyntax memberDecl: return memberDecl.WithModifiers(modifiers);
case AccessorDeclarationSyntax accessor: return accessor.WithModifiers(modifiers);
case AnonymousFunctionExpressionSyntax anonymous: return anonymous.WithModifiers(modifiers);
case LocalFunctionStatementSyntax localFunction: return localFunction.WithModifiers(modifiers);
case LocalDeclarationStatementSyntax localDeclaration: return localDeclaration.WithModifiers(modifiers);
}
return null;
}
public static bool CheckTopLevel(this SyntaxNode node, TextSpan span)
{
switch (node)
{
case BlockSyntax block:
return block.ContainsInBlockBody(span);
case ArrowExpressionClauseSyntax expressionBodiedMember:
return expressionBodiedMember.ContainsInExpressionBodiedMemberBody(span);
case FieldDeclarationSyntax field:
{
foreach (var variable in field.Declaration.Variables)
{
if (variable.Initializer != null && variable.Initializer.Span.Contains(span))
{
return true;
}
}
break;
}
case GlobalStatementSyntax _:
return true;
case ConstructorInitializerSyntax constructorInitializer:
return constructorInitializer.ContainsInArgument(span);
}
return false;
}
public static bool ContainsInArgument(this ConstructorInitializerSyntax initializer, TextSpan textSpan)
{
if (initializer == null)
{
return false;
}
return initializer.ArgumentList.Arguments.Any(a => a.Span.Contains(textSpan));
}
public static bool ContainsInBlockBody(this BlockSyntax block, TextSpan textSpan)
{
if (block == null)
{
return false;
}
var blockSpan = TextSpan.FromBounds(block.OpenBraceToken.Span.End, block.CloseBraceToken.SpanStart);
return blockSpan.Contains(textSpan);
}
public static bool ContainsInExpressionBodiedMemberBody(this ArrowExpressionClauseSyntax expressionBodiedMember, TextSpan textSpan)
{
if (expressionBodiedMember == null)
{
return false;
}
var expressionBodiedMemberBody = TextSpan.FromBounds(expressionBodiedMember.Expression.SpanStart, expressionBodiedMember.Expression.Span.End);
return expressionBodiedMemberBody.Contains(textSpan);
}
public static IEnumerable<MemberDeclarationSyntax> GetMembers(this SyntaxNode? node)
{
switch (node)
{
case CompilationUnitSyntax compilation:
return compilation.Members;
case BaseNamespaceDeclarationSyntax @namespace:
return @namespace.Members;
case TypeDeclarationSyntax type:
return type.Members;
case EnumDeclarationSyntax @enum:
return @enum.Members;
}
return SpecializedCollections.EmptyEnumerable<MemberDeclarationSyntax>();
}
public static bool IsInExpressionTree(
[NotNullWhen(returnValue: true)] this SyntaxNode? node,
SemanticModel semanticModel,
[NotNullWhen(returnValue: true)] INamedTypeSymbol? expressionTypeOpt,
CancellationToken cancellationToken)
{
if (expressionTypeOpt != null)
{
for (var current = node; current != null; current = current.Parent)
{
if (current.IsAnyLambda())
{
var typeInfo = semanticModel.GetTypeInfo(current, cancellationToken);
if (expressionTypeOpt.Equals(typeInfo.ConvertedType?.OriginalDefinition))
return true;
}
else if (current is SelectOrGroupClauseSyntax ||
current is OrderingSyntax)
{
var info = semanticModel.GetSymbolInfo(current, cancellationToken);
if (TakesExpressionTree(info, expressionTypeOpt))
return true;
}
else if (current is QueryClauseSyntax queryClause)
{
var info = semanticModel.GetQueryClauseInfo(queryClause, cancellationToken);
if (TakesExpressionTree(info.CastInfo, expressionTypeOpt) ||
TakesExpressionTree(info.OperationInfo, expressionTypeOpt))
{
return true;
}
}
}
}
return false;
static bool TakesExpressionTree(SymbolInfo info, INamedTypeSymbol expressionType)
{
foreach (var symbol in info.GetAllSymbols())
{
if (symbol is IMethodSymbol method &&
method.Parameters.Length > 0 &&
expressionType.Equals(method.Parameters[0].Type?.OriginalDefinition))
{
return true;
}
}
return false;
}
}
public static bool IsInDeconstructionLeft(
[NotNullWhen(returnValue: true)] this SyntaxNode? node,
[NotNullWhen(returnValue: true)] out SyntaxNode? deconstructionLeft)
{
SyntaxNode? previous = null;
for (var current = node; current != null; current = current.Parent)
{
if ((current is AssignmentExpressionSyntax assignment && previous == assignment.Left && assignment.IsDeconstruction()) ||
(current is ForEachVariableStatementSyntax @foreach && previous == @foreach.Variable))
{
deconstructionLeft = previous;
return true;
}
if (current is StatementSyntax)
{
break;
}
previous = current;
}
deconstructionLeft = null;
return false;
}
public static bool IsTopLevelOfUsingAliasDirective(this SyntaxToken node)
=> node switch
{
{ Parent: NameEqualsSyntax { Parent: UsingDirectiveSyntax _ } } => true,
{ Parent: IdentifierNameSyntax { Parent: UsingDirectiveSyntax _ } } => true,
_ => false
};
public static T WithCommentsFrom<T>(this T node, SyntaxToken leadingToken, SyntaxToken trailingToken)
where T : SyntaxNode
=> node.WithCommentsFrom(
SyntaxNodeOrTokenExtensions.GetTrivia(leadingToken),
SyntaxNodeOrTokenExtensions.GetTrivia(trailingToken));
public static T WithCommentsFrom<T>(
this T node,
IEnumerable<SyntaxToken> leadingTokens,
IEnumerable<SyntaxToken> trailingTokens)
where T : SyntaxNode
=> node.WithCommentsFrom(leadingTokens.GetTrivia(), trailingTokens.GetTrivia());
public static T WithCommentsFrom<T>(
this T node,
IEnumerable<SyntaxTrivia> leadingTrivia,
IEnumerable<SyntaxTrivia> trailingTrivia,
params SyntaxNodeOrToken[] trailingNodesOrTokens)
where T : SyntaxNode
=> node
.WithLeadingTrivia(leadingTrivia.Concat(node.GetLeadingTrivia()).FilterComments(addElasticMarker: false))
.WithTrailingTrivia(
node.GetTrailingTrivia().Concat(SyntaxNodeOrTokenExtensions.GetTrivia(trailingNodesOrTokens).Concat(trailingTrivia)).FilterComments(addElasticMarker: false));
public static T KeepCommentsAndAddElasticMarkers<T>(this T node) where T : SyntaxNode
=> node
.WithTrailingTrivia(node.GetTrailingTrivia().FilterComments(addElasticMarker: true))
.WithLeadingTrivia(node.GetLeadingTrivia().FilterComments(addElasticMarker: true));
}
}
| 1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/CompilationUnitSyntaxExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.AddImports;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static class CompilationUnitSyntaxExtensions
{
public static bool CanAddUsingDirectives(this SyntaxNode contextNode, Document document, CancellationToken cancellationToken)
=> CanAddUsingDirectives(contextNode, document.CanAddImportsInHiddenRegions(), cancellationToken);
public static bool CanAddUsingDirectives(this SyntaxNode contextNode, bool allowInHiddenRegions, CancellationToken cancellationToken)
{
var usingDirectiveAncestor = contextNode.GetAncestor<UsingDirectiveSyntax>();
if (usingDirectiveAncestor?.Parent is CompilationUnitSyntax)
{
// We are inside a top level using directive (i.e. one that's directly in the compilation unit).
return false;
}
if (!allowInHiddenRegions && contextNode.SyntaxTree.HasHiddenRegions())
{
var namespaceDeclaration = contextNode.GetInnermostNamespaceDeclarationWithUsings();
var root = (CompilationUnitSyntax)contextNode.SyntaxTree.GetRoot(cancellationToken);
var span = GetUsingsSpan(root, namespaceDeclaration);
if (contextNode.SyntaxTree.OverlapsHiddenPosition(span, cancellationToken))
{
return false;
}
}
if (cancellationToken.IsCancellationRequested)
{
return false;
}
return true;
}
private static TextSpan GetUsingsSpan(CompilationUnitSyntax root, BaseNamespaceDeclarationSyntax? namespaceDeclaration)
{
if (namespaceDeclaration != null)
{
var usings = namespaceDeclaration.Usings;
var start = usings.First().SpanStart;
var end = usings.Last().Span.End;
return TextSpan.FromBounds(start, end);
}
else
{
var rootUsings = root.Usings;
if (rootUsings.Any())
{
var start = rootUsings.First().SpanStart;
var end = rootUsings.Last().Span.End;
return TextSpan.FromBounds(start, end);
}
else
{
var start = 0;
var end = root.Members.Any()
? root.Members.First().GetFirstToken().Span.End
: root.Span.End;
return TextSpan.FromBounds(start, end);
}
}
}
public static CompilationUnitSyntax AddUsingDirective(
this CompilationUnitSyntax root,
UsingDirectiveSyntax usingDirective,
SyntaxNode contextNode,
bool placeSystemNamespaceFirst,
params SyntaxAnnotation[] annotations)
{
return root.AddUsingDirectives(new[] { usingDirective }, contextNode, placeSystemNamespaceFirst, annotations);
}
public static CompilationUnitSyntax AddUsingDirectives(
this CompilationUnitSyntax root,
IList<UsingDirectiveSyntax> usingDirectives,
SyntaxNode contextNode,
bool placeSystemNamespaceFirst,
params SyntaxAnnotation[] annotations)
{
if (!usingDirectives.Any())
{
return root;
}
var firstOuterNamespaceWithUsings = contextNode.GetInnermostNamespaceDeclarationWithUsings();
if (firstOuterNamespaceWithUsings == null)
{
return root.AddUsingDirectives(usingDirectives, placeSystemNamespaceFirst, annotations);
}
else
{
var newNamespace = firstOuterNamespaceWithUsings.AddUsingDirectives(usingDirectives, placeSystemNamespaceFirst, annotations);
return root.ReplaceNode(firstOuterNamespaceWithUsings, newNamespace);
}
}
public static CompilationUnitSyntax AddUsingDirectives(
this CompilationUnitSyntax root,
IList<UsingDirectiveSyntax> usingDirectives,
bool placeSystemNamespaceFirst,
params SyntaxAnnotation[] annotations)
{
if (usingDirectives.Count == 0)
{
return root;
}
var usings = AddUsingDirectives(root, usingDirectives);
// Keep usings sorted if they were originally sorted.
usings.SortUsingDirectives(root.Usings, placeSystemNamespaceFirst);
if (root.Externs.Count == 0)
{
root = AddImportHelpers.MoveTrivia(
CSharpSyntaxFacts.Instance, root, root.Usings, usings);
}
return root.WithUsings(
usings.Select(u => u.WithAdditionalAnnotations(annotations)).ToSyntaxList());
}
private static List<UsingDirectiveSyntax> AddUsingDirectives(
CompilationUnitSyntax root, IList<UsingDirectiveSyntax> usingDirectives)
{
// We need to try and not place the using inside of a directive if possible.
var usings = new List<UsingDirectiveSyntax>();
var endOfList = root.Usings.Count - 1;
var startOfLastDirective = -1;
var endOfLastDirective = -1;
for (var i = 0; i < root.Usings.Count; i++)
{
if (root.Usings[i].GetLeadingTrivia().Any(trivia => trivia.IsKind(SyntaxKind.IfDirectiveTrivia)))
{
startOfLastDirective = i;
}
if (root.Usings[i].GetLeadingTrivia().Any(trivia => trivia.IsKind(SyntaxKind.EndIfDirectiveTrivia)))
{
endOfLastDirective = i;
}
}
// if the entire using is in a directive or there is a using list at the end outside of the directive add the using at the end,
// else place it before the last directive.
usings.AddRange(root.Usings);
if ((startOfLastDirective == 0 && (endOfLastDirective == endOfList || endOfLastDirective == -1)) ||
(startOfLastDirective == -1 && endOfLastDirective == -1) ||
(endOfLastDirective != endOfList && endOfLastDirective != -1))
{
usings.AddRange(usingDirectives);
}
else
{
usings.InsertRange(startOfLastDirective, usingDirectives);
}
return usings;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.AddImports;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static class CompilationUnitSyntaxExtensions
{
public static bool CanAddUsingDirectives(this SyntaxNode contextNode, Document document, CancellationToken cancellationToken)
=> CanAddUsingDirectives(contextNode, document.CanAddImportsInHiddenRegions(), cancellationToken);
public static bool CanAddUsingDirectives(this SyntaxNode contextNode, bool allowInHiddenRegions, CancellationToken cancellationToken)
{
var usingDirectiveAncestor = contextNode.GetAncestor<UsingDirectiveSyntax>();
if (usingDirectiveAncestor?.Parent is CompilationUnitSyntax)
{
// We are inside a top level using directive (i.e. one that's directly in the compilation unit).
return false;
}
if (!allowInHiddenRegions && contextNode.SyntaxTree.HasHiddenRegions())
{
var namespaceDeclaration = contextNode.GetInnermostNamespaceDeclarationWithUsings();
var root = (CompilationUnitSyntax)contextNode.SyntaxTree.GetRoot(cancellationToken);
var span = GetUsingsSpan(root, namespaceDeclaration);
if (contextNode.SyntaxTree.OverlapsHiddenPosition(span, cancellationToken))
{
return false;
}
}
if (cancellationToken.IsCancellationRequested)
{
return false;
}
return true;
}
private static TextSpan GetUsingsSpan(CompilationUnitSyntax root, BaseNamespaceDeclarationSyntax? namespaceDeclaration)
{
if (namespaceDeclaration != null)
{
var usings = namespaceDeclaration.Usings;
var start = usings.First().SpanStart;
var end = usings.Last().Span.End;
return TextSpan.FromBounds(start, end);
}
else
{
var rootUsings = root.Usings;
if (rootUsings.Any())
{
var start = rootUsings.First().SpanStart;
var end = rootUsings.Last().Span.End;
return TextSpan.FromBounds(start, end);
}
else
{
var start = 0;
var end = root.Members.Any()
? root.Members.First().GetFirstToken().Span.End
: root.Span.End;
return TextSpan.FromBounds(start, end);
}
}
}
public static CompilationUnitSyntax AddUsingDirective(
this CompilationUnitSyntax root,
UsingDirectiveSyntax usingDirective,
SyntaxNode contextNode,
bool placeSystemNamespaceFirst,
params SyntaxAnnotation[] annotations)
{
return root.AddUsingDirectives(new[] { usingDirective }, contextNode, placeSystemNamespaceFirst, annotations);
}
public static CompilationUnitSyntax AddUsingDirectives(
this CompilationUnitSyntax root,
IList<UsingDirectiveSyntax> usingDirectives,
SyntaxNode contextNode,
bool placeSystemNamespaceFirst,
params SyntaxAnnotation[] annotations)
{
if (!usingDirectives.Any())
{
return root;
}
var firstOuterNamespaceWithUsings = contextNode.GetInnermostNamespaceDeclarationWithUsings();
if (firstOuterNamespaceWithUsings == null)
{
return root.AddUsingDirectives(usingDirectives, placeSystemNamespaceFirst, annotations);
}
else
{
var newNamespace = firstOuterNamespaceWithUsings.AddUsingDirectives(usingDirectives, placeSystemNamespaceFirst, annotations);
return root.ReplaceNode(firstOuterNamespaceWithUsings, newNamespace);
}
}
public static CompilationUnitSyntax AddUsingDirectives(
this CompilationUnitSyntax root,
IList<UsingDirectiveSyntax> usingDirectives,
bool placeSystemNamespaceFirst,
params SyntaxAnnotation[] annotations)
{
if (usingDirectives.Count == 0)
{
return root;
}
var usings = AddUsingDirectives(root, usingDirectives);
// Keep usings sorted if they were originally sorted.
usings.SortUsingDirectives(root.Usings, placeSystemNamespaceFirst);
if (root.Externs.Count == 0)
{
root = AddImportHelpers.MoveTrivia(
CSharpSyntaxFacts.Instance, root, root.Usings, usings);
}
return root.WithUsings(
usings.Select(u => u.WithAdditionalAnnotations(annotations)).ToSyntaxList());
}
private static List<UsingDirectiveSyntax> AddUsingDirectives(
CompilationUnitSyntax root, IList<UsingDirectiveSyntax> usingDirectives)
{
// We need to try and not place the using inside of a directive if possible.
var usings = new List<UsingDirectiveSyntax>();
var endOfList = root.Usings.Count - 1;
var startOfLastDirective = -1;
var endOfLastDirective = -1;
for (var i = 0; i < root.Usings.Count; i++)
{
if (root.Usings[i].GetLeadingTrivia().Any(trivia => trivia.IsKind(SyntaxKind.IfDirectiveTrivia)))
{
startOfLastDirective = i;
}
if (root.Usings[i].GetLeadingTrivia().Any(trivia => trivia.IsKind(SyntaxKind.EndIfDirectiveTrivia)))
{
endOfLastDirective = i;
}
}
// if the entire using is in a directive or there is a using list at the end outside of the directive add the using at the end,
// else place it before the last directive.
usings.AddRange(root.Usings);
if ((startOfLastDirective == 0 && (endOfLastDirective == endOfList || endOfLastDirective == -1)) ||
(startOfLastDirective == -1 && endOfLastDirective == -1) ||
(endOfLastDirective != endOfList && endOfLastDirective != -1))
{
usings.AddRange(usingDirectives);
}
else
{
usings.InsertRange(startOfLastDirective, usingDirectives);
}
return usings;
}
}
}
| 1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/Core/Shared/Extensions/SnapshotPointExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions
{
internal static class SnapshotPointExtensions
{
public static void GetLineAndCharacter(this SnapshotPoint point, out int lineNumber, out int characterIndex)
=> point.Snapshot.GetLineAndCharacter(point.Position, out lineNumber, out characterIndex);
public static int GetContainingLineNumber(this SnapshotPoint point)
=> point.GetContainingLine().LineNumber;
public static ITrackingPoint CreateTrackingPoint(this SnapshotPoint point, PointTrackingMode trackingMode)
=> point.Snapshot.CreateTrackingPoint(point, trackingMode);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions
{
internal static class SnapshotPointExtensions
{
public static void GetLineAndCharacter(this SnapshotPoint point, out int lineNumber, out int characterIndex)
=> point.Snapshot.GetLineAndCharacter(point.Position, out lineNumber, out characterIndex);
public static int GetContainingLineNumber(this SnapshotPoint point)
=> point.GetContainingLine().LineNumber;
public static ITrackingPoint CreateTrackingPoint(this SnapshotPoint point, PointTrackingMode trackingMode)
=> point.Snapshot.CreateTrackingPoint(point, trackingMode);
}
}
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Def/Implementation/Remote/VisualStudioRemoteHostClientProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.ServiceBroker;
using Roslyn.Utilities;
using VSThreading = Microsoft.VisualStudio.Threading;
namespace Microsoft.VisualStudio.LanguageServices.Remote
{
internal sealed class VisualStudioRemoteHostClientProvider : IRemoteHostClientProvider
{
[ExportWorkspaceServiceFactory(typeof(IRemoteHostClientProvider), WorkspaceKind.Host), Shared]
internal sealed class Factory : IWorkspaceServiceFactory
{
private readonly IAsyncServiceProvider _vsServiceProvider;
private readonly AsynchronousOperationListenerProvider _listenerProvider;
private readonly RemoteServiceCallbackDispatcherRegistry _callbackDispatchers;
private readonly IThreadingContext _threadingContext;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public Factory(
SVsServiceProvider vsServiceProvider,
AsynchronousOperationListenerProvider listenerProvider,
IThreadingContext threadingContext,
[ImportMany] IEnumerable<Lazy<IRemoteServiceCallbackDispatcher, RemoteServiceCallbackDispatcherRegistry.ExportMetadata>> callbackDispatchers)
{
_vsServiceProvider = (IAsyncServiceProvider)vsServiceProvider;
_listenerProvider = listenerProvider;
_threadingContext = threadingContext;
_callbackDispatchers = new RemoteServiceCallbackDispatcherRegistry(callbackDispatchers);
}
[Obsolete(MefConstruction.FactoryMethodMessage, error: true)]
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
{
// We don't want to bring up the OOP process in a VS cloud environment client instance
// Avoids proffering brokered services on the client instance.
if (!RemoteHostOptions.IsUsingServiceHubOutOfProcess(workspaceServices) ||
workspaceServices.Workspace is not VisualStudioWorkspace ||
workspaceServices.GetRequiredService<IWorkspaceContextService>().IsCloudEnvironmentClient())
{
// Run code in the current process
return new DefaultRemoteHostClientProvider();
}
return new VisualStudioRemoteHostClientProvider(workspaceServices, _vsServiceProvider, _threadingContext, _listenerProvider, _callbackDispatchers);
}
}
private readonly HostWorkspaceServices _services;
private readonly VSThreading.AsyncLazy<RemoteHostClient?> _lazyClient;
private readonly IAsyncServiceProvider _vsServiceProvider;
private readonly AsynchronousOperationListenerProvider _listenerProvider;
private readonly RemoteServiceCallbackDispatcherRegistry _callbackDispatchers;
private VisualStudioRemoteHostClientProvider(
HostWorkspaceServices services,
IAsyncServiceProvider vsServiceProvider,
IThreadingContext threadingContext,
AsynchronousOperationListenerProvider listenerProvider,
RemoteServiceCallbackDispatcherRegistry callbackDispatchers)
{
_services = services;
_vsServiceProvider = vsServiceProvider;
_listenerProvider = listenerProvider;
_callbackDispatchers = callbackDispatchers;
// using VS AsyncLazy here since Roslyn's is not compatible with JTF.
// Our ServiceBroker services may be invoked by other VS components under JTF.
_lazyClient = new VSThreading.AsyncLazy<RemoteHostClient?>(CreateHostClientAsync, threadingContext.JoinableTaskFactory);
}
private async Task<RemoteHostClient?> CreateHostClientAsync()
{
try
{
var brokeredServiceContainer = await _vsServiceProvider.GetServiceAsync<SVsBrokeredServiceContainer, IBrokeredServiceContainer>().ConfigureAwait(false);
var serviceBroker = brokeredServiceContainer.GetFullAccessServiceBroker();
// VS AsyncLazy does not currently support cancellation:
var client = await ServiceHubRemoteHostClient.CreateAsync(_services, _listenerProvider, serviceBroker, _callbackDispatchers, CancellationToken.None).ConfigureAwait(false);
// proffer in-proc brokered services:
_ = brokeredServiceContainer.Proffer(SolutionAssetProvider.ServiceDescriptor, (_, _, _, _) => ValueTaskFactory.FromResult<object?>(new SolutionAssetProvider(_services)));
return client;
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e))
{
return null;
}
}
public Task<RemoteHostClient?> TryGetRemoteHostClientAsync(CancellationToken cancellationToken)
=> _lazyClient.GetValueAsync(cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.ServiceBroker;
using Roslyn.Utilities;
using VSThreading = Microsoft.VisualStudio.Threading;
namespace Microsoft.VisualStudio.LanguageServices.Remote
{
internal sealed class VisualStudioRemoteHostClientProvider : IRemoteHostClientProvider
{
[ExportWorkspaceServiceFactory(typeof(IRemoteHostClientProvider), WorkspaceKind.Host), Shared]
internal sealed class Factory : IWorkspaceServiceFactory
{
private readonly IAsyncServiceProvider _vsServiceProvider;
private readonly AsynchronousOperationListenerProvider _listenerProvider;
private readonly RemoteServiceCallbackDispatcherRegistry _callbackDispatchers;
private readonly IThreadingContext _threadingContext;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public Factory(
SVsServiceProvider vsServiceProvider,
AsynchronousOperationListenerProvider listenerProvider,
IThreadingContext threadingContext,
[ImportMany] IEnumerable<Lazy<IRemoteServiceCallbackDispatcher, RemoteServiceCallbackDispatcherRegistry.ExportMetadata>> callbackDispatchers)
{
_vsServiceProvider = (IAsyncServiceProvider)vsServiceProvider;
_listenerProvider = listenerProvider;
_threadingContext = threadingContext;
_callbackDispatchers = new RemoteServiceCallbackDispatcherRegistry(callbackDispatchers);
}
[Obsolete(MefConstruction.FactoryMethodMessage, error: true)]
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
{
// We don't want to bring up the OOP process in a VS cloud environment client instance
// Avoids proffering brokered services on the client instance.
if (!RemoteHostOptions.IsUsingServiceHubOutOfProcess(workspaceServices) ||
workspaceServices.Workspace is not VisualStudioWorkspace ||
workspaceServices.GetRequiredService<IWorkspaceContextService>().IsCloudEnvironmentClient())
{
// Run code in the current process
return new DefaultRemoteHostClientProvider();
}
return new VisualStudioRemoteHostClientProvider(workspaceServices, _vsServiceProvider, _threadingContext, _listenerProvider, _callbackDispatchers);
}
}
private readonly HostWorkspaceServices _services;
private readonly VSThreading.AsyncLazy<RemoteHostClient?> _lazyClient;
private readonly IAsyncServiceProvider _vsServiceProvider;
private readonly AsynchronousOperationListenerProvider _listenerProvider;
private readonly RemoteServiceCallbackDispatcherRegistry _callbackDispatchers;
private VisualStudioRemoteHostClientProvider(
HostWorkspaceServices services,
IAsyncServiceProvider vsServiceProvider,
IThreadingContext threadingContext,
AsynchronousOperationListenerProvider listenerProvider,
RemoteServiceCallbackDispatcherRegistry callbackDispatchers)
{
_services = services;
_vsServiceProvider = vsServiceProvider;
_listenerProvider = listenerProvider;
_callbackDispatchers = callbackDispatchers;
// using VS AsyncLazy here since Roslyn's is not compatible with JTF.
// Our ServiceBroker services may be invoked by other VS components under JTF.
_lazyClient = new VSThreading.AsyncLazy<RemoteHostClient?>(CreateHostClientAsync, threadingContext.JoinableTaskFactory);
}
private async Task<RemoteHostClient?> CreateHostClientAsync()
{
try
{
var brokeredServiceContainer = await _vsServiceProvider.GetServiceAsync<SVsBrokeredServiceContainer, IBrokeredServiceContainer>().ConfigureAwait(false);
var serviceBroker = brokeredServiceContainer.GetFullAccessServiceBroker();
// VS AsyncLazy does not currently support cancellation:
var client = await ServiceHubRemoteHostClient.CreateAsync(_services, _listenerProvider, serviceBroker, _callbackDispatchers, CancellationToken.None).ConfigureAwait(false);
// proffer in-proc brokered services:
_ = brokeredServiceContainer.Proffer(SolutionAssetProvider.ServiceDescriptor, (_, _, _, _) => ValueTaskFactory.FromResult<object?>(new SolutionAssetProvider(_services)));
return client;
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e))
{
return null;
}
}
public Task<RemoteHostClient?> TryGetRemoteHostClientAsync(CancellationToken cancellationToken)
=> _lazyClient.GetValueAsync(cancellationToken);
}
}
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/Core/Portable/ExternalAccess/UnitTesting/Api/IUnitTestingIncrementalAnalyzerImplementation.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api
{
internal interface IUnitTestingIncrementalAnalyzerImplementation
{
Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken);
Task DocumentOpenAsync(Document document, CancellationToken cancellationToken);
Task DocumentCloseAsync(Document document, CancellationToken cancellationToken);
Task DocumentResetAsync(Document document, CancellationToken cancellationToken);
Task AnalyzeSyntaxAsync(Document document, UnitTestingInvocationReasonsWrapper reasons, CancellationToken cancellationToken);
Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, UnitTestingInvocationReasonsWrapper reasons, CancellationToken cancellationToken);
Task AnalyzeProjectAsync(Project project, bool semanticsChanged, UnitTestingInvocationReasonsWrapper reasons, CancellationToken cancellationToken);
void RemoveDocument(DocumentId documentId);
void RemoveProject(ProjectId projectId);
bool NeedsReanalysisOnOptionChanged(object sender, UnitTestingOptionChangedEventArgsWrapper e);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api
{
internal interface IUnitTestingIncrementalAnalyzerImplementation
{
Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken);
Task DocumentOpenAsync(Document document, CancellationToken cancellationToken);
Task DocumentCloseAsync(Document document, CancellationToken cancellationToken);
Task DocumentResetAsync(Document document, CancellationToken cancellationToken);
Task AnalyzeSyntaxAsync(Document document, UnitTestingInvocationReasonsWrapper reasons, CancellationToken cancellationToken);
Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, UnitTestingInvocationReasonsWrapper reasons, CancellationToken cancellationToken);
Task AnalyzeProjectAsync(Project project, bool semanticsChanged, UnitTestingInvocationReasonsWrapper reasons, CancellationToken cancellationToken);
void RemoveDocument(DocumentId documentId);
void RemoveProject(ProjectId projectId);
bool NeedsReanalysisOnOptionChanged(object sender, UnitTestingOptionChangedEventArgsWrapper e);
}
}
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Server/VBCSCompiler/VisualBasicCompilerServer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.VisualBasic;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CompilerServer
{
internal sealed class VisualBasicCompilerServer : VisualBasicCompiler
{
private readonly Func<string, MetadataReferenceProperties, PortableExecutableReference> _metadataProvider;
internal VisualBasicCompilerServer(Func<string, MetadataReferenceProperties, PortableExecutableReference> metadataProvider, string[] args, BuildPaths buildPaths, string? libDirectory, IAnalyzerAssemblyLoader analyzerLoader)
: this(metadataProvider, Path.Combine(buildPaths.ClientDirectory, ResponseFileName), args, buildPaths, libDirectory, analyzerLoader)
{
}
internal VisualBasicCompilerServer(Func<string, MetadataReferenceProperties, PortableExecutableReference> metadataProvider, string? responseFile, string[] args, BuildPaths buildPaths, string? libDirectory, IAnalyzerAssemblyLoader analyzerLoader)
: base(VisualBasicCommandLineParser.Default, responseFile, args, buildPaths, libDirectory, analyzerLoader)
{
_metadataProvider = metadataProvider;
}
internal override Func<string, MetadataReferenceProperties, PortableExecutableReference> GetMetadataProvider()
{
return _metadataProvider;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.VisualBasic;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CompilerServer
{
internal sealed class VisualBasicCompilerServer : VisualBasicCompiler
{
private readonly Func<string, MetadataReferenceProperties, PortableExecutableReference> _metadataProvider;
internal VisualBasicCompilerServer(Func<string, MetadataReferenceProperties, PortableExecutableReference> metadataProvider, string[] args, BuildPaths buildPaths, string? libDirectory, IAnalyzerAssemblyLoader analyzerLoader)
: this(metadataProvider, Path.Combine(buildPaths.ClientDirectory, ResponseFileName), args, buildPaths, libDirectory, analyzerLoader)
{
}
internal VisualBasicCompilerServer(Func<string, MetadataReferenceProperties, PortableExecutableReference> metadataProvider, string? responseFile, string[] args, BuildPaths buildPaths, string? libDirectory, IAnalyzerAssemblyLoader analyzerLoader)
: base(VisualBasicCommandLineParser.Default, responseFile, args, buildPaths, libDirectory, analyzerLoader)
{
_metadataProvider = metadataProvider;
}
internal override Func<string, MetadataReferenceProperties, PortableExecutableReference> GetMetadataProvider()
{
return _metadataProvider;
}
}
}
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/CSharpTest2/Recommendations/IfKeywordRecommenderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 IfKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClass_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalStatement_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalVariableDeclaration_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInPreprocessor1()
{
await VerifyAbsenceAsync(AddInsideMethod(
"#if $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestEmptyStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterHash()
{
await VerifyKeywordAsync(
@"#$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterHashFollowedBySkippedTokens()
{
await VerifyKeywordAsync(
@"#$$
aeu");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterHashAndSpace()
{
await VerifyKeywordAsync(
@"# $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideMethod()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestBeforeStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$
return true;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"return true;
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterBlock()
{
await VerifyKeywordAsync(AddInsideMethod(
@"if (true) {
}
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterIf()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"if $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCase()
{
await VerifyKeywordAsync(AddInsideMethod(
@"switch (true) {
case 0:
$$
}"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCaseBlock()
{
await VerifyKeywordAsync(AddInsideMethod(
@"switch (true) {
case 0: {
$$
}
}"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDefaultCase()
{
await VerifyKeywordAsync(AddInsideMethod(
@"switch (true) {
default:
$$
}"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDefaultCaseBlock()
{
await VerifyKeywordAsync(AddInsideMethod(
@"switch (true) {
default: {
$$
}
}"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterLabel()
{
await VerifyKeywordAsync(AddInsideMethod(
@"label:
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterDoBlock()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"do {
}
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInActiveRegion1()
{
await VerifyKeywordAsync(AddInsideMethod(
@"#if true
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInActiveRegion2()
{
await VerifyKeywordAsync(AddInsideMethod(
@"#if true
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterElse()
{
await VerifyKeywordAsync(AddInsideMethod(
@"if (goo) {
} else $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterCatch()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"try {} catch $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterCatchDeclaration1()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"try {} catch (Exception) $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterCatchDeclaration2()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"try {} catch (Exception e) $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterCatchDeclarationEmpty()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"try {} catch () $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterTryBlock()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"try {} $$"));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 IfKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClass_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalStatement_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalVariableDeclaration_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInPreprocessor1()
{
await VerifyAbsenceAsync(AddInsideMethod(
"#if $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestEmptyStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterHash()
{
await VerifyKeywordAsync(
@"#$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterHashFollowedBySkippedTokens()
{
await VerifyKeywordAsync(
@"#$$
aeu");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterHashAndSpace()
{
await VerifyKeywordAsync(
@"# $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideMethod()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestBeforeStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$
return true;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"return true;
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterBlock()
{
await VerifyKeywordAsync(AddInsideMethod(
@"if (true) {
}
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterIf()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"if $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCase()
{
await VerifyKeywordAsync(AddInsideMethod(
@"switch (true) {
case 0:
$$
}"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCaseBlock()
{
await VerifyKeywordAsync(AddInsideMethod(
@"switch (true) {
case 0: {
$$
}
}"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDefaultCase()
{
await VerifyKeywordAsync(AddInsideMethod(
@"switch (true) {
default:
$$
}"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDefaultCaseBlock()
{
await VerifyKeywordAsync(AddInsideMethod(
@"switch (true) {
default: {
$$
}
}"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterLabel()
{
await VerifyKeywordAsync(AddInsideMethod(
@"label:
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterDoBlock()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"do {
}
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInActiveRegion1()
{
await VerifyKeywordAsync(AddInsideMethod(
@"#if true
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInActiveRegion2()
{
await VerifyKeywordAsync(AddInsideMethod(
@"#if true
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterElse()
{
await VerifyKeywordAsync(AddInsideMethod(
@"if (goo) {
} else $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterCatch()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"try {} catch $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterCatchDeclaration1()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"try {} catch (Exception) $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterCatchDeclaration2()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"try {} catch (Exception e) $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterCatchDeclarationEmpty()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"try {} catch () $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterTryBlock()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"try {} $$"));
}
}
}
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/SyntaxGeneratorExtensions_Negate.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Threading;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Simplification;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static partial class SyntaxGeneratorExtensions
{
private const string LongLength = "LongLength";
private static readonly Dictionary<BinaryOperatorKind, BinaryOperatorKind> s_negatedBinaryMap =
new Dictionary<BinaryOperatorKind, BinaryOperatorKind>()
{
{ BinaryOperatorKind.Equals, BinaryOperatorKind.NotEquals },
{ BinaryOperatorKind.NotEquals, BinaryOperatorKind.Equals },
{ BinaryOperatorKind.LessThan, BinaryOperatorKind.GreaterThanOrEqual },
{ BinaryOperatorKind.GreaterThan, BinaryOperatorKind.LessThanOrEqual },
{ BinaryOperatorKind.LessThanOrEqual, BinaryOperatorKind.GreaterThan },
{ BinaryOperatorKind.GreaterThanOrEqual, BinaryOperatorKind.LessThan },
{ BinaryOperatorKind.Or, BinaryOperatorKind.And },
{ BinaryOperatorKind.And, BinaryOperatorKind.Or },
{ BinaryOperatorKind.ConditionalOr, BinaryOperatorKind.ConditionalAnd },
{ BinaryOperatorKind.ConditionalAnd, BinaryOperatorKind.ConditionalOr },
};
public static SyntaxNode Negate(
this SyntaxGenerator generator,
SyntaxGeneratorInternal generatorInternal,
SyntaxNode expression,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
return Negate(generator, generatorInternal, expression, semanticModel, negateBinary: true, cancellationToken);
}
public static SyntaxNode Negate(
this SyntaxGenerator generator,
SyntaxGeneratorInternal generatorInternal,
SyntaxNode expressionOrPattern,
SemanticModel semanticModel,
bool negateBinary,
CancellationToken cancellationToken)
{
var syntaxFacts = generatorInternal.SyntaxFacts;
if (syntaxFacts.IsParenthesizedExpression(expressionOrPattern))
{
return generatorInternal.AddParentheses(
generator.Negate(
generatorInternal,
syntaxFacts.GetExpressionOfParenthesizedExpression(expressionOrPattern),
semanticModel,
negateBinary,
cancellationToken))
.WithTriviaFrom(expressionOrPattern);
}
if (negateBinary && syntaxFacts.IsBinaryExpression(expressionOrPattern))
return GetNegationOfBinaryExpression(expressionOrPattern, generator, generatorInternal, semanticModel, cancellationToken);
if (syntaxFacts.IsLiteralExpression(expressionOrPattern))
return GetNegationOfLiteralExpression(expressionOrPattern, generator, semanticModel);
if (syntaxFacts.IsLogicalNotExpression(expressionOrPattern))
return GetNegationOfLogicalNotExpression(expressionOrPattern, syntaxFacts);
if (negateBinary && syntaxFacts.IsIsPatternExpression(expressionOrPattern))
return GetNegationOfIsPatternExpression(expressionOrPattern, generator, generatorInternal, semanticModel, cancellationToken);
if (syntaxFacts.IsParenthesizedPattern(expressionOrPattern))
{
// Push the negation inside the parenthesized pattern.
return generatorInternal.AddParentheses(
generator.Negate(
generatorInternal,
syntaxFacts.GetPatternOfParenthesizedPattern(expressionOrPattern),
semanticModel,
negateBinary,
cancellationToken))
.WithTriviaFrom(expressionOrPattern);
}
if (negateBinary && syntaxFacts.IsBinaryPattern(expressionOrPattern))
return GetNegationOfBinaryPattern(expressionOrPattern, generator, generatorInternal, semanticModel, cancellationToken);
if (syntaxFacts.IsConstantPattern(expressionOrPattern))
return GetNegationOfConstantPattern(expressionOrPattern, generator, generatorInternal);
if (syntaxFacts.IsUnaryPattern(expressionOrPattern))
return GetNegationOfUnaryPattern(expressionOrPattern, generatorInternal, syntaxFacts);
// TODO(cyrusn): We could support negating relational patterns in the future. i.e.
//
// not >= 0 -> < 0
return syntaxFacts.IsAnyPattern(expressionOrPattern)
? generatorInternal.NotPattern(expressionOrPattern)
: generator.LogicalNotExpression(expressionOrPattern);
}
private static SyntaxNode GetNegationOfBinaryExpression(
SyntaxNode expressionNode,
SyntaxGenerator generator,
SyntaxGeneratorInternal generatorInternal,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
var syntaxFacts = generatorInternal.SyntaxFacts;
syntaxFacts.GetPartsOfBinaryExpression(expressionNode, out var leftOperand, out var operatorToken, out var rightOperand);
var binaryOperation = semanticModel.GetOperation(expressionNode, cancellationToken) as IBinaryOperation;
if (binaryOperation == null)
{
// x is y -> x is not y
if (syntaxFacts.IsIsExpression(expressionNode) && syntaxFacts.SupportsNotPattern(semanticModel.SyntaxTree.Options))
return generatorInternal.IsPatternExpression(leftOperand, operatorToken, generatorInternal.NotPattern(generatorInternal.TypePattern(rightOperand)));
// Apply the logical not operator if it is not a binary operation.
return generator.LogicalNotExpression(expressionNode);
}
if (!s_negatedBinaryMap.TryGetValue(binaryOperation.OperatorKind, out var negatedKind))
{
return generator.LogicalNotExpression(expressionNode);
}
else
{
var negateOperands = false;
switch (binaryOperation.OperatorKind)
{
case BinaryOperatorKind.Or:
case BinaryOperatorKind.And:
case BinaryOperatorKind.ConditionalAnd:
case BinaryOperatorKind.ConditionalOr:
negateOperands = true;
break;
}
//Workaround for https://github.com/dotnet/roslyn/issues/23956
//Issue to remove this when above is merged
if (binaryOperation.OperatorKind == BinaryOperatorKind.Or && syntaxFacts.IsLogicalOrExpression(expressionNode))
{
negatedKind = BinaryOperatorKind.ConditionalAnd;
}
else if (binaryOperation.OperatorKind == BinaryOperatorKind.And && syntaxFacts.IsLogicalAndExpression(expressionNode))
{
negatedKind = BinaryOperatorKind.ConditionalOr;
}
var newLeftOperand = leftOperand;
var newRightOperand = rightOperand;
if (negateOperands)
{
newLeftOperand = generator.Negate(generatorInternal, leftOperand, semanticModel, cancellationToken);
newRightOperand = generator.Negate(generatorInternal, rightOperand, semanticModel, cancellationToken);
}
var newBinaryExpressionSyntax = NewBinaryOperation(binaryOperation, newLeftOperand, negatedKind, newRightOperand, generator)
.WithTriviaFrom(expressionNode);
var newToken = syntaxFacts.GetOperatorTokenOfBinaryExpression(newBinaryExpressionSyntax);
var newTokenWithTrivia = newToken.WithTriviaFrom(operatorToken);
return newBinaryExpressionSyntax.ReplaceToken(newToken, newTokenWithTrivia);
}
}
private static SyntaxNode GetNegationOfBinaryPattern(
SyntaxNode pattern,
SyntaxGenerator generator,
SyntaxGeneratorInternal generatorInternal,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
// Apply demorgans's law here.
//
// not (a and b) -> not a or not b
// not (a or b) -> not a and not b
var syntaxFacts = generatorInternal.SyntaxFacts;
syntaxFacts.GetPartsOfBinaryPattern(pattern, out var left, out var operatorToken, out var right);
var newLeft = generator.Negate(generatorInternal, left, semanticModel, cancellationToken);
var newRight = generator.Negate(generatorInternal, right, semanticModel, cancellationToken);
var newPattern =
syntaxFacts.IsAndPattern(pattern) ? generatorInternal.OrPattern(newLeft, newRight) :
syntaxFacts.IsOrPattern(pattern) ? generatorInternal.AndPattern(newLeft, newRight) :
throw ExceptionUtilities.UnexpectedValue(pattern.RawKind);
newPattern = newPattern.WithTriviaFrom(pattern);
syntaxFacts.GetPartsOfBinaryPattern(newPattern, out _, out var newToken, out _);
var newTokenWithTrivia = newToken.WithTriviaFrom(operatorToken);
return newPattern.ReplaceToken(newToken, newTokenWithTrivia);
}
private static SyntaxNode GetNegationOfIsPatternExpression(SyntaxNode isExpression, SyntaxGenerator generator, SyntaxGeneratorInternal generatorInternal, SemanticModel semanticModel, CancellationToken cancellationToken)
{
// Don't recurse into patterns if the language doesn't support negated patterns.
// Just wrap with a normal '!' expression.
var syntaxFacts = generatorInternal.SyntaxFacts;
if (syntaxFacts.SupportsNotPattern(semanticModel.SyntaxTree.Options))
{
syntaxFacts.GetPartsOfIsPatternExpression(isExpression, out var left, out var isToken, out var pattern);
var negated = generator.Negate(generatorInternal, pattern, semanticModel, cancellationToken);
// Negating the pattern may have formed something illegal. If so, just do a normal `!` negation.
if (IsLegalPattern(syntaxFacts, negated, designatorsLegal: true))
{
if (syntaxFacts.IsTypePattern(negated))
{
// We started with `x is not t`. Unwrap the type pattern for 't' and create a simple `is` binary expr `x is t`.
var type = syntaxFacts.GetTypeOfTypePattern(negated);
return generator.IsTypeExpression(left, type);
}
else
{
// Keep this as a normal `is-pattern`, just with the pattern portion negated.
return generatorInternal.IsPatternExpression(left, isToken, negated);
}
}
}
return generator.LogicalNotExpression(isExpression);
}
private static bool IsLegalPattern(ISyntaxFacts syntaxFacts, SyntaxNode pattern, bool designatorsLegal)
{
// It is illegal to create a pattern that has a designator under a not-pattern or or-pattern
if (syntaxFacts.IsBinaryPattern(pattern))
{
syntaxFacts.GetPartsOfBinaryPattern(pattern, out var left, out _, out var right);
designatorsLegal = designatorsLegal && !syntaxFacts.IsOrPattern(pattern);
return IsLegalPattern(syntaxFacts, left, designatorsLegal) &&
IsLegalPattern(syntaxFacts, right, designatorsLegal);
}
if (syntaxFacts.IsNotPattern(pattern))
{
syntaxFacts.GetPartsOfUnaryPattern(pattern, out _, out var subPattern);
return IsLegalPattern(syntaxFacts, subPattern, designatorsLegal: false);
}
if (syntaxFacts.IsParenthesizedPattern(pattern))
{
syntaxFacts.GetPartsOfParenthesizedPattern(pattern, out _, out var subPattern, out _);
return IsLegalPattern(syntaxFacts, subPattern, designatorsLegal);
}
if (syntaxFacts.IsDeclarationPattern(pattern))
{
syntaxFacts.GetPartsOfDeclarationPattern(pattern, out _, out var designator);
return designator == null || designatorsLegal;
}
if (syntaxFacts.IsRecursivePattern(pattern))
{
syntaxFacts.GetPartsOfRecursivePattern(pattern, out _, out _, out _, out var designator);
return designator == null || designatorsLegal;
}
if (syntaxFacts.IsVarPattern(pattern))
return designatorsLegal;
return true;
}
private static SyntaxNode NewBinaryOperation(
IBinaryOperation binaryOperation,
SyntaxNode leftOperand,
BinaryOperatorKind operationKind,
SyntaxNode rightOperand,
SyntaxGenerator generator)
{
switch (operationKind)
{
case BinaryOperatorKind.Equals:
return binaryOperation.LeftOperand.Type?.IsValueType == true && binaryOperation.RightOperand.Type?.IsValueType == true
? generator.ValueEqualsExpression(leftOperand, rightOperand)
: generator.ReferenceEqualsExpression(leftOperand, rightOperand);
case BinaryOperatorKind.NotEquals:
return binaryOperation.LeftOperand.Type?.IsValueType == true && binaryOperation.RightOperand.Type?.IsValueType == true
? generator.ValueNotEqualsExpression(leftOperand, rightOperand)
: generator.ReferenceNotEqualsExpression(leftOperand, rightOperand);
case BinaryOperatorKind.LessThanOrEqual:
return IsSpecialCaseBinaryExpression(binaryOperation, operationKind)
? generator.ValueEqualsExpression(leftOperand, rightOperand)
: generator.LessThanOrEqualExpression(leftOperand, rightOperand);
case BinaryOperatorKind.GreaterThanOrEqual:
return IsSpecialCaseBinaryExpression(binaryOperation, operationKind)
? generator.ValueEqualsExpression(leftOperand, rightOperand)
: generator.GreaterThanOrEqualExpression(leftOperand, rightOperand);
case BinaryOperatorKind.LessThan:
return generator.LessThanExpression(leftOperand, rightOperand);
case BinaryOperatorKind.GreaterThan:
return generator.GreaterThanExpression(leftOperand, rightOperand);
case BinaryOperatorKind.Or:
return generator.BitwiseOrExpression(leftOperand, rightOperand);
case BinaryOperatorKind.And:
return generator.BitwiseAndExpression(leftOperand, rightOperand);
case BinaryOperatorKind.ConditionalOr:
return generator.LogicalOrExpression(leftOperand, rightOperand);
case BinaryOperatorKind.ConditionalAnd:
return generator.LogicalAndExpression(leftOperand, rightOperand);
}
return null;
}
/// <summary>
/// Returns true if the binaryExpression consists of an expression that can never be negative,
/// such as length or unsigned numeric types, being compared to zero with greater than,
/// less than, or equals relational operator.
/// </summary>
public static bool IsSpecialCaseBinaryExpression(
IBinaryOperation binaryOperation,
BinaryOperatorKind operationKind)
{
if (binaryOperation == null)
{
return false;
}
var rightOperand = RemoveImplicitConversion(binaryOperation.RightOperand);
var leftOperand = RemoveImplicitConversion(binaryOperation.LeftOperand);
switch (operationKind)
{
case BinaryOperatorKind.LessThanOrEqual when rightOperand.IsNumericLiteral():
return CanSimplifyToLengthEqualsZeroExpression(
leftOperand, (ILiteralOperation)rightOperand);
case BinaryOperatorKind.GreaterThanOrEqual when leftOperand.IsNumericLiteral():
return CanSimplifyToLengthEqualsZeroExpression(
rightOperand, (ILiteralOperation)leftOperand);
}
return false;
}
private static IOperation RemoveImplicitConversion(IOperation operation)
{
return operation is IConversionOperation conversion && conversion.IsImplicit
? RemoveImplicitConversion(conversion.Operand)
: operation;
}
private static bool CanSimplifyToLengthEqualsZeroExpression(
IOperation variableExpression, ILiteralOperation numericLiteralExpression)
{
var numericValue = numericLiteralExpression.ConstantValue;
if (numericValue.HasValue && numericValue.Value is 0)
{
if (variableExpression is IPropertyReferenceOperation propertyOperation)
{
var property = propertyOperation.Property;
if ((property.Name == nameof(Array.Length) || property.Name == LongLength))
{
var containingType = property.ContainingType;
if (containingType?.SpecialType == SpecialType.System_Array ||
containingType.SpecialType == SpecialType.System_String)
{
return true;
}
}
}
var type = variableExpression.Type;
if (type != null)
{
switch (type.SpecialType)
{
case SpecialType.System_Byte:
case SpecialType.System_UInt16:
case SpecialType.System_UInt32:
case SpecialType.System_UInt64:
return true;
}
}
}
return false;
}
private static SyntaxNode GetNegationOfLiteralExpression(
SyntaxNode expression,
SyntaxGenerator generator,
SemanticModel semanticModel)
{
var operation = semanticModel.GetOperation(expression);
SyntaxNode newLiteralExpression;
if (operation?.Kind == OperationKind.Literal && operation.ConstantValue.HasValue && operation.ConstantValue.Value is true)
{
newLiteralExpression = generator.FalseLiteralExpression();
}
else if (operation?.Kind == OperationKind.Literal && operation.ConstantValue.HasValue && operation.ConstantValue.Value is false)
{
newLiteralExpression = generator.TrueLiteralExpression();
}
else
{
newLiteralExpression = generator.LogicalNotExpression(expression.WithoutTrivia());
}
return newLiteralExpression.WithTriviaFrom(expression);
}
private static SyntaxNode GetNegationOfConstantPattern(
SyntaxNode pattern,
SyntaxGenerator generator,
SyntaxGeneratorInternal generatorInternal)
{
var syntaxFacts = generatorInternal.SyntaxFacts;
// If we have `is true/false` just swap that to be `is false/true`.
var expression = syntaxFacts.GetExpressionOfConstantPattern(pattern);
if (syntaxFacts.IsTrueLiteralExpression(expression))
return generatorInternal.ConstantPattern(generator.FalseLiteralExpression());
if (syntaxFacts.IsFalseLiteralExpression(expression))
return generatorInternal.ConstantPattern(generator.TrueLiteralExpression());
// Otherwise, just negate the entire pattern, we don't have anything else special we can do here.
return generatorInternal.NotPattern(pattern);
}
private static SyntaxNode GetNegationOfLogicalNotExpression(
SyntaxNode expression,
ISyntaxFacts syntaxFacts)
{
var operatorToken = syntaxFacts.GetOperatorTokenOfPrefixUnaryExpression(expression);
var operand = syntaxFacts.GetOperandOfPrefixUnaryExpression(expression);
return operand.WithPrependedLeadingTrivia(operatorToken.LeadingTrivia)
.WithAdditionalAnnotations(Simplifier.Annotation);
}
private static SyntaxNode GetNegationOfUnaryPattern(
SyntaxNode pattern,
SyntaxGeneratorInternal generatorInternal,
ISyntaxFacts syntaxFacts)
{
syntaxFacts.GetPartsOfUnaryPattern(pattern, out var opToken, out var subPattern);
// not not p -> p
if (syntaxFacts.IsNotPattern(pattern))
{
return subPattern.WithPrependedLeadingTrivia(opToken.LeadingTrivia)
.WithAdditionalAnnotations(Simplifier.Annotation);
}
// If there are other interesting unary patterns in the future, we can support specialized logic for
// negating them here.
return generatorInternal.NotPattern(pattern);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Threading;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Simplification;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static partial class SyntaxGeneratorExtensions
{
private const string LongLength = "LongLength";
private static readonly Dictionary<BinaryOperatorKind, BinaryOperatorKind> s_negatedBinaryMap =
new Dictionary<BinaryOperatorKind, BinaryOperatorKind>()
{
{ BinaryOperatorKind.Equals, BinaryOperatorKind.NotEquals },
{ BinaryOperatorKind.NotEquals, BinaryOperatorKind.Equals },
{ BinaryOperatorKind.LessThan, BinaryOperatorKind.GreaterThanOrEqual },
{ BinaryOperatorKind.GreaterThan, BinaryOperatorKind.LessThanOrEqual },
{ BinaryOperatorKind.LessThanOrEqual, BinaryOperatorKind.GreaterThan },
{ BinaryOperatorKind.GreaterThanOrEqual, BinaryOperatorKind.LessThan },
{ BinaryOperatorKind.Or, BinaryOperatorKind.And },
{ BinaryOperatorKind.And, BinaryOperatorKind.Or },
{ BinaryOperatorKind.ConditionalOr, BinaryOperatorKind.ConditionalAnd },
{ BinaryOperatorKind.ConditionalAnd, BinaryOperatorKind.ConditionalOr },
};
public static SyntaxNode Negate(
this SyntaxGenerator generator,
SyntaxGeneratorInternal generatorInternal,
SyntaxNode expression,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
return Negate(generator, generatorInternal, expression, semanticModel, negateBinary: true, cancellationToken);
}
public static SyntaxNode Negate(
this SyntaxGenerator generator,
SyntaxGeneratorInternal generatorInternal,
SyntaxNode expressionOrPattern,
SemanticModel semanticModel,
bool negateBinary,
CancellationToken cancellationToken)
{
var syntaxFacts = generatorInternal.SyntaxFacts;
if (syntaxFacts.IsParenthesizedExpression(expressionOrPattern))
{
return generatorInternal.AddParentheses(
generator.Negate(
generatorInternal,
syntaxFacts.GetExpressionOfParenthesizedExpression(expressionOrPattern),
semanticModel,
negateBinary,
cancellationToken))
.WithTriviaFrom(expressionOrPattern);
}
if (negateBinary && syntaxFacts.IsBinaryExpression(expressionOrPattern))
return GetNegationOfBinaryExpression(expressionOrPattern, generator, generatorInternal, semanticModel, cancellationToken);
if (syntaxFacts.IsLiteralExpression(expressionOrPattern))
return GetNegationOfLiteralExpression(expressionOrPattern, generator, semanticModel);
if (syntaxFacts.IsLogicalNotExpression(expressionOrPattern))
return GetNegationOfLogicalNotExpression(expressionOrPattern, syntaxFacts);
if (negateBinary && syntaxFacts.IsIsPatternExpression(expressionOrPattern))
return GetNegationOfIsPatternExpression(expressionOrPattern, generator, generatorInternal, semanticModel, cancellationToken);
if (syntaxFacts.IsParenthesizedPattern(expressionOrPattern))
{
// Push the negation inside the parenthesized pattern.
return generatorInternal.AddParentheses(
generator.Negate(
generatorInternal,
syntaxFacts.GetPatternOfParenthesizedPattern(expressionOrPattern),
semanticModel,
negateBinary,
cancellationToken))
.WithTriviaFrom(expressionOrPattern);
}
if (negateBinary && syntaxFacts.IsBinaryPattern(expressionOrPattern))
return GetNegationOfBinaryPattern(expressionOrPattern, generator, generatorInternal, semanticModel, cancellationToken);
if (syntaxFacts.IsConstantPattern(expressionOrPattern))
return GetNegationOfConstantPattern(expressionOrPattern, generator, generatorInternal);
if (syntaxFacts.IsUnaryPattern(expressionOrPattern))
return GetNegationOfUnaryPattern(expressionOrPattern, generatorInternal, syntaxFacts);
// TODO(cyrusn): We could support negating relational patterns in the future. i.e.
//
// not >= 0 -> < 0
return syntaxFacts.IsAnyPattern(expressionOrPattern)
? generatorInternal.NotPattern(expressionOrPattern)
: generator.LogicalNotExpression(expressionOrPattern);
}
private static SyntaxNode GetNegationOfBinaryExpression(
SyntaxNode expressionNode,
SyntaxGenerator generator,
SyntaxGeneratorInternal generatorInternal,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
var syntaxFacts = generatorInternal.SyntaxFacts;
syntaxFacts.GetPartsOfBinaryExpression(expressionNode, out var leftOperand, out var operatorToken, out var rightOperand);
var binaryOperation = semanticModel.GetOperation(expressionNode, cancellationToken) as IBinaryOperation;
if (binaryOperation == null)
{
// x is y -> x is not y
if (syntaxFacts.IsIsExpression(expressionNode) && syntaxFacts.SupportsNotPattern(semanticModel.SyntaxTree.Options))
return generatorInternal.IsPatternExpression(leftOperand, operatorToken, generatorInternal.NotPattern(generatorInternal.TypePattern(rightOperand)));
// Apply the logical not operator if it is not a binary operation.
return generator.LogicalNotExpression(expressionNode);
}
if (!s_negatedBinaryMap.TryGetValue(binaryOperation.OperatorKind, out var negatedKind))
{
return generator.LogicalNotExpression(expressionNode);
}
else
{
var negateOperands = false;
switch (binaryOperation.OperatorKind)
{
case BinaryOperatorKind.Or:
case BinaryOperatorKind.And:
case BinaryOperatorKind.ConditionalAnd:
case BinaryOperatorKind.ConditionalOr:
negateOperands = true;
break;
}
//Workaround for https://github.com/dotnet/roslyn/issues/23956
//Issue to remove this when above is merged
if (binaryOperation.OperatorKind == BinaryOperatorKind.Or && syntaxFacts.IsLogicalOrExpression(expressionNode))
{
negatedKind = BinaryOperatorKind.ConditionalAnd;
}
else if (binaryOperation.OperatorKind == BinaryOperatorKind.And && syntaxFacts.IsLogicalAndExpression(expressionNode))
{
negatedKind = BinaryOperatorKind.ConditionalOr;
}
var newLeftOperand = leftOperand;
var newRightOperand = rightOperand;
if (negateOperands)
{
newLeftOperand = generator.Negate(generatorInternal, leftOperand, semanticModel, cancellationToken);
newRightOperand = generator.Negate(generatorInternal, rightOperand, semanticModel, cancellationToken);
}
var newBinaryExpressionSyntax = NewBinaryOperation(binaryOperation, newLeftOperand, negatedKind, newRightOperand, generator)
.WithTriviaFrom(expressionNode);
var newToken = syntaxFacts.GetOperatorTokenOfBinaryExpression(newBinaryExpressionSyntax);
var newTokenWithTrivia = newToken.WithTriviaFrom(operatorToken);
return newBinaryExpressionSyntax.ReplaceToken(newToken, newTokenWithTrivia);
}
}
private static SyntaxNode GetNegationOfBinaryPattern(
SyntaxNode pattern,
SyntaxGenerator generator,
SyntaxGeneratorInternal generatorInternal,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
// Apply demorgans's law here.
//
// not (a and b) -> not a or not b
// not (a or b) -> not a and not b
var syntaxFacts = generatorInternal.SyntaxFacts;
syntaxFacts.GetPartsOfBinaryPattern(pattern, out var left, out var operatorToken, out var right);
var newLeft = generator.Negate(generatorInternal, left, semanticModel, cancellationToken);
var newRight = generator.Negate(generatorInternal, right, semanticModel, cancellationToken);
var newPattern =
syntaxFacts.IsAndPattern(pattern) ? generatorInternal.OrPattern(newLeft, newRight) :
syntaxFacts.IsOrPattern(pattern) ? generatorInternal.AndPattern(newLeft, newRight) :
throw ExceptionUtilities.UnexpectedValue(pattern.RawKind);
newPattern = newPattern.WithTriviaFrom(pattern);
syntaxFacts.GetPartsOfBinaryPattern(newPattern, out _, out var newToken, out _);
var newTokenWithTrivia = newToken.WithTriviaFrom(operatorToken);
return newPattern.ReplaceToken(newToken, newTokenWithTrivia);
}
private static SyntaxNode GetNegationOfIsPatternExpression(SyntaxNode isExpression, SyntaxGenerator generator, SyntaxGeneratorInternal generatorInternal, SemanticModel semanticModel, CancellationToken cancellationToken)
{
// Don't recurse into patterns if the language doesn't support negated patterns.
// Just wrap with a normal '!' expression.
var syntaxFacts = generatorInternal.SyntaxFacts;
if (syntaxFacts.SupportsNotPattern(semanticModel.SyntaxTree.Options))
{
syntaxFacts.GetPartsOfIsPatternExpression(isExpression, out var left, out var isToken, out var pattern);
var negated = generator.Negate(generatorInternal, pattern, semanticModel, cancellationToken);
// Negating the pattern may have formed something illegal. If so, just do a normal `!` negation.
if (IsLegalPattern(syntaxFacts, negated, designatorsLegal: true))
{
if (syntaxFacts.IsTypePattern(negated))
{
// We started with `x is not t`. Unwrap the type pattern for 't' and create a simple `is` binary expr `x is t`.
var type = syntaxFacts.GetTypeOfTypePattern(negated);
return generator.IsTypeExpression(left, type);
}
else
{
// Keep this as a normal `is-pattern`, just with the pattern portion negated.
return generatorInternal.IsPatternExpression(left, isToken, negated);
}
}
}
return generator.LogicalNotExpression(isExpression);
}
private static bool IsLegalPattern(ISyntaxFacts syntaxFacts, SyntaxNode pattern, bool designatorsLegal)
{
// It is illegal to create a pattern that has a designator under a not-pattern or or-pattern
if (syntaxFacts.IsBinaryPattern(pattern))
{
syntaxFacts.GetPartsOfBinaryPattern(pattern, out var left, out _, out var right);
designatorsLegal = designatorsLegal && !syntaxFacts.IsOrPattern(pattern);
return IsLegalPattern(syntaxFacts, left, designatorsLegal) &&
IsLegalPattern(syntaxFacts, right, designatorsLegal);
}
if (syntaxFacts.IsNotPattern(pattern))
{
syntaxFacts.GetPartsOfUnaryPattern(pattern, out _, out var subPattern);
return IsLegalPattern(syntaxFacts, subPattern, designatorsLegal: false);
}
if (syntaxFacts.IsParenthesizedPattern(pattern))
{
syntaxFacts.GetPartsOfParenthesizedPattern(pattern, out _, out var subPattern, out _);
return IsLegalPattern(syntaxFacts, subPattern, designatorsLegal);
}
if (syntaxFacts.IsDeclarationPattern(pattern))
{
syntaxFacts.GetPartsOfDeclarationPattern(pattern, out _, out var designator);
return designator == null || designatorsLegal;
}
if (syntaxFacts.IsRecursivePattern(pattern))
{
syntaxFacts.GetPartsOfRecursivePattern(pattern, out _, out _, out _, out var designator);
return designator == null || designatorsLegal;
}
if (syntaxFacts.IsVarPattern(pattern))
return designatorsLegal;
return true;
}
private static SyntaxNode NewBinaryOperation(
IBinaryOperation binaryOperation,
SyntaxNode leftOperand,
BinaryOperatorKind operationKind,
SyntaxNode rightOperand,
SyntaxGenerator generator)
{
switch (operationKind)
{
case BinaryOperatorKind.Equals:
return binaryOperation.LeftOperand.Type?.IsValueType == true && binaryOperation.RightOperand.Type?.IsValueType == true
? generator.ValueEqualsExpression(leftOperand, rightOperand)
: generator.ReferenceEqualsExpression(leftOperand, rightOperand);
case BinaryOperatorKind.NotEquals:
return binaryOperation.LeftOperand.Type?.IsValueType == true && binaryOperation.RightOperand.Type?.IsValueType == true
? generator.ValueNotEqualsExpression(leftOperand, rightOperand)
: generator.ReferenceNotEqualsExpression(leftOperand, rightOperand);
case BinaryOperatorKind.LessThanOrEqual:
return IsSpecialCaseBinaryExpression(binaryOperation, operationKind)
? generator.ValueEqualsExpression(leftOperand, rightOperand)
: generator.LessThanOrEqualExpression(leftOperand, rightOperand);
case BinaryOperatorKind.GreaterThanOrEqual:
return IsSpecialCaseBinaryExpression(binaryOperation, operationKind)
? generator.ValueEqualsExpression(leftOperand, rightOperand)
: generator.GreaterThanOrEqualExpression(leftOperand, rightOperand);
case BinaryOperatorKind.LessThan:
return generator.LessThanExpression(leftOperand, rightOperand);
case BinaryOperatorKind.GreaterThan:
return generator.GreaterThanExpression(leftOperand, rightOperand);
case BinaryOperatorKind.Or:
return generator.BitwiseOrExpression(leftOperand, rightOperand);
case BinaryOperatorKind.And:
return generator.BitwiseAndExpression(leftOperand, rightOperand);
case BinaryOperatorKind.ConditionalOr:
return generator.LogicalOrExpression(leftOperand, rightOperand);
case BinaryOperatorKind.ConditionalAnd:
return generator.LogicalAndExpression(leftOperand, rightOperand);
}
return null;
}
/// <summary>
/// Returns true if the binaryExpression consists of an expression that can never be negative,
/// such as length or unsigned numeric types, being compared to zero with greater than,
/// less than, or equals relational operator.
/// </summary>
public static bool IsSpecialCaseBinaryExpression(
IBinaryOperation binaryOperation,
BinaryOperatorKind operationKind)
{
if (binaryOperation == null)
{
return false;
}
var rightOperand = RemoveImplicitConversion(binaryOperation.RightOperand);
var leftOperand = RemoveImplicitConversion(binaryOperation.LeftOperand);
switch (operationKind)
{
case BinaryOperatorKind.LessThanOrEqual when rightOperand.IsNumericLiteral():
return CanSimplifyToLengthEqualsZeroExpression(
leftOperand, (ILiteralOperation)rightOperand);
case BinaryOperatorKind.GreaterThanOrEqual when leftOperand.IsNumericLiteral():
return CanSimplifyToLengthEqualsZeroExpression(
rightOperand, (ILiteralOperation)leftOperand);
}
return false;
}
private static IOperation RemoveImplicitConversion(IOperation operation)
{
return operation is IConversionOperation conversion && conversion.IsImplicit
? RemoveImplicitConversion(conversion.Operand)
: operation;
}
private static bool CanSimplifyToLengthEqualsZeroExpression(
IOperation variableExpression, ILiteralOperation numericLiteralExpression)
{
var numericValue = numericLiteralExpression.ConstantValue;
if (numericValue.HasValue && numericValue.Value is 0)
{
if (variableExpression is IPropertyReferenceOperation propertyOperation)
{
var property = propertyOperation.Property;
if ((property.Name == nameof(Array.Length) || property.Name == LongLength))
{
var containingType = property.ContainingType;
if (containingType?.SpecialType == SpecialType.System_Array ||
containingType.SpecialType == SpecialType.System_String)
{
return true;
}
}
}
var type = variableExpression.Type;
if (type != null)
{
switch (type.SpecialType)
{
case SpecialType.System_Byte:
case SpecialType.System_UInt16:
case SpecialType.System_UInt32:
case SpecialType.System_UInt64:
return true;
}
}
}
return false;
}
private static SyntaxNode GetNegationOfLiteralExpression(
SyntaxNode expression,
SyntaxGenerator generator,
SemanticModel semanticModel)
{
var operation = semanticModel.GetOperation(expression);
SyntaxNode newLiteralExpression;
if (operation?.Kind == OperationKind.Literal && operation.ConstantValue.HasValue && operation.ConstantValue.Value is true)
{
newLiteralExpression = generator.FalseLiteralExpression();
}
else if (operation?.Kind == OperationKind.Literal && operation.ConstantValue.HasValue && operation.ConstantValue.Value is false)
{
newLiteralExpression = generator.TrueLiteralExpression();
}
else
{
newLiteralExpression = generator.LogicalNotExpression(expression.WithoutTrivia());
}
return newLiteralExpression.WithTriviaFrom(expression);
}
private static SyntaxNode GetNegationOfConstantPattern(
SyntaxNode pattern,
SyntaxGenerator generator,
SyntaxGeneratorInternal generatorInternal)
{
var syntaxFacts = generatorInternal.SyntaxFacts;
// If we have `is true/false` just swap that to be `is false/true`.
var expression = syntaxFacts.GetExpressionOfConstantPattern(pattern);
if (syntaxFacts.IsTrueLiteralExpression(expression))
return generatorInternal.ConstantPattern(generator.FalseLiteralExpression());
if (syntaxFacts.IsFalseLiteralExpression(expression))
return generatorInternal.ConstantPattern(generator.TrueLiteralExpression());
// Otherwise, just negate the entire pattern, we don't have anything else special we can do here.
return generatorInternal.NotPattern(pattern);
}
private static SyntaxNode GetNegationOfLogicalNotExpression(
SyntaxNode expression,
ISyntaxFacts syntaxFacts)
{
var operatorToken = syntaxFacts.GetOperatorTokenOfPrefixUnaryExpression(expression);
var operand = syntaxFacts.GetOperandOfPrefixUnaryExpression(expression);
return operand.WithPrependedLeadingTrivia(operatorToken.LeadingTrivia)
.WithAdditionalAnnotations(Simplifier.Annotation);
}
private static SyntaxNode GetNegationOfUnaryPattern(
SyntaxNode pattern,
SyntaxGeneratorInternal generatorInternal,
ISyntaxFacts syntaxFacts)
{
syntaxFacts.GetPartsOfUnaryPattern(pattern, out var opToken, out var subPattern);
// not not p -> p
if (syntaxFacts.IsNotPattern(pattern))
{
return subPattern.WithPrependedLeadingTrivia(opToken.LeadingTrivia)
.WithAdditionalAnnotations(Simplifier.Annotation);
}
// If there are other interesting unary patterns in the future, we can support specialized logic for
// negating them here.
return generatorInternal.NotPattern(pattern);
}
}
}
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/Core.Cocoa/Structure/StructureTaggerProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Projection;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Structure
{
[Export(typeof(ITaggerProvider))]
[TagType(typeof(IStructureTag))]
[ContentType(ContentTypeNames.RoslynContentType)]
internal partial class StructureTaggerProvider :
AbstractStructureTaggerProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public StructureTaggerProvider(
IThreadingContext threadingContext,
IEditorOptionsFactoryService editorOptionsFactoryService,
IProjectionBufferFactoryService projectionBufferFactoryService,
IAsynchronousOperationListenerProvider listenerProvider)
: base(threadingContext, editorOptionsFactoryService, projectionBufferFactoryService, listenerProvider)
{
}
internal override object? GetCollapsedHintForm(StructureTag structureTag)
{
return CreateElisionBufferForTagTooltip(structureTag).CurrentSnapshot.GetText();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Projection;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Structure
{
[Export(typeof(ITaggerProvider))]
[TagType(typeof(IStructureTag))]
[ContentType(ContentTypeNames.RoslynContentType)]
internal partial class StructureTaggerProvider :
AbstractStructureTaggerProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public StructureTaggerProvider(
IThreadingContext threadingContext,
IEditorOptionsFactoryService editorOptionsFactoryService,
IProjectionBufferFactoryService projectionBufferFactoryService,
IAsynchronousOperationListenerProvider listenerProvider)
: base(threadingContext, editorOptionsFactoryService, projectionBufferFactoryService, listenerProvider)
{
}
internal override object? GetCollapsedHintForm(StructureTag structureTag)
{
return CreateElisionBufferForTagTooltip(structureTag).CurrentSnapshot.GetText();
}
}
}
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/Test2/Rename/VisualBasic/DeclarationConflictTests.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.Remote.Testing
Imports Microsoft.CodeAnalysis.Rename.ConflictEngine
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.VisualBasic
<[UseExportProvider]>
Public Class DeclarationConflictTests
Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper
Public Sub New(outputHelper As Abstractions.ITestOutputHelper)
_outputHelper = outputHelper
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenFields(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module GooModule
Dim [|$$goo|] As Integer
Dim {|Conflict:bar|} As Integer
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="bar")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenFieldAndMethod(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module GooModule
Dim [|$$goo|] As Integer
Sub {|Conflict:bar|}()
End Module
</Document>
</Project>
</Workspace>, host:=host,
renameTo:="bar")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenTwoMethodsWithSameSignature(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module GooModule
Sub [|$$goo|]()
End Sub
Sub {|Conflict:bar|}()
End Sub
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="bar")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenTwoParameters(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module GooModule
Sub f([|$$goo|] As Integer, {|Conflict:bar|} As Integer)
End Sub
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="bar")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub NoConflictBetweenMethodsWithDifferentSignatures(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module GooModule
Sub [|$$goo|]()
End Sub
Sub bar(parameter As Integer)
End Sub
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="bar")
End Using
End Sub
<Theory>
<WorkItem(543245, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543245")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenTwoLocals(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
Sub Main(args As String())
Dim {|stmt1:$$i|} = 1
Dim {|Conflict:j|} = 2
End Sub
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="j")
result.AssertLabeledSpansAre("stmt1", "j", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(543245, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543245")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenLocalAndParameter(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
Sub Main({|Conflict:args|} As String())
Dim {|stmt1:$$i|} = 1
End Sub
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="args")
result.AssertLabeledSpansAre("stmt1", "args", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(545859, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545859")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenQueryVariableAndParameter(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
Sub Main({|Conflict:args|} As String())
Dim z = From {|stmt1:$$x|} In args
End Sub
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="args")
result.AssertLabeledSpansAre("stmt1", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(545859, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545859")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenTwoQueryVariables(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
Sub Main(args As String())
Dim z = From {|Conflict:x|} In args
From {|stmt1:$$y|} In args
End Sub
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="x")
result.AssertLabeledSpansAre("stmt1", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(543654, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543654")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenLambdaParametersInsideMethod(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Module M1
Sub Main()
Dim y = Sub({|Conflict:c|}) Call (Sub(a, {|stmt1:$$b|}) Exit Sub)(c)
End Sub
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="c")
result.AssertLabeledSpansAre("stmt1", "c", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(543654, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543654")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenLambdaParametersInFieldInitializer(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Module M1
Dim y = Sub({|Conflict:c|}) Call (Sub({|stmt:$$b|}) Exit Sub)(c)
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="c")
result.AssertLabeledSpansAre("stmt", "c", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(543654, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543654")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub NoConflictBetweenLambdaParameterAndField(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Module M1
Dim y = Sub({|fieldinit:$$c|}) Exit Sub
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="y")
result.AssertLabeledSpansAre("fieldinit", "y", RelatedLocationType.NoConflict)
End Using
End Sub
<Theory>
<WorkItem(543407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543407")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenLabels(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Program
Sub Main()
{|Conflict:Goo|}:
[|$$Bar|]:
Dim f = Sub()
Goo:
End Sub
End Sub
End Class
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Goo")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(543308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543308")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenMethodsDifferingByByRef(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
Sub {|Conflict:a|}(x As Integer)
End Sub
Sub [|$$c|](ByRef x As Integer)
End Sub
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="a")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(543308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543308")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenMethodsDifferingByOptional(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
Sub {|Conflict:a|}(x As Integer)
End Sub
Sub [|$$d|](x As Integer, Optional y As Integer = 0)
End Sub
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="a")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(543308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543308")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub NoConflictBetweenMethodsDifferingByArity(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
Sub a(Of T)(x As Integer)
End Sub
Sub [|$$d|](x As Integer, Optional y As Integer = 0)
End Sub
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="a")
End Using
End Sub
<Theory>
<WorkItem(546902, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546902")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenImplicitlyDeclaredLocalAndNamespace(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Explicit Off
Module Program
Sub Main()
__ = {|Conflict1:$$Google|}
{|Conflict2:Google|} = __
End Sub
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Microsoft")
result.AssertLabeledSpansAre("Conflict1", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("Conflict2", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(529556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529556")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenImplicitlyDeclaredLocalAndAndGlobalFunction(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports Microsoft.VisualBasic
Module Module1
Sub Main()
Dim a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Dim q = From i In a
Where i Mod 2 = 0
Select Function() i * i
For Each {|Conflict:$$sq|} In q
Console.Write({|Conflict:sq|}())
Next
End Sub
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Write")
result.AssertLabeledSpansAre("Conflict", "Write", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(542217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542217")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenAliases(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports A = X.Something
Imports {|Conflict:$$B|} = X.SomethingElse
Namespace X
Class Something
End Class
Class SomethingElse
End Class
End Namespace
</Document>
</Project>
</Workspace>, host:=host, renameTo:="A")
result.AssertLabeledSpansAre("Conflict", "A", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(530125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530125")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenImplicitVariableAndClass(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Explicit Off
Class X
End Class
Module M
Sub Main()
{|conflict:$$Y|} = 1
End Sub
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="X")
result.AssertLabeledSpansAre("conflict", "X", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(530038, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530038")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenEquallyNamedAlias(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports [|$$A|] = NS1.Something
Imports {|conflict1:Something|} = NS1
Namespace NS1
Class Something
Public Something()
End Class
End Namespace
Class Program
Dim a As {|noconflict:A|}
Dim q As {|conflict2:Something|}.{|conflict3:Something|}
End Class
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Something")
result.AssertLabeledSpansAre("conflict1", "Something", RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("conflict2", "NS1", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("conflict3", "Something", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("noconflict", "Something", RelatedLocationType.NoConflict)
End Using
End Sub
<Theory>
<WorkItem(610120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/610120")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenEquallyNamedPropertyAndItsParameter_1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class A
Public Property [|$$X|]({|declconflict:Y|} As Integer) As Integer
Get
Return 0
End Get
Set
End Set
End Property
End Class
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Y")
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(610120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/610120")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenEquallyNamedPropertyAndItsParameter_2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class A
Public Overridable Property [|X|]({|declconflict:Y|} As Integer) As Integer
Get
Return 0
End Get
Set
End Set
End Property
End Class
Public Class B
Inherits A
Public Overrides Property [|$$X|]({|declconflict:y|} As Integer) As Integer
Get
Return 0
End Get
Set
End Set
End Property
End Class
Public Class C
Inherits A
Public Overrides Property [|X|]({|declconflict:y|} As Integer) As Integer
Get
Return 0
End Get
Set
End Set
End Property
End Class
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Y")
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(610120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/610120")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenEquallyNamedPropertyAndItsParameter_3(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class A
Public Overridable Property {|declconflict:X|}([|$$Y|] As Integer) As Integer
Get
Return 0
End Get
Set
End Set
End Property
End Class
</Document>
</Project>
</Workspace>, host:=host, renameTo:="X")
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(608198, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608198"), WorkItem(798375, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/798375")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictInFieldInitializerOfFieldAndModuleNameResolvedThroughFullQualification(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Module [|$$M|] ' Rename M to X
Dim x As Action = Sub() Console.WriteLine({|stmt1:M|}.x)
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="X")
result.AssertLabeledSpansAre("stmt1", "Console.WriteLine(Global.X.x)", type:=RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory>
<WorkItem(528706, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528706")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictForForEachLoopVariableNotBindingToTypeAnyMore(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Namespace X
Module Program
Sub Main
For Each {|conflict:x|} In ""
Next
End Sub
End Module
End Namespace
Namespace X
Class [|$$X|] ' Rename X to M
End Class
End Namespace
</Document>
</Project>
</Workspace>, host:=host, renameTo:="M")
result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictForForEachLoopVariableAndRangeVariable_1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Imports System.Linq
Namespace X
Module Program
Sub Main
For Each {|ctrlvar:goo|} In {1, 2, 3}
Dim y As Integer = (From {|conflict:g|} In {{|broken:goo|}} Select g).First()
Console.WriteLine({|stmt:$$goo|})
Next
End Sub
End Module
End Namespace
</Document>
</Project>
</Workspace>, host:=host, renameTo:="g")
result.AssertLabeledSpansAre("ctrlvar", "g", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("broken", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt", "g", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<Theory>
<WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictForForEachLoopVariableAndRangeVariable_2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Imports System.Linq
Namespace X
Module Program
Sub Main
For Each {|ctrlvar:goo|} As Integer In {1, 2, 3}
Dim y As Integer = (From {|conflict:g|} In {{|broken:goo|}} Select g).First()
Console.WriteLine({|stmt:$$goo|})
Next
End Sub
End Module
End Namespace
</Document>
</Project>
</Workspace>, host:=host, renameTo:="g")
result.AssertLabeledSpansAre("ctrlvar", "g", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("broken", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt", "g", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<Theory>
<WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictForForEachLoopVariableAndRangeVariable_3(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Imports System.Linq
Namespace X
Module Program
Sub Main
Dim {|stmt1:goo|} as Integer
For Each {|ctrlvar:goo|} In {1, 2, 3}
Dim y As Integer = (From {|conflict:g|} In {{|broken:goo|}} Select g).First()
Console.WriteLine({|stmt2:$$goo|})
Next
End Sub
End Module
End Namespace
</Document>
</Project>
</Workspace>, host:=host, renameTo:="g")
result.AssertLabeledSpansAre("stmt1", "g", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("ctrlvar", "g", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("broken", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", "g", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<Theory>
<WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictForForEachLoopVariableAndRangeVariable_4(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Imports System.Linq
Namespace X
Module Program
Public [|goo|] as Integer
Sub Main
For Each Program.{|ctrlvar:goo|} In {1, 2, 3}
Dim y As Integer = (From g In {{|query:goo|}} Select g).First()
Console.WriteLine({|stmt:$$goo|})
Next
End Sub
End Module
End Namespace
</Document>
</Project>
</Workspace>, host:=host, renameTo:="g")
result.AssertLabeledSpansAre("ctrlvar", "g", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("query", "g", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt", "g", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<Theory>
<WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictForUsingVariableAndRangeVariable_1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Imports System.Linq
Namespace X
Module Program
Sub Main
Using {|usingstmt:v1|} = new Object, v2 as Object = new Object(), v3, v4 as new Object()
Dim o As Object = (From {|declconflict:c|} In {{|query:v1|}} Select c).First()
Console.WriteLine({|stmt:$$v1|})
End Using
End Sub
End Module
End Namespace
</Document>
</Project>
</Workspace>, host:=host, renameTo:="c")
result.AssertLabeledSpansAre("usingstmt", "c", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("query", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt", "c", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<Theory>
<WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictForUsingVariableAndRangeVariable_2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Namespace X
Module Program
Sub Main
Using {|usingstmt:v3|}, {|declconflict:v4|} as new Object()
Dim o As Object = (From c In {{|query:v3|}} Select c).First()
Console.WriteLine({|stmt:$$v3|})
End Using
End Sub
End Module
End Namespace
</Document>
</Project>
</Workspace>, host:=host, renameTo:="v4")
result.AssertLabeledSpansAre("usingstmt", "v4", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("query", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt", "v4", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<WpfTheory(Skip:="657210")>
<WorkItem(653311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/653311")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictForUsingVariableAndRangeVariable_3(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Namespace X
Module Program
Sub Main
Using {|usingstmt:v3|} as new Object()
Dim o As Object = (From c In {{|query:v3|}} Let {|declconflict:d|} = c Select {|declconflict:d|}).First()
Console.WriteLine({|stmt:$$v3|})
End Using
End Sub
End Module
End Namespace
</Document>
</Project>
</Workspace>, host:=host, renameTo:="d")
result.AssertLabeledSpansAre("usingstmt", "d", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("query", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt", "d", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictForCatchVariable_1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Namespace X
Module Program
Sub Main
Try
Catch {|catchstmt:$$x|} as Exception
dim {|declconflict:y|} = 23
End Try
End Sub
End Module
End Namespace
</Document>
</Project>
</Workspace>, host:=host, renameTo:="y")
result.AssertLabeledSpansAre("catchstmt", "y", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(529986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529986")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictBetweenTypeParametersInTypeDeclaration(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Goo(Of {|declconflict:T|} as {New}, [|$$U|])
End Class
</Document>
</Project>
</Workspace>, host:=host, renameTo:="T")
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(529986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529986")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictBetweenTypeParametersInMethodDeclaration_1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Goo
Public Sub M(Of {|declconflict:T|} as {New}, [|$$U|])()
End Sub
End Class
</Document>
</Project>
</Workspace>, host:=host, renameTo:="T")
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(529986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529986")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictBetweenTypeParametersInMethodDeclaration_2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Goo
Public Sub M(Of {|declconflict:[T]|} as {New}, [|$$U|])()
End Sub
End Class
</Document>
</Project>
</Workspace>, host:=host, renameTo:="t")
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(529986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529986")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictBetweenTypeParameterAndMember_1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Goo(Of {|declconflict:[T]|})
Public Sub [|$$M|]()
End Sub
End Class
</Document>
</Project>
</Workspace>, host:=host, renameTo:="t")
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(529986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529986")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictBetweenTypeParameterAndMember_2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Goo(Of {|declconflict:[T]|})
Public [|$$M|] as Integer = 23
End Class
</Document>
</Project>
</Workspace>, host:=host, renameTo:="t")
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(658437, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658437")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictBetweenEscapedForEachControlVariableAndQueryRangeVariable(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System.Linq
Module Program
Sub Main(args As String())
For Each {|stmt1:goo|} In {1, 2, 3}
Dim x As Integer = (From {|declconflict:g|} In {{|stmt3:goo|}} Select g).First()
Console.WriteLine({|stmt2:$$goo|})
Next
End Sub
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="[g]")
result.AssertLabeledSpansAre("stmt1", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt3", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(658801, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658801")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_OverridingImplicitlyUsedMethod(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Option Infer On
Imports System
Class A
Public Property current As Integer
Public Function MOVENext() As Boolean
Return False
End Function
Public Function GetEnumerator() As C
Return Me
End Function
End Class
Class C
Inherits A
Shared Sub Main()
For Each x In New C()
Next
End Sub
Public Sub {|possibleImplicitConflict:$$Goo|}() ' Rename Goo to MoveNext
End Sub
End Class
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="movenext")
result.AssertLabeledSpansAre("possibleImplicitConflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(682669, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682669")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_OverridingImplicitlyUsedMethod_1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><() ' Rename Goo to MoveNext
End Sub
End Class
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="movenext")
End Using
End Sub
<WorkItem(682669, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682669")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_OverridingImplicitlyUsedMethod_2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Option Infer On
Imports System
Class A
Public Property current As Integer
Public Function MOVENext(of T)() As Boolean
Return False
End Function
Public Function GetEnumerator() As C
Return Me
End Function
End Class
Class C
Inherits A
Shared Sub Main()
End Sub
Public Sub [|$$Goo|]() ' Rename Goo to MoveNext
End Sub
End Class
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="movenext")
End Using
End Sub
<WorkItem(851604, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/851604")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictInsideSimpleArgument(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System.ComponentModel
Imports System.Reflection
Class C
Const {|first:$$M|} As MemberTypes = MemberTypes.Method
Delegate Sub D(<DefaultValue({|second:M|})> x As Object);
End Class
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Method")
result.AssertLabeledSpansAre("first", "Method", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("second", "C.Method", type:=RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(18566, "https://github.com/dotnet/roslyn/issues/18566")>
Public Sub ParameterInPartialMethodDefinitionConflictingWithLocalInPartialMethodImplementation(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Partial Class C
Partial Private Sub M({|parameter0:$$x|} As Integer)
End Sub
End Class
</Document>
<Document>
Partial Class C
Private Sub M({|parameter1:x|} As Integer)
Dim {|local0:y|} = 1
End Sub
End Class
</Document>
</Project>
</Workspace>, host:=host, renameTo:="y")
result.AssertLabeledSpansAre("parameter0", "y", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("parameter1", "y", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("local0", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(941271, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/941271")>
Public Sub AsNewClauseSpeculationResolvesConflicts(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Main
Private T As {|class0:$$Test|} = Nothing
End Class
Public Class {|class1:Test|}
Private Rnd As New {|classConflict:Random|}
End Class
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Random")
result.AssertLabeledSpansAre("class0", "Random", RelatedLocationType.ResolvedReferenceConflict)
result.AssertLabeledSpansAre("class1", "Random", RelatedLocationType.ResolvedReferenceConflict)
result.AssertLabeledSpansAre("classConflict", "System.Random", type:=RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Remote.Testing
Imports Microsoft.CodeAnalysis.Rename.ConflictEngine
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.VisualBasic
<[UseExportProvider]>
Public Class DeclarationConflictTests
Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper
Public Sub New(outputHelper As Abstractions.ITestOutputHelper)
_outputHelper = outputHelper
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenFields(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module GooModule
Dim [|$$goo|] As Integer
Dim {|Conflict:bar|} As Integer
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="bar")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenFieldAndMethod(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module GooModule
Dim [|$$goo|] As Integer
Sub {|Conflict:bar|}()
End Module
</Document>
</Project>
</Workspace>, host:=host,
renameTo:="bar")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenTwoMethodsWithSameSignature(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module GooModule
Sub [|$$goo|]()
End Sub
Sub {|Conflict:bar|}()
End Sub
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="bar")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenTwoParameters(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module GooModule
Sub f([|$$goo|] As Integer, {|Conflict:bar|} As Integer)
End Sub
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="bar")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub NoConflictBetweenMethodsWithDifferentSignatures(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module GooModule
Sub [|$$goo|]()
End Sub
Sub bar(parameter As Integer)
End Sub
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="bar")
End Using
End Sub
<Theory>
<WorkItem(543245, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543245")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenTwoLocals(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
Sub Main(args As String())
Dim {|stmt1:$$i|} = 1
Dim {|Conflict:j|} = 2
End Sub
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="j")
result.AssertLabeledSpansAre("stmt1", "j", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(543245, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543245")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenLocalAndParameter(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
Sub Main({|Conflict:args|} As String())
Dim {|stmt1:$$i|} = 1
End Sub
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="args")
result.AssertLabeledSpansAre("stmt1", "args", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(545859, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545859")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenQueryVariableAndParameter(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
Sub Main({|Conflict:args|} As String())
Dim z = From {|stmt1:$$x|} In args
End Sub
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="args")
result.AssertLabeledSpansAre("stmt1", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(545859, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545859")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenTwoQueryVariables(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
Sub Main(args As String())
Dim z = From {|Conflict:x|} In args
From {|stmt1:$$y|} In args
End Sub
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="x")
result.AssertLabeledSpansAre("stmt1", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(543654, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543654")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenLambdaParametersInsideMethod(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Module M1
Sub Main()
Dim y = Sub({|Conflict:c|}) Call (Sub(a, {|stmt1:$$b|}) Exit Sub)(c)
End Sub
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="c")
result.AssertLabeledSpansAre("stmt1", "c", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(543654, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543654")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenLambdaParametersInFieldInitializer(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Module M1
Dim y = Sub({|Conflict:c|}) Call (Sub({|stmt:$$b|}) Exit Sub)(c)
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="c")
result.AssertLabeledSpansAre("stmt", "c", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(543654, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543654")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub NoConflictBetweenLambdaParameterAndField(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Module M1
Dim y = Sub({|fieldinit:$$c|}) Exit Sub
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="y")
result.AssertLabeledSpansAre("fieldinit", "y", RelatedLocationType.NoConflict)
End Using
End Sub
<Theory>
<WorkItem(543407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543407")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenLabels(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Program
Sub Main()
{|Conflict:Goo|}:
[|$$Bar|]:
Dim f = Sub()
Goo:
End Sub
End Sub
End Class
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Goo")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(543308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543308")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenMethodsDifferingByByRef(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
Sub {|Conflict:a|}(x As Integer)
End Sub
Sub [|$$c|](ByRef x As Integer)
End Sub
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="a")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(543308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543308")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenMethodsDifferingByOptional(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
Sub {|Conflict:a|}(x As Integer)
End Sub
Sub [|$$d|](x As Integer, Optional y As Integer = 0)
End Sub
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="a")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(543308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543308")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub NoConflictBetweenMethodsDifferingByArity(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Module Program
Sub a(Of T)(x As Integer)
End Sub
Sub [|$$d|](x As Integer, Optional y As Integer = 0)
End Sub
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="a")
End Using
End Sub
<Theory>
<WorkItem(546902, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546902")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenImplicitlyDeclaredLocalAndNamespace(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Explicit Off
Module Program
Sub Main()
__ = {|Conflict1:$$Google|}
{|Conflict2:Google|} = __
End Sub
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Microsoft")
result.AssertLabeledSpansAre("Conflict1", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("Conflict2", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(529556, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529556")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenImplicitlyDeclaredLocalAndAndGlobalFunction(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports Microsoft.VisualBasic
Module Module1
Sub Main()
Dim a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Dim q = From i In a
Where i Mod 2 = 0
Select Function() i * i
For Each {|Conflict:$$sq|} In q
Console.Write({|Conflict:sq|}())
Next
End Sub
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Write")
result.AssertLabeledSpansAre("Conflict", "Write", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(542217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542217")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenAliases(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports A = X.Something
Imports {|Conflict:$$B|} = X.SomethingElse
Namespace X
Class Something
End Class
Class SomethingElse
End Class
End Namespace
</Document>
</Project>
</Workspace>, host:=host, renameTo:="A")
result.AssertLabeledSpansAre("Conflict", "A", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(530125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530125")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenImplicitVariableAndClass(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Explicit Off
Class X
End Class
Module M
Sub Main()
{|conflict:$$Y|} = 1
End Sub
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="X")
result.AssertLabeledSpansAre("conflict", "X", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(530038, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530038")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenEquallyNamedAlias(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports [|$$A|] = NS1.Something
Imports {|conflict1:Something|} = NS1
Namespace NS1
Class Something
Public Something()
End Class
End Namespace
Class Program
Dim a As {|noconflict:A|}
Dim q As {|conflict2:Something|}.{|conflict3:Something|}
End Class
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Something")
result.AssertLabeledSpansAre("conflict1", "Something", RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("conflict2", "NS1", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("conflict3", "Something", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("noconflict", "Something", RelatedLocationType.NoConflict)
End Using
End Sub
<Theory>
<WorkItem(610120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/610120")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenEquallyNamedPropertyAndItsParameter_1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class A
Public Property [|$$X|]({|declconflict:Y|} As Integer) As Integer
Get
Return 0
End Get
Set
End Set
End Property
End Class
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Y")
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(610120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/610120")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenEquallyNamedPropertyAndItsParameter_2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class A
Public Overridable Property [|X|]({|declconflict:Y|} As Integer) As Integer
Get
Return 0
End Get
Set
End Set
End Property
End Class
Public Class B
Inherits A
Public Overrides Property [|$$X|]({|declconflict:y|} As Integer) As Integer
Get
Return 0
End Get
Set
End Set
End Property
End Class
Public Class C
Inherits A
Public Overrides Property [|X|]({|declconflict:y|} As Integer) As Integer
Get
Return 0
End Get
Set
End Set
End Property
End Class
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Y")
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(610120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/610120")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenEquallyNamedPropertyAndItsParameter_3(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class A
Public Overridable Property {|declconflict:X|}([|$$Y|] As Integer) As Integer
Get
Return 0
End Get
Set
End Set
End Property
End Class
</Document>
</Project>
</Workspace>, host:=host, renameTo:="X")
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(608198, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608198"), WorkItem(798375, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/798375")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictInFieldInitializerOfFieldAndModuleNameResolvedThroughFullQualification(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Module [|$$M|] ' Rename M to X
Dim x As Action = Sub() Console.WriteLine({|stmt1:M|}.x)
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="X")
result.AssertLabeledSpansAre("stmt1", "Console.WriteLine(Global.X.x)", type:=RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory>
<WorkItem(528706, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528706")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictForForEachLoopVariableNotBindingToTypeAnyMore(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Namespace X
Module Program
Sub Main
For Each {|conflict:x|} In ""
Next
End Sub
End Module
End Namespace
Namespace X
Class [|$$X|] ' Rename X to M
End Class
End Namespace
</Document>
</Project>
</Workspace>, host:=host, renameTo:="M")
result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictForForEachLoopVariableAndRangeVariable_1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Imports System.Linq
Namespace X
Module Program
Sub Main
For Each {|ctrlvar:goo|} In {1, 2, 3}
Dim y As Integer = (From {|conflict:g|} In {{|broken:goo|}} Select g).First()
Console.WriteLine({|stmt:$$goo|})
Next
End Sub
End Module
End Namespace
</Document>
</Project>
</Workspace>, host:=host, renameTo:="g")
result.AssertLabeledSpansAre("ctrlvar", "g", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("broken", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt", "g", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<Theory>
<WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictForForEachLoopVariableAndRangeVariable_2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Imports System.Linq
Namespace X
Module Program
Sub Main
For Each {|ctrlvar:goo|} As Integer In {1, 2, 3}
Dim y As Integer = (From {|conflict:g|} In {{|broken:goo|}} Select g).First()
Console.WriteLine({|stmt:$$goo|})
Next
End Sub
End Module
End Namespace
</Document>
</Project>
</Workspace>, host:=host, renameTo:="g")
result.AssertLabeledSpansAre("ctrlvar", "g", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("broken", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt", "g", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<Theory>
<WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictForForEachLoopVariableAndRangeVariable_3(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Imports System.Linq
Namespace X
Module Program
Sub Main
Dim {|stmt1:goo|} as Integer
For Each {|ctrlvar:goo|} In {1, 2, 3}
Dim y As Integer = (From {|conflict:g|} In {{|broken:goo|}} Select g).First()
Console.WriteLine({|stmt2:$$goo|})
Next
End Sub
End Module
End Namespace
</Document>
</Project>
</Workspace>, host:=host, renameTo:="g")
result.AssertLabeledSpansAre("stmt1", "g", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("ctrlvar", "g", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("broken", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", "g", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<Theory>
<WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictForForEachLoopVariableAndRangeVariable_4(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Imports System.Linq
Namespace X
Module Program
Public [|goo|] as Integer
Sub Main
For Each Program.{|ctrlvar:goo|} In {1, 2, 3}
Dim y As Integer = (From g In {{|query:goo|}} Select g).First()
Console.WriteLine({|stmt:$$goo|})
Next
End Sub
End Module
End Namespace
</Document>
</Project>
</Workspace>, host:=host, renameTo:="g")
result.AssertLabeledSpansAre("ctrlvar", "g", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("query", "g", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt", "g", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<Theory>
<WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictForUsingVariableAndRangeVariable_1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Imports System.Linq
Namespace X
Module Program
Sub Main
Using {|usingstmt:v1|} = new Object, v2 as Object = new Object(), v3, v4 as new Object()
Dim o As Object = (From {|declconflict:c|} In {{|query:v1|}} Select c).First()
Console.WriteLine({|stmt:$$v1|})
End Using
End Sub
End Module
End Namespace
</Document>
</Project>
</Workspace>, host:=host, renameTo:="c")
result.AssertLabeledSpansAre("usingstmt", "c", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("query", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt", "c", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<Theory>
<WorkItem(530476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530476")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictForUsingVariableAndRangeVariable_2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Namespace X
Module Program
Sub Main
Using {|usingstmt:v3|}, {|declconflict:v4|} as new Object()
Dim o As Object = (From c In {{|query:v3|}} Select c).First()
Console.WriteLine({|stmt:$$v3|})
End Using
End Sub
End Module
End Namespace
</Document>
</Project>
</Workspace>, host:=host, renameTo:="v4")
result.AssertLabeledSpansAre("usingstmt", "v4", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("query", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt", "v4", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<WpfTheory(Skip:="657210")>
<WorkItem(653311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/653311")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictForUsingVariableAndRangeVariable_3(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Namespace X
Module Program
Sub Main
Using {|usingstmt:v3|} as new Object()
Dim o As Object = (From c In {{|query:v3|}} Let {|declconflict:d|} = c Select {|declconflict:d|}).First()
Console.WriteLine({|stmt:$$v3|})
End Using
End Sub
End Module
End Namespace
</Document>
</Project>
</Workspace>, host:=host, renameTo:="d")
result.AssertLabeledSpansAre("usingstmt", "d", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("query", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt", "d", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictForCatchVariable_1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Option Infer On
Namespace X
Module Program
Sub Main
Try
Catch {|catchstmt:$$x|} as Exception
dim {|declconflict:y|} = 23
End Try
End Sub
End Module
End Namespace
</Document>
</Project>
</Workspace>, host:=host, renameTo:="y")
result.AssertLabeledSpansAre("catchstmt", "y", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(529986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529986")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictBetweenTypeParametersInTypeDeclaration(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Goo(Of {|declconflict:T|} as {New}, [|$$U|])
End Class
</Document>
</Project>
</Workspace>, host:=host, renameTo:="T")
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(529986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529986")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictBetweenTypeParametersInMethodDeclaration_1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Goo
Public Sub M(Of {|declconflict:T|} as {New}, [|$$U|])()
End Sub
End Class
</Document>
</Project>
</Workspace>, host:=host, renameTo:="T")
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(529986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529986")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictBetweenTypeParametersInMethodDeclaration_2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Goo
Public Sub M(Of {|declconflict:[T]|} as {New}, [|$$U|])()
End Sub
End Class
</Document>
</Project>
</Workspace>, host:=host, renameTo:="t")
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(529986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529986")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictBetweenTypeParameterAndMember_1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Goo(Of {|declconflict:[T]|})
Public Sub [|$$M|]()
End Sub
End Class
</Document>
</Project>
</Workspace>, host:=host, renameTo:="t")
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(529986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529986")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictBetweenTypeParameterAndMember_2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Goo(Of {|declconflict:[T]|})
Public [|$$M|] as Integer = 23
End Class
</Document>
</Project>
</Workspace>, host:=host, renameTo:="t")
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(658437, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658437")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_ConflictBetweenEscapedForEachControlVariableAndQueryRangeVariable(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System.Linq
Module Program
Sub Main(args As String())
For Each {|stmt1:goo|} In {1, 2, 3}
Dim x As Integer = (From {|declconflict:g|} In {{|stmt3:goo|}} Select g).First()
Console.WriteLine({|stmt2:$$goo|})
Next
End Sub
End Module
</Document>
</Project>
</Workspace>, host:=host, renameTo:="[g]")
result.AssertLabeledSpansAre("stmt1", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt3", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("declconflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(658801, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/658801")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_OverridingImplicitlyUsedMethod(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Option Infer On
Imports System
Class A
Public Property current As Integer
Public Function MOVENext() As Boolean
Return False
End Function
Public Function GetEnumerator() As C
Return Me
End Function
End Class
Class C
Inherits A
Shared Sub Main()
For Each x In New C()
Next
End Sub
Public Sub {|possibleImplicitConflict:$$Goo|}() ' Rename Goo to MoveNext
End Sub
End Class
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="movenext")
result.AssertLabeledSpansAre("possibleImplicitConflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(682669, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682669")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_OverridingImplicitlyUsedMethod_1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><() ' Rename Goo to MoveNext
End Sub
End Class
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="movenext")
End Using
End Sub
<WorkItem(682669, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682669")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub VB_OverridingImplicitlyUsedMethod_2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document><![CDATA[
Option Infer On
Imports System
Class A
Public Property current As Integer
Public Function MOVENext(of T)() As Boolean
Return False
End Function
Public Function GetEnumerator() As C
Return Me
End Function
End Class
Class C
Inherits A
Shared Sub Main()
End Sub
Public Sub [|$$Goo|]() ' Rename Goo to MoveNext
End Sub
End Class
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="movenext")
End Using
End Sub
<WorkItem(851604, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/851604")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictInsideSimpleArgument(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System.ComponentModel
Imports System.Reflection
Class C
Const {|first:$$M|} As MemberTypes = MemberTypes.Method
Delegate Sub D(<DefaultValue({|second:M|})> x As Object);
End Class
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Method")
result.AssertLabeledSpansAre("first", "Method", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("second", "C.Method", type:=RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(18566, "https://github.com/dotnet/roslyn/issues/18566")>
Public Sub ParameterInPartialMethodDefinitionConflictingWithLocalInPartialMethodImplementation(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Partial Class C
Partial Private Sub M({|parameter0:$$x|} As Integer)
End Sub
End Class
</Document>
<Document>
Partial Class C
Private Sub M({|parameter1:x|} As Integer)
Dim {|local0:y|} = 1
End Sub
End Class
</Document>
</Project>
</Workspace>, host:=host, renameTo:="y")
result.AssertLabeledSpansAre("parameter0", "y", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("parameter1", "y", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("local0", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(941271, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/941271")>
Public Sub AsNewClauseSpeculationResolvesConflicts(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Main
Private T As {|class0:$$Test|} = Nothing
End Class
Public Class {|class1:Test|}
Private Rnd As New {|classConflict:Random|}
End Class
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Random")
result.AssertLabeledSpansAre("class0", "Random", RelatedLocationType.ResolvedReferenceConflict)
result.AssertLabeledSpansAre("class1", "Random", RelatedLocationType.ResolvedReferenceConflict)
result.AssertLabeledSpansAre("classConflict", "System.Random", type:=RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenAwaitUsingTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
[CompilerTrait(CompilerFeature.AsyncStreams)]
public class CodeGenAwaitUsingTests : CSharpTestBase
{
[Fact]
public void TestWithCSharp7_3()
{
string source = @"
class C : System.IAsyncDisposable
{
async System.Threading.Tasks.Task M()
{
await using (var x = new C())
{
}
}
public System.Threading.Tasks.ValueTask DisposeAsync()
{
throw null;
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (6,9): error CS8652: The feature 'asynchronous using' is not available in C# 7.3. Please use language version 8.0 or greater.
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "await").WithArguments("asynchronous using", "8.0").WithLocation(6, 9)
);
}
[Fact]
public void TestInNonAsyncVoidMethod()
{
string source = @"
class C : System.IAsyncDisposable
{
void M()
{
await using (var x = new C())
{
return;
}
}
public System.Threading.Tasks.ValueTask DisposeAsync()
{
throw null;
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition });
comp.VerifyDiagnostics(
// (6,9): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await").WithLocation(6, 9)
);
}
[Fact]
public void TestInNonAsyncMethodReturningInt()
{
string source = @"
class C : System.IAsyncDisposable
{
int M()
{
await using (var x = new C())
{
return 1;
}
}
public System.Threading.Tasks.ValueTask DisposeAsync()
{
throw null;
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition });
comp.VerifyDiagnostics(
// (6,9): error CS4032: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task<int>'.
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_BadAwaitWithoutAsyncMethod, "await").WithArguments("int").WithLocation(6, 9)
);
}
[Fact]
public void TestInNonAsyncAnonymousMethod()
{
string source = @"
class C : System.IAsyncDisposable
{
void M()
{
System.Action x = () =>
{
await using (var y = new C())
{
return;
}
};
}
public System.Threading.Tasks.ValueTask DisposeAsync()
{
throw null;
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition });
comp.VerifyDiagnostics(
// (8,13): error CS4034: The 'await' operator can only be used within an async lambda expression. Consider marking this lambda expression with the 'async' modifier.
// await using (var y = new C())
Diagnostic(ErrorCode.ERR_BadAwaitWithoutAsyncLambda, "await").WithArguments("lambda expression").WithLocation(8, 13)
);
}
[Fact]
public void TestWithTaskReturningDisposeAsync()
{
string source = @"
using System.Threading.Tasks;
class C : System.IAsyncDisposable
{
public static async Task Main()
{
await using (var y = new C()) { }
}
public async Task DisposeAsync() { }
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (3,11): error CS0738: 'C' does not implement interface member 'IAsyncDisposable.DisposeAsync()'. 'C.DisposeAsync()' cannot implement 'IAsyncDisposable.DisposeAsync()' because it does not have the matching return type of 'ValueTask'.
// class C : System.IAsyncDisposable
Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "System.IAsyncDisposable").WithArguments("C", "System.IAsyncDisposable.DisposeAsync()", "C.DisposeAsync()", "System.Threading.Tasks.ValueTask").WithLocation(3, 11),
// (9,23): 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.
// public async Task DisposeAsync() { }
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "DisposeAsync").WithLocation(9, 23)
);
}
[Fact]
public void TestInAsyncAnonymousMethod()
{
string source = @"
using System.Threading.Tasks;
class C : System.IAsyncDisposable
{
C()
{
System.Console.Write(""C "");
}
public static async Task Main()
{
System.Func<Task> x = async () =>
{
await using (var y = new C())
{
System.Console.Write(""body "");
}
System.Console.Write(""end"");
};
await x();
}
public async ValueTask DisposeAsync()
{
System.Console.Write(""DisposeAsync1 "");
await Task.Yield();
System.Console.Write(""DisposeAsync2 "");
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "C body DisposeAsync1 DisposeAsync2 end");
}
[Fact]
public void TestInUnsafeRegion()
{
string source = @"
class C : System.IAsyncDisposable
{
async System.Threading.Tasks.Task<int> M<T>()
{
unsafe
{
await using (var x = new C())
{
return 1;
}
}
}
public System.Threading.Tasks.ValueTask DisposeAsync()
{
throw null;
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.UnsafeDebugDll);
comp.VerifyDiagnostics(
// (8,13): error CS4004: Cannot await in an unsafe context
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await").WithLocation(8, 13)
);
}
[Fact]
public void TestInLock()
{
string source = @"
class C : System.IAsyncDisposable
{
async System.Threading.Tasks.Task<int> M<T>()
{
lock(this)
{
await using (var x = new C())
{
return 1;
}
}
}
public System.Threading.Tasks.ValueTask DisposeAsync()
{
throw null;
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition });
comp.VerifyDiagnostics(
// (8,13): error CS1996: Cannot await in the body of a lock statement
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_BadAwaitInLock, "await").WithLocation(8, 13)
);
}
[Fact]
public void TestWithObsoleteDisposeAsync()
{
string source = @"
class C : System.IAsyncDisposable
{
public static async System.Threading.Tasks.Task Main()
{
await using (var x = new C())
{
}
}
[System.Obsolete]
public async System.Threading.Tasks.ValueTask DisposeAsync()
{
await System.Threading.Tasks.Task.Yield();
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
// https://github.com/dotnet/roslyn/issues/30257 Confirm whether this behavior is ok (currently matching behavior of obsolete Dispose in non-async using)
}
[Fact]
public void TestWithObsoleteDispose()
{
string source = @"
class C : System.IDisposable
{
public static void Main()
{
using (var x = new C())
{
}
}
[System.Obsolete]
public void Dispose()
{
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition });
comp.VerifyDiagnostics();
}
[Fact]
public void TestInCatchBlock()
{
string source = @"
class C : System.IAsyncDisposable
{
public static async System.Threading.Tasks.Task Main()
{
try
{
System.Console.Write(""try "");
throw new System.ArgumentNullException();
}
catch (System.ArgumentNullException)
{
await using (var x = new C())
{
System.Console.Write(""using "");
}
System.Console.Write(""end"");
}
}
public async System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write($""dispose_start "");
await System.Threading.Tasks.Task.Yield();
System.Console.Write($""dispose_end "");
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "try using dispose_start dispose_end end");
}
[Fact]
public void MissingAwaitInAsyncMethod()
{
string source = @"
class C
{
public static async System.Threading.Tasks.Task Main()
{
System.Action a = () =>
{
System.Action b = async () =>
{
await local();
await using (null) { }
}; // these awaits don't count towards Main method
};
async System.Threading.Tasks.Task local()
{
await local();
await using (null) { }
// neither do these
}
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition });
comp.VerifyDiagnostics(
// (4,53): 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.
// public static async System.Threading.Tasks.Task Main()
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Main").WithLocation(4, 53)
);
}
[Fact]
public void MissingAwaitInAsyncMethod2()
{
string source = @"
class C
{
public static void Main()
{
System.Action lambda1 = async () =>
{
System.Action b = async () =>
{
await local();
await using (null) { }
}; // these awaits don't count towards lambda
};
System.Action lambda2 = async () => await local2(); // this await counts towards lambda
async System.Threading.Tasks.Task local()
{
System.Func<System.Threading.Tasks.Task> c = innerLocal;
async System.Threading.Tasks.Task innerLocal()
{
await local();
await using (null) { }
// these awaits don't count towards lambda either
}
}
async System.Threading.Tasks.Task local2() => await local(); // this await counts towards local function
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition });
comp.VerifyDiagnostics(
// (17,43): 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.
// async System.Threading.Tasks.Task local()
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "local").WithLocation(17, 43),
// (6,42): 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.
// System.Action lambda1 = async () =>
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "=>").WithLocation(6, 42)
);
}
[Fact]
public void TestInFinallyBlock()
{
string source = @"
class C : System.IAsyncDisposable
{
static async System.Threading.Tasks.Task<int> Main()
{
try
{
}
finally
{
await using (var x = new C())
{
System.Console.Write(""using "");
}
}
System.Console.Write(""return"");
return 1;
}
public async System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write($""dispose_start "");
await System.Threading.Tasks.Task.Yield();
System.Console.Write($""dispose_end "");
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "using dispose_start dispose_end return");
}
[Fact]
public void TestThrowingDisposeAsync()
{
string source = @"
class C : System.IAsyncDisposable
{
static async System.Threading.Tasks.Task Main()
{
try
{
await using (var x = new C())
{
System.Console.Write(""using "");
}
}
catch (System.Exception e)
{
System.Console.Write($""caught {e.Message}"");
return;
}
System.Console.Write(""SKIPPED"");
}
public async System.Threading.Tasks.ValueTask DisposeAsync()
{
bool b = true;
if (b) throw new System.Exception(""message"");
System.Console.Write(""SKIPPED"");
await System.Threading.Tasks.Task.Yield();
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "using caught message");
}
[Fact]
public void TestRegularAwaitInFinallyBlock()
{
string source = @"
using System.Threading.Tasks;
class C
{
static async Task<int> Main()
{
try
{
}
finally
{
System.Console.Write(""before "");
await Task.Yield();
System.Console.Write(""after"");
}
return 1;
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "before after");
}
[Fact]
public void TestMissingIAsyncDisposable()
{
string source = @"
class C
{
async System.Threading.Tasks.Task<int> M()
{
await using (new C())
{
}
await using (var x = new C())
{
return 1;
}
}
}
";
var comp = CreateCompilationWithTasksExtensions(source);
comp.VerifyDiagnostics(
// (6,9): error CS0518: Predefined type 'System.IAsyncDisposable' is not defined or imported
// await using (new C())
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.IAsyncDisposable").WithLocation(6, 9),
// (6,22): error CS8410: 'C': type used in an async using statement must be implicitly convertible to 'System.IAsyncDisposable'
// await using (new C())
Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "new C()").WithArguments("C").WithLocation(6, 22),
// (9,9): error CS0518: Predefined type 'System.IAsyncDisposable' is not defined or imported
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.IAsyncDisposable").WithLocation(9, 9),
// (9,22): error CS8410: 'C': type used in an async using statement must be implicitly convertible to 'System.IAsyncDisposable'
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "var x = new C()").WithArguments("C").WithLocation(9, 22)
);
}
[Fact]
public void TestMissingIAsyncDisposableAndMissingValueTaskAndMissingAsync()
{
string source = @"
class C
{
System.Threading.Tasks.Task<int> M()
{
await using (new C())
{
}
await using (var x = new C())
{
return 1;
}
}
}
";
var comp = CreateCompilationWithMscorlib46(source);
comp.MakeTypeMissing(WellKnownType.System_Threading_Tasks_ValueTask);
comp.VerifyDiagnostics(
// (6,9): error CS0518: Predefined type 'System.IAsyncDisposable' is not defined or imported
// await using (new C())
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.IAsyncDisposable").WithLocation(6, 9),
// (6,9): error CS4032: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task<Task<int>>'.
// await using (new C())
Diagnostic(ErrorCode.ERR_BadAwaitWithoutAsyncMethod, "await").WithArguments("System.Threading.Tasks.Task<int>").WithLocation(6, 9),
// (6,22): error CS8410: 'C': type used in an async using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method.
// await using (new C())
Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "new C()").WithArguments("C").WithLocation(6, 22),
// (9,9): error CS0518: Predefined type 'System.IAsyncDisposable' is not defined or imported
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.IAsyncDisposable").WithLocation(9, 9),
// (9,9): error CS4032: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task<Task<int>>'.
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_BadAwaitWithoutAsyncMethod, "await").WithArguments("System.Threading.Tasks.Task<int>").WithLocation(9, 9),
// (9,22): error CS8410: 'C': type used in an async using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method.
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "var x = new C()").WithArguments("C").WithLocation(9, 22),
// (11,20): error CS0029: Cannot implicitly convert type 'int' to 'System.Threading.Tasks.Task<int>'
// return 1;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "System.Threading.Tasks.Task<int>").WithLocation(11, 20)
);
}
[Fact]
public void TestMissingIDisposable()
{
string source = @"
class C
{
int M()
{
using (new C())
{
}
using (var x = new C())
{
return 1;
}
}
}
";
var comp = CreateCompilationWithMscorlib46(source);
comp.MakeTypeMissing(SpecialType.System_IDisposable);
comp.VerifyEmitDiagnostics(
// (6,9): error CS0518: Predefined type 'System.IDisposable' is not defined or imported
// using (new C())
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "using").WithArguments("System.IDisposable").WithLocation(6, 9),
// (6,16): error CS1674: 'C': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using (new C())
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "new C()").WithArguments("C").WithLocation(6, 16),
// (9,9): error CS0518: Predefined type 'System.IDisposable' is not defined or imported
// using (var x = new C())
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "using").WithArguments("System.IDisposable").WithLocation(9, 9),
// (9,16): error CS1674: 'C': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using (var x = new C())
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var x = new C()").WithArguments("C").WithLocation(9, 16)
);
}
[Fact]
public void TestMissingDisposeAsync()
{
string source = @"
namespace System
{
public interface IAsyncDisposable
{
// missing DisposeAsync
}
}
class C : System.IAsyncDisposable
{
async System.Threading.Tasks.Task<int> M()
{
await using (new C()) { }
await using (var x = new C()) { return 1; }
}
}
";
var comp = CreateCompilationWithTasksExtensions(source);
comp.VerifyDiagnostics();
comp.VerifyEmitDiagnostics(
// (13,9): error CS0656: Missing compiler required member 'System.IAsyncDisposable.DisposeAsync'
// await using (new C()) { }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "await").WithArguments("System.IAsyncDisposable", "DisposeAsync").WithLocation(13, 9),
// (14,9): error CS0656: Missing compiler required member 'System.IAsyncDisposable.DisposeAsync'
// await using (var x = new C()) { return 1; }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "await").WithArguments("System.IAsyncDisposable", "DisposeAsync").WithLocation(14, 9)
);
}
[Fact]
public void TestMissingDispose()
{
string source = @"
class C : System.IDisposable
{
int M()
{
using (new C()) { }
using (var x = new C()) { return 1; }
}
public void Dispose()
{
throw null;
}
}
";
var comp = CreateCompilationWithTasksExtensions(source);
comp.MakeMemberMissing(SpecialMember.System_IDisposable__Dispose);
comp.VerifyEmitDiagnostics(
// (6,9): error CS0656: Missing compiler required member 'System.IDisposable.Dispose'
// using (new C()) { }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "using (new C()) { }").WithArguments("System.IDisposable", "Dispose").WithLocation(6, 9),
// (7,9): error CS0656: Missing compiler required member 'System.IDisposable.Dispose'
// using (var x = new C()) { return 1; }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "using (var x = new C()) { return 1; }").WithArguments("System.IDisposable", "Dispose").WithLocation(7, 9)
);
}
[Fact]
public void TestBadDisposeAsync()
{
string source = @"
namespace System
{
public interface IAsyncDisposable
{
int DisposeAsync(); // bad return type
}
}
class C : System.IAsyncDisposable
{
async System.Threading.Tasks.Task<int> M<T>()
{
await using (new C()) { }
await using (var x = new C()) { return 1; }
}
public int DisposeAsync()
{
throw null;
}
}
";
var comp = CreateCompilationWithTasksExtensions(source);
comp.VerifyDiagnostics();
comp.VerifyEmitDiagnostics(
// (13,9): error CS0656: Missing compiler required member 'System.IAsyncDisposable.DisposeAsync'
// await using (new C()) { }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "await").WithArguments("System.IAsyncDisposable", "DisposeAsync").WithLocation(13, 9),
// (14,9): error CS0656: Missing compiler required member 'System.IAsyncDisposable.DisposeAsync'
// await using (var x = new C()) { return 1; }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "await").WithArguments("System.IAsyncDisposable", "DisposeAsync").WithLocation(14, 9)
);
}
[Fact]
public void TestMissingTaskType()
{
string lib_cs = @"
public class Base : System.IAsyncDisposable
{
public System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write(""DisposeAsync"");
return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask);
}
}
";
string comp_cs = @"
public class C : Base
{
public static async System.Threading.Tasks.Task<int> Main()
{
await using (var x = new C())
{
System.Console.Write(""body "");
return 1;
}
}
}
";
var libComp = CreateCompilationWithTasksExtensions(lib_cs + IAsyncDisposableDefinition);
var comp = CreateCompilationWithTasksExtensions(comp_cs, references: new[] { libComp.EmitToImageReference() }, options: TestOptions.DebugExe);
comp.MakeTypeMissing(WellKnownType.System_Threading_Tasks_ValueTask);
comp.VerifyDiagnostics(
// (6,9): error CS0518: Predefined type 'System.Threading.Tasks.ValueTask' is not defined or imported
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.Threading.Tasks.ValueTask").WithLocation(6, 9)
);
}
[Fact]
public void TestWithDeclaration()
{
string source = @"
class C : System.IAsyncDisposable, System.IDisposable
{
public static async System.Threading.Tasks.Task<int> Main()
{
await using (var x = new C())
{
System.Console.Write(""body "");
return 1;
}
}
public System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write(""DisposeAsync"");
return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask);
}
public void Dispose()
{
System.Console.Write(""IGNORED"");
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "body DisposeAsync");
}
[Fact]
public void TestIAsyncDisposableInRegularUsing()
{
string source = @"
class C : System.IAsyncDisposable
{
public static int Main()
{
using (var x = new C())
{
return 1;
}
}
public System.Threading.Tasks.ValueTask DisposeAsync()
=> throw null;
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition });
comp.VerifyDiagnostics(
// (6,16): error CS8418: 'C': type used in a using statement must be implicitly convertible to 'System.IDisposable'. Did you mean 'await using' rather than 'using'?
// using (var x = new C())
Diagnostic(ErrorCode.ERR_NoConvToIDispWrongAsync, "var x = new C()").WithArguments("C").WithLocation(6, 16)
);
}
[Fact]
public void TestIAsyncDisposableInRegularUsing_Expression()
{
string source = @"
class C : System.IAsyncDisposable
{
public static int Main()
{
using (new C())
{
return 1;
}
}
public System.Threading.Tasks.ValueTask DisposeAsync()
=> throw null;
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition });
comp.VerifyDiagnostics(
// (6,16): error CS8418: 'C': type used in a using statement must be implicitly convertible to 'System.IDisposable'. Did you mean 'await using'?
// using (new C())
Diagnostic(ErrorCode.ERR_NoConvToIDispWrongAsync, "new C()").WithArguments("C").WithLocation(6, 16)
);
}
[Fact]
public void TestIAsyncDisposableInRegularUsing_WithDispose()
{
string source = @"
class C : System.IAsyncDisposable, System.IDisposable
{
public static int Main()
{
using (var x = new C())
{
System.Console.Write(""body "");
return 1;
}
}
public System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write(""IGNORED"");
return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask);
}
public void Dispose()
{
System.Console.Write(""Dispose"");
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "body Dispose");
}
[Fact]
public void TestIDisposableInAwaitUsing()
{
string source = @"
class C : System.IDisposable
{
async System.Threading.Tasks.Task<int> M()
{
await using (var x = new C())
{
return 1;
}
}
public void Dispose()
=> throw null;
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition });
comp.VerifyDiagnostics(
// (6,22): error CS8417: 'C': type used in an async using statement must be implicitly convertible to 'System.IAsyncDisposable'. Did you mean 'using' rather than 'await using'?
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_NoConvToIAsyncDispWrongAsync, "var x = new C()").WithArguments("C").WithLocation(6, 22)
);
}
[Fact]
public void TestIDisposableInAwaitUsing_Expression()
{
string source = @"
class C : System.IDisposable
{
async System.Threading.Tasks.Task<int> M()
{
await using (new C())
{
return 1;
}
}
public void Dispose()
=> throw null;
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition });
comp.VerifyDiagnostics(
// (6,22): error CS8417: 'C': type used in an async using statement must be implicitly convertible to 'System.IAsyncDisposable'. Did you mean 'using' rather than 'await using'?
// await using (new C())
Diagnostic(ErrorCode.ERR_NoConvToIAsyncDispWrongAsync, "new C()").WithArguments("C").WithLocation(6, 22)
);
}
[Fact]
public void TestWithDynamicDeclaration_ExplicitInterfaceImplementation()
{
string source = @"
class C : System.IAsyncDisposable
{
public static async System.Threading.Tasks.Task<int> Main()
{
await using (dynamic x = new C())
{
System.Console.Write(""body "");
}
System.Console.Write(""end "");
return 1;
}
System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()
{
System.Console.Write(""DisposeAsync "");
return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask);
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe, references: new[] { CSharpRef });
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "body DisposeAsync end");
}
[Fact]
public void TestWithDynamicDeclaration()
{
string source = @"
class C : System.IAsyncDisposable
{
public static async System.Threading.Tasks.Task<int> Main()
{
await using (dynamic x = new C())
{
System.Console.Write(""body "");
}
System.Console.Write(""end "");
return 1;
}
public System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write(""DisposeAsync "");
return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask);
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe, references: new[] { CSharpRef });
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "body DisposeAsync end");
}
[Fact]
public void TestWithExpression()
{
string source = @"
class C : System.IAsyncDisposable
{
public static async System.Threading.Tasks.Task Main()
{
await using (new C())
{
System.Console.Write(""body "");
return;
}
}
public System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write(""DisposeAsync"");
return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask);
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "body DisposeAsync");
verifier.VerifyIL("C.<Main>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 306 (0x132)
.maxstack 3
.locals init (int V_0,
object V_1,
System.Runtime.CompilerServices.ValueTaskAwaiter V_2,
System.Threading.Tasks.ValueTask V_3,
C.<Main>d__0 V_4,
System.Exception V_5,
int V_6)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<Main>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_000c
IL_000a: br.s IL_0011
IL_000c: br IL_0099
IL_0011: nop
IL_0012: ldarg.0
IL_0013: newobj ""C..ctor()""
IL_0018: stfld ""C C.<Main>d__0.<>s__1""
IL_001d: ldarg.0
IL_001e: ldnull
IL_001f: stfld ""object C.<Main>d__0.<>s__2""
IL_0024: ldarg.0
IL_0025: ldc.i4.0
IL_0026: stfld ""int C.<Main>d__0.<>s__3""
.try
{
IL_002b: nop
IL_002c: ldstr ""body ""
IL_0031: call ""void System.Console.Write(string)""
IL_0036: nop
IL_0037: br.s IL_0039
IL_0039: ldarg.0
IL_003a: ldc.i4.1
IL_003b: stfld ""int C.<Main>d__0.<>s__3""
IL_0040: leave.s IL_004c
}
catch object
{
IL_0042: stloc.1
IL_0043: ldarg.0
IL_0044: ldloc.1
IL_0045: stfld ""object C.<Main>d__0.<>s__2""
IL_004a: leave.s IL_004c
}
IL_004c: ldarg.0
IL_004d: ldfld ""C C.<Main>d__0.<>s__1""
IL_0052: brfalse.s IL_00bd
IL_0054: ldarg.0
IL_0055: ldfld ""C C.<Main>d__0.<>s__1""
IL_005a: callvirt ""System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()""
IL_005f: stloc.3
IL_0060: ldloca.s V_3
IL_0062: call ""System.Runtime.CompilerServices.ValueTaskAwaiter System.Threading.Tasks.ValueTask.GetAwaiter()""
IL_0067: stloc.2
IL_0068: ldloca.s V_2
IL_006a: call ""bool System.Runtime.CompilerServices.ValueTaskAwaiter.IsCompleted.get""
IL_006f: brtrue.s IL_00b5
IL_0071: ldarg.0
IL_0072: ldc.i4.0
IL_0073: dup
IL_0074: stloc.0
IL_0075: stfld ""int C.<Main>d__0.<>1__state""
IL_007a: ldarg.0
IL_007b: ldloc.2
IL_007c: stfld ""System.Runtime.CompilerServices.ValueTaskAwaiter C.<Main>d__0.<>u__1""
IL_0081: ldarg.0
IL_0082: stloc.s V_4
IL_0084: ldarg.0
IL_0085: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder""
IL_008a: ldloca.s V_2
IL_008c: ldloca.s V_4
IL_008e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.ValueTaskAwaiter, C.<Main>d__0>(ref System.Runtime.CompilerServices.ValueTaskAwaiter, ref C.<Main>d__0)""
IL_0093: nop
IL_0094: leave IL_0131
IL_0099: ldarg.0
IL_009a: ldfld ""System.Runtime.CompilerServices.ValueTaskAwaiter C.<Main>d__0.<>u__1""
IL_009f: stloc.2
IL_00a0: ldarg.0
IL_00a1: ldflda ""System.Runtime.CompilerServices.ValueTaskAwaiter C.<Main>d__0.<>u__1""
IL_00a6: initobj ""System.Runtime.CompilerServices.ValueTaskAwaiter""
IL_00ac: ldarg.0
IL_00ad: ldc.i4.m1
IL_00ae: dup
IL_00af: stloc.0
IL_00b0: stfld ""int C.<Main>d__0.<>1__state""
IL_00b5: ldloca.s V_2
IL_00b7: call ""void System.Runtime.CompilerServices.ValueTaskAwaiter.GetResult()""
IL_00bc: nop
IL_00bd: ldarg.0
IL_00be: ldfld ""object C.<Main>d__0.<>s__2""
IL_00c3: stloc.1
IL_00c4: ldloc.1
IL_00c5: brfalse.s IL_00e2
IL_00c7: ldloc.1
IL_00c8: isinst ""System.Exception""
IL_00cd: stloc.s V_5
IL_00cf: ldloc.s V_5
IL_00d1: brtrue.s IL_00d5
IL_00d3: ldloc.1
IL_00d4: throw
IL_00d5: ldloc.s V_5
IL_00d7: call ""System.Runtime.ExceptionServices.ExceptionDispatchInfo System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(System.Exception)""
IL_00dc: callvirt ""void System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()""
IL_00e1: nop
IL_00e2: ldarg.0
IL_00e3: ldfld ""int C.<Main>d__0.<>s__3""
IL_00e8: stloc.s V_6
IL_00ea: ldloc.s V_6
IL_00ec: ldc.i4.1
IL_00ed: beq.s IL_00f1
IL_00ef: br.s IL_00f3
IL_00f1: leave.s IL_011d
IL_00f3: ldarg.0
IL_00f4: ldnull
IL_00f5: stfld ""object C.<Main>d__0.<>s__2""
IL_00fa: ldarg.0
IL_00fb: ldnull
IL_00fc: stfld ""C C.<Main>d__0.<>s__1""
IL_0101: leave.s IL_011d
}
catch System.Exception
{
IL_0103: stloc.s V_5
IL_0105: ldarg.0
IL_0106: ldc.i4.s -2
IL_0108: stfld ""int C.<Main>d__0.<>1__state""
IL_010d: ldarg.0
IL_010e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder""
IL_0113: ldloc.s V_5
IL_0115: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_011a: nop
IL_011b: leave.s IL_0131
}
IL_011d: ldarg.0
IL_011e: ldc.i4.s -2
IL_0120: stfld ""int C.<Main>d__0.<>1__state""
IL_0125: ldarg.0
IL_0126: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder""
IL_012b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_0130: nop
IL_0131: ret
}");
}
[Fact]
public void TestWithNullExpression()
{
string source = @"
class C
{
public static async System.Threading.Tasks.Task Main()
{
await using (null)
{
System.Console.Write(""body"");
return;
}
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "body");
}
[Fact]
public void TestWithMethodName()
{
string source = @"
class C
{
public static async System.Threading.Tasks.Task Main()
{
await using (Main)
{
}
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition });
comp.VerifyDiagnostics(
// (6,22): error CS8410: 'method group': type used in an async using statement must be implicitly convertible to 'System.IAsyncDisposable'
// await using (Main)
Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "Main").WithArguments("method group").WithLocation(6, 22)
);
}
[Fact]
public void TestWithDynamicExpression()
{
string source = @"
class C : System.IAsyncDisposable
{
public static async System.Threading.Tasks.Task Main()
{
dynamic d = new C();
await using (d)
{
System.Console.Write(""body "");
return;
}
}
public System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write(""DisposeAsync"");
return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask);
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe, references: new[] { CSharpRef });
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "body DisposeAsync");
}
[Fact]
public void TestWithStructExpression()
{
string source = @"
struct S : System.IAsyncDisposable
{
public static async System.Threading.Tasks.Task Main()
{
await using (new S())
{
System.Console.Write(""body "");
return;
}
}
public System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write(""DisposeAsync"");
return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask);
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "body DisposeAsync");
verifier.VerifyIL("S.<Main>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 298 (0x12a)
.maxstack 3
.locals init (int V_0,
object V_1,
System.Runtime.CompilerServices.ValueTaskAwaiter V_2,
System.Threading.Tasks.ValueTask V_3,
S.<Main>d__0 V_4,
System.Exception V_5,
int V_6)
IL_0000: ldarg.0
IL_0001: ldfld ""int S.<Main>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_000c
IL_000a: br.s IL_0011
IL_000c: br IL_0098
IL_0011: nop
IL_0012: ldarg.0
IL_0013: ldflda ""S S.<Main>d__0.<>s__1""
IL_0018: initobj ""S""
IL_001e: ldarg.0
IL_001f: ldnull
IL_0020: stfld ""object S.<Main>d__0.<>s__2""
IL_0025: ldarg.0
IL_0026: ldc.i4.0
IL_0027: stfld ""int S.<Main>d__0.<>s__3""
.try
{
IL_002c: nop
IL_002d: ldstr ""body ""
IL_0032: call ""void System.Console.Write(string)""
IL_0037: nop
IL_0038: br.s IL_003a
IL_003a: ldarg.0
IL_003b: ldc.i4.1
IL_003c: stfld ""int S.<Main>d__0.<>s__3""
IL_0041: leave.s IL_004d
}
catch object
{
IL_0043: stloc.1
IL_0044: ldarg.0
IL_0045: ldloc.1
IL_0046: stfld ""object S.<Main>d__0.<>s__2""
IL_004b: leave.s IL_004d
}
IL_004d: ldarg.0
IL_004e: ldflda ""S S.<Main>d__0.<>s__1""
IL_0053: constrained. ""S""
IL_0059: callvirt ""System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()""
IL_005e: stloc.3
IL_005f: ldloca.s V_3
IL_0061: call ""System.Runtime.CompilerServices.ValueTaskAwaiter System.Threading.Tasks.ValueTask.GetAwaiter()""
IL_0066: stloc.2
IL_0067: ldloca.s V_2
IL_0069: call ""bool System.Runtime.CompilerServices.ValueTaskAwaiter.IsCompleted.get""
IL_006e: brtrue.s IL_00b4
IL_0070: ldarg.0
IL_0071: ldc.i4.0
IL_0072: dup
IL_0073: stloc.0
IL_0074: stfld ""int S.<Main>d__0.<>1__state""
IL_0079: ldarg.0
IL_007a: ldloc.2
IL_007b: stfld ""System.Runtime.CompilerServices.ValueTaskAwaiter S.<Main>d__0.<>u__1""
IL_0080: ldarg.0
IL_0081: stloc.s V_4
IL_0083: ldarg.0
IL_0084: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder S.<Main>d__0.<>t__builder""
IL_0089: ldloca.s V_2
IL_008b: ldloca.s V_4
IL_008d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.ValueTaskAwaiter, S.<Main>d__0>(ref System.Runtime.CompilerServices.ValueTaskAwaiter, ref S.<Main>d__0)""
IL_0092: nop
IL_0093: leave IL_0129
IL_0098: ldarg.0
IL_0099: ldfld ""System.Runtime.CompilerServices.ValueTaskAwaiter S.<Main>d__0.<>u__1""
IL_009e: stloc.2
IL_009f: ldarg.0
IL_00a0: ldflda ""System.Runtime.CompilerServices.ValueTaskAwaiter S.<Main>d__0.<>u__1""
IL_00a5: initobj ""System.Runtime.CompilerServices.ValueTaskAwaiter""
IL_00ab: ldarg.0
IL_00ac: ldc.i4.m1
IL_00ad: dup
IL_00ae: stloc.0
IL_00af: stfld ""int S.<Main>d__0.<>1__state""
IL_00b4: ldloca.s V_2
IL_00b6: call ""void System.Runtime.CompilerServices.ValueTaskAwaiter.GetResult()""
IL_00bb: nop
IL_00bc: ldarg.0
IL_00bd: ldfld ""object S.<Main>d__0.<>s__2""
IL_00c2: stloc.1
IL_00c3: ldloc.1
IL_00c4: brfalse.s IL_00e1
IL_00c6: ldloc.1
IL_00c7: isinst ""System.Exception""
IL_00cc: stloc.s V_5
IL_00ce: ldloc.s V_5
IL_00d0: brtrue.s IL_00d4
IL_00d2: ldloc.1
IL_00d3: throw
IL_00d4: ldloc.s V_5
IL_00d6: call ""System.Runtime.ExceptionServices.ExceptionDispatchInfo System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(System.Exception)""
IL_00db: callvirt ""void System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()""
IL_00e0: nop
IL_00e1: ldarg.0
IL_00e2: ldfld ""int S.<Main>d__0.<>s__3""
IL_00e7: stloc.s V_6
IL_00e9: ldloc.s V_6
IL_00eb: ldc.i4.1
IL_00ec: beq.s IL_00f0
IL_00ee: br.s IL_00f2
IL_00f0: leave.s IL_0115
IL_00f2: ldarg.0
IL_00f3: ldnull
IL_00f4: stfld ""object S.<Main>d__0.<>s__2""
IL_00f9: leave.s IL_0115
}
catch System.Exception
{
IL_00fb: stloc.s V_5
IL_00fd: ldarg.0
IL_00fe: ldc.i4.s -2
IL_0100: stfld ""int S.<Main>d__0.<>1__state""
IL_0105: ldarg.0
IL_0106: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder S.<Main>d__0.<>t__builder""
IL_010b: ldloc.s V_5
IL_010d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_0112: nop
IL_0113: leave.s IL_0129
}
IL_0115: ldarg.0
IL_0116: ldc.i4.s -2
IL_0118: stfld ""int S.<Main>d__0.<>1__state""
IL_011d: ldarg.0
IL_011e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder S.<Main>d__0.<>t__builder""
IL_0123: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_0128: nop
IL_0129: ret
}");
}
[Fact]
public void Struct_ExplicitImplementation()
{
string source =
@"using System;
using System.Threading.Tasks;
class C
{
internal bool _disposed;
}
struct S : IAsyncDisposable
{
C _c;
S(C c)
{
_c = c;
}
static async Task Main()
{
var s = new S(new C());
await using (s)
{
}
Console.WriteLine(s._c._disposed);
}
ValueTask IAsyncDisposable.DisposeAsync()
{
_c._disposed = true;
return new ValueTask(Task.CompletedTask);
}
}";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "True");
}
[Fact]
public void TestWithNullableExpression()
{
string source = @"
struct S : System.IAsyncDisposable
{
public static async System.Threading.Tasks.Task Main()
{
S? s = new S();
await using (s)
{
System.Console.Write(""body "");
return;
}
}
public System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write(""DisposeAsync"");
return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask);
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "body DisposeAsync");
}
[Fact]
public void TestWithNullNullableExpression()
{
string source = @"
struct S : System.IAsyncDisposable
{
public static async System.Threading.Tasks.Task Main()
{
S? s = null;
await using (s)
{
System.Console.Write(""body"");
return;
}
}
public System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write(""NOT RELEVANT"");
return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask);
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "body");
}
[Fact]
[WorkItem(24267, "https://github.com/dotnet/roslyn/issues/24267")]
public void AssignsInAsyncWithAwaitUsing()
{
var comp = CreateCompilationWithTasksExtensions(@"
class C
{
public static void M2()
{
int a=0, x, y, z;
L1();
a++;
x++;
y++;
z++;
async void L1()
{
x = 0;
await using (null) { }
y = 0;
// local function exists with a pending branch from the async using, in which `y` was not assigned
}
}
}" + IAsyncDisposableDefinition);
comp.VerifyDiagnostics(
// (10,9): error CS0165: Use of unassigned local variable 'y'
// y++;
Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(10, 9),
// (11,9): error CS0165: Use of unassigned local variable 'z'
// z++;
Diagnostic(ErrorCode.ERR_UseDefViolation, "z").WithArguments("z").WithLocation(11, 9)
);
}
[Fact]
public void TestWithMultipleResources()
{
string source = @"
class S : System.IAsyncDisposable
{
private int _i;
S(int i)
{
System.Console.Write($""ctor{i} "");
_i = i;
}
public static async System.Threading.Tasks.Task Main()
{
await using (S s1 = new S(1), s2 = new S(2))
{
System.Console.Write(""body "");
return;
}
}
public async System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write($""dispose{_i}_start "");
await System.Threading.Tasks.Task.Yield();
System.Console.Write($""dispose{_i}_end "");
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "ctor1 ctor2 body dispose2_start dispose2_end dispose1_start dispose1_end");
}
[Fact]
public void TestWithMultipleResourcesAndException()
{
string source = @"
class S : System.IAsyncDisposable
{
private int _i;
S(int i)
{
System.Console.Write($""ctor{i} "");
_i = i;
}
public static async System.Threading.Tasks.Task Main()
{
try
{
await using (S s1 = new S(1), s2 = new S(2))
{
System.Console.Write(""body "");
throw new System.Exception();
}
}
catch (System.Exception)
{
System.Console.Write(""caught"");
}
}
public System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write($""dispose{_i} "");
return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask);
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "ctor1 ctor2 body dispose2 dispose1 caught");
}
[Fact]
public void TestWithMultipleResourcesAndExceptionInSecondResource()
{
string source = @"
class S : System.IAsyncDisposable
{
private int _i;
S(int i)
{
System.Console.Write($""ctor{i} "");
if (i == 1)
{
_i = i;
}
else
{
throw new System.Exception();
}
}
public static async System.Threading.Tasks.Task Main()
{
try
{
await using (S s1 = new S(1), s2 = new S(2))
{
System.Console.Write(""SKIPPED"");
}
}
catch (System.Exception)
{
System.Console.Write(""caught"");
}
}
public System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write($""dispose{_i} "");
return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask);
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "ctor1 ctor2 dispose1 caught");
}
[Fact]
public void TestAwaitExpressionInfo_IEquatable()
{
string source = @"
public class C
{
void GetAwaiter() { }
void GetResult() { }
bool IsCompleted => true;
}
public class D
{
void GetAwaiter() { }
void GetResult() { }
bool IsCompleted => true;
}
";
var comp = CreateCompilation(source);
var getAwaiter1 = (MethodSymbol)comp.GetMember("C.GetAwaiter");
var isCompleted1 = (PropertySymbol)comp.GetMember("C.IsCompleted");
var getResult1 = (MethodSymbol)comp.GetMember("C.GetResult");
var first = new AwaitExpressionInfo(getAwaiter1.GetPublicSymbol(), isCompleted1.GetPublicSymbol(), getResult1.GetPublicSymbol(), false);
var nulls1 = new AwaitExpressionInfo(null, isCompleted1.GetPublicSymbol(), getResult1.GetPublicSymbol(), false);
var nulls2 = new AwaitExpressionInfo(getAwaiter1.GetPublicSymbol(), null, getResult1.GetPublicSymbol(), false);
var nulls3 = new AwaitExpressionInfo(getAwaiter1.GetPublicSymbol(), isCompleted1.GetPublicSymbol(), null, false);
var nulls4 = new AwaitExpressionInfo(getAwaiter1.GetPublicSymbol(), isCompleted1.GetPublicSymbol(), null, true);
Assert.False(first.Equals(nulls1));
Assert.False(first.Equals(nulls2));
Assert.False(first.Equals(nulls3));
Assert.False(first.Equals(nulls4));
Assert.False(nulls1.Equals(first));
Assert.False(nulls2.Equals(first));
Assert.False(nulls3.Equals(first));
Assert.False(nulls4.Equals(first));
_ = nulls1.GetHashCode();
_ = nulls2.GetHashCode();
_ = nulls3.GetHashCode();
_ = nulls4.GetHashCode();
object nullObj = null;
Assert.False(first.Equals(nullObj));
var getAwaiter2 = (MethodSymbol)comp.GetMember("D.GetAwaiter");
var isCompleted2 = (PropertySymbol)comp.GetMember("D.IsCompleted");
var getResult2 = (MethodSymbol)comp.GetMember("D.GetResult");
var second1 = new AwaitExpressionInfo(getAwaiter2.GetPublicSymbol(), isCompleted1.GetPublicSymbol(), getResult1.GetPublicSymbol(), false);
var second2 = new AwaitExpressionInfo(getAwaiter1.GetPublicSymbol(), isCompleted2.GetPublicSymbol(), getResult1.GetPublicSymbol(), false);
var second3 = new AwaitExpressionInfo(getAwaiter1.GetPublicSymbol(), isCompleted1.GetPublicSymbol(), getResult2.GetPublicSymbol(), false);
var second4 = new AwaitExpressionInfo(getAwaiter2.GetPublicSymbol(), isCompleted2.GetPublicSymbol(), getResult2.GetPublicSymbol(), false);
Assert.False(first.Equals(second1));
Assert.False(first.Equals(second2));
Assert.False(first.Equals(second3));
Assert.False(first.Equals(second4));
Assert.False(second1.Equals(first));
Assert.False(second2.Equals(first));
Assert.False(second3.Equals(first));
Assert.False(second4.Equals(first));
Assert.True(first.Equals(first));
Assert.True(first.Equals((object)first));
var another = new AwaitExpressionInfo(getAwaiter1.GetPublicSymbol(), isCompleted1.GetPublicSymbol(), getResult1.GetPublicSymbol(), false);
Assert.True(first.GetHashCode() == another.GetHashCode());
}
[Fact]
[WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")]
public void TestPatternBasedDisposal_ExtensionMethod()
{
string source = @"
public class C
{
public static async System.Threading.Tasks.Task<int> Main()
{
await using (var x = new C())
{
}
return 1;
}
}
public static class Extensions
{
public static System.Threading.Tasks.ValueTask DisposeAsync(this C c)
=> throw null;
}
";
// extension methods do not contribute to pattern-based disposal
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,22): error CS8410: 'C': type used in an async using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method.
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "var x = new C()").WithArguments("C").WithLocation(6, 22)
);
}
[Fact]
[WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")]
public void TestPatternBasedDisposal_TwoOverloads()
{
string source = @"
public class C
{
public static async System.Threading.Tasks.Task<int> Main()
{
await using (var x = new C())
{
}
return 1;
}
public async System.Threading.Tasks.ValueTask DisposeAsync(int i = 0)
{
System.Console.Write($""dispose"");
await System.Threading.Tasks.Task.Yield();
}
public System.Threading.Tasks.ValueTask DisposeAsync(params string[] s)
=> throw null;
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "dispose");
}
[Fact]
[WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")]
public void TestPatternBasedDisposal_Expression_ExtensionMethod()
{
string source = @"
public class C
{
public static async System.Threading.Tasks.Task<int> Main()
{
await using (new C())
{
}
return 1;
}
}
public static class Extensions
{
public static System.Threading.Tasks.ValueTask DisposeAsync(this C c)
=> throw null;
}
";
// extension methods do not contribute to pattern-based disposal
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,22): error CS8410: 'C': type used in an async using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method.
// await using (new C())
Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "new C()").WithArguments("C").WithLocation(6, 22)
);
}
[Fact]
[WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")]
public void TestPatternBasedDisposal_Expression_InstanceMethod()
{
string source = @"
public class C
{
public static async System.Threading.Tasks.Task<int> Main()
{
await using (new C())
{
System.Console.Write(""using "");
}
System.Console.Write(""return"");
return 1;
}
public async System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write($""dispose_start "");
await System.Threading.Tasks.Task.Yield();
System.Console.Write($""dispose_end "");
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "using dispose_start dispose_end return");
}
[Fact]
[WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")]
public void TestPatternBasedDisposal_InstanceMethod()
{
string source = @"
public class C
{
public static async System.Threading.Tasks.Task<int> Main()
{
await using (var x = new C())
{
System.Console.Write(""using "");
}
System.Console.Write(""return"");
return 1;
}
public async System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write($""dispose_start "");
await System.Threading.Tasks.Task.Yield();
System.Console.Write($""dispose_end "");
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "using dispose_start dispose_end return");
}
[Fact]
[WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")]
public void TestPatternBasedDisposal_InterfacePreferredOverInstanceMethod()
{
string source = @"
public class C : System.IAsyncDisposable
{
public static async System.Threading.Tasks.Task<int> Main()
{
await using (var x = new C())
{
System.Console.Write(""using "");
}
System.Console.Write(""return"");
return 1;
}
async System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()
{
System.Console.Write($""dispose_start "");
await System.Threading.Tasks.Task.Yield();
System.Console.Write($""dispose_end "");
}
public System.Threading.Tasks.ValueTask DisposeAsync()
=> throw null;
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "using dispose_start dispose_end return");
}
[Fact]
[WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")]
public void TestPatternBasedDisposal_InstanceMethod_OptionalParameter()
{
string source = @"
public class C
{
public static async System.Threading.Tasks.Task<int> Main()
{
await using (var x = new C())
{
System.Console.Write(""using "");
}
System.Console.Write(""return"");
return 1;
}
public async System.Threading.Tasks.ValueTask DisposeAsync(int i = 0)
{
System.Console.Write($""dispose_start "");
await System.Threading.Tasks.Task.Yield();
System.Console.Write($""dispose_end "");
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "using dispose_start dispose_end return");
}
[Fact]
[WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")]
public void TestPatternBasedDisposal_InstanceMethod_ParamsParameter()
{
string source = @"
public class C
{
public static async System.Threading.Tasks.Task<int> Main()
{
await using (var x = new C())
{
System.Console.Write(""using "");
}
System.Console.Write(""return"");
return 1;
}
public async System.Threading.Tasks.ValueTask DisposeAsync(params int[] x)
{
System.Console.Write($""dispose_start "");
await System.Threading.Tasks.Task.Yield();
System.Console.Write($""dispose_end({x.Length}) "");
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "using dispose_start dispose_end(0) return");
}
[Fact]
[WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")]
public void TestPatternBasedDisposal_InstanceMethod_ReturningVoid()
{
string source = @"
public class C
{
public static async System.Threading.Tasks.Task<int> Main()
{
await using (var x = new C())
{
}
return 1;
}
public void DisposeAsync()
{
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition });
comp.VerifyDiagnostics(
// (6,22): error CS4008: Cannot await 'void'
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_BadAwaitArgVoidCall, "var x = new C()").WithLocation(6, 22)
);
}
[Fact]
[WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")]
public void TestPatternBasedDisposal_InstanceMethod_ReturningInt()
{
string source = @"
public class C
{
public static async System.Threading.Tasks.Task<int> Main()
{
await using (var x = new C())
{
}
return 1;
}
public int DisposeAsync()
=> throw null;
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition });
comp.VerifyDiagnostics(
// (6,22): error CS1061: 'int' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?)
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "var x = new C()").WithArguments("int", "GetAwaiter").WithLocation(6, 22)
);
}
[Fact]
[WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")]
public void TestPatternBasedDisposal_InstanceMethod_Inaccessible()
{
string source = @"
public class D
{
public static async System.Threading.Tasks.Task<int> Main()
{
await using (var x = new C())
{
}
return 1;
}
}
public class C
{
private System.Threading.Tasks.ValueTask DisposeAsync()
=> throw null;
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition });
comp.VerifyDiagnostics(
// (6,22): error CS0122: 'C.DisposeAsync()' is inaccessible due to its protection level
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_BadAccess, "var x = new C()").WithArguments("C.DisposeAsync()").WithLocation(6, 22),
// (6,22): error CS8410: 'C': type used in an async using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method.
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "var x = new C()").WithArguments("C").WithLocation(6, 22)
);
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
[WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")]
public void TestPatternBasedDisposal_InstanceMethod_UsingDeclaration()
{
string source = @"
public class C
{
public static async System.Threading.Tasks.Task<int> Main()
{
{
await using var x = new C();
System.Console.Write(""using "");
}
System.Console.Write(""return"");
return 1;
}
public async System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write($""dispose_start "");
await System.Threading.Tasks.Task.Yield();
System.Console.Write($""dispose_end "");
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "using dispose_start dispose_end return");
// Sequence point higlights `await using ...`
verifier.VerifyIL("C.<Main>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 303 (0x12f)
.maxstack 3
.locals init (int V_0,
int V_1,
object V_2,
System.Runtime.CompilerServices.ValueTaskAwaiter V_3,
System.Threading.Tasks.ValueTask V_4,
C.<Main>d__0 V_5,
System.Exception V_6)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<Main>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: <hidden>
IL_0007: ldloc.0
IL_0008: brfalse.s IL_000c
IL_000a: br.s IL_0011
IL_000c: br IL_0091
// sequence point: {
IL_0011: nop
// sequence point: {
IL_0012: nop
// sequence point: await using var x = new C();
IL_0013: ldarg.0
IL_0014: newobj ""C..ctor()""
IL_0019: stfld ""C C.<Main>d__0.<x>5__1""
// sequence point: <hidden>
IL_001e: ldarg.0
IL_001f: ldnull
IL_0020: stfld ""object C.<Main>d__0.<>s__2""
IL_0025: ldarg.0
IL_0026: ldc.i4.0
IL_0027: stfld ""int C.<Main>d__0.<>s__3""
.try
{
// sequence point: System.Console.Write(""using "");
IL_002c: ldstr ""using ""
IL_0031: call ""void System.Console.Write(string)""
IL_0036: nop
// sequence point: <hidden>
IL_0037: leave.s IL_0043
}
catch object
{
// sequence point: <hidden>
IL_0039: stloc.2
IL_003a: ldarg.0
IL_003b: ldloc.2
IL_003c: stfld ""object C.<Main>d__0.<>s__2""
IL_0041: leave.s IL_0043
}
// sequence point: <hidden>
IL_0043: ldarg.0
IL_0044: ldfld ""C C.<Main>d__0.<x>5__1""
IL_0049: brfalse.s IL_00b5
IL_004b: ldarg.0
IL_004c: ldfld ""C C.<Main>d__0.<x>5__1""
IL_0051: callvirt ""System.Threading.Tasks.ValueTask C.DisposeAsync()""
IL_0056: stloc.s V_4
IL_0058: ldloca.s V_4
IL_005a: call ""System.Runtime.CompilerServices.ValueTaskAwaiter System.Threading.Tasks.ValueTask.GetAwaiter()""
IL_005f: stloc.3
// sequence point: <hidden>
IL_0060: ldloca.s V_3
IL_0062: call ""bool System.Runtime.CompilerServices.ValueTaskAwaiter.IsCompleted.get""
IL_0067: brtrue.s IL_00ad
IL_0069: ldarg.0
IL_006a: ldc.i4.0
IL_006b: dup
IL_006c: stloc.0
IL_006d: stfld ""int C.<Main>d__0.<>1__state""
// async: yield
IL_0072: ldarg.0
IL_0073: ldloc.3
IL_0074: stfld ""System.Runtime.CompilerServices.ValueTaskAwaiter C.<Main>d__0.<>u__1""
IL_0079: ldarg.0
IL_007a: stloc.s V_5
IL_007c: ldarg.0
IL_007d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<Main>d__0.<>t__builder""
IL_0082: ldloca.s V_3
IL_0084: ldloca.s V_5
IL_0086: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.ValueTaskAwaiter, C.<Main>d__0>(ref System.Runtime.CompilerServices.ValueTaskAwaiter, ref C.<Main>d__0)""
IL_008b: nop
IL_008c: leave IL_012e
// async: resume
IL_0091: ldarg.0
IL_0092: ldfld ""System.Runtime.CompilerServices.ValueTaskAwaiter C.<Main>d__0.<>u__1""
IL_0097: stloc.3
IL_0098: ldarg.0
IL_0099: ldflda ""System.Runtime.CompilerServices.ValueTaskAwaiter C.<Main>d__0.<>u__1""
IL_009e: initobj ""System.Runtime.CompilerServices.ValueTaskAwaiter""
IL_00a4: ldarg.0
IL_00a5: ldc.i4.m1
IL_00a6: dup
IL_00a7: stloc.0
IL_00a8: stfld ""int C.<Main>d__0.<>1__state""
IL_00ad: ldloca.s V_3
IL_00af: call ""void System.Runtime.CompilerServices.ValueTaskAwaiter.GetResult()""
IL_00b4: nop
// sequence point: <hidden>
IL_00b5: ldarg.0
IL_00b6: ldfld ""object C.<Main>d__0.<>s__2""
IL_00bb: stloc.2
IL_00bc: ldloc.2
IL_00bd: brfalse.s IL_00da
IL_00bf: ldloc.2
IL_00c0: isinst ""System.Exception""
IL_00c5: stloc.s V_6
IL_00c7: ldloc.s V_6
IL_00c9: brtrue.s IL_00cd
IL_00cb: ldloc.2
IL_00cc: throw
IL_00cd: ldloc.s V_6
IL_00cf: call ""System.Runtime.ExceptionServices.ExceptionDispatchInfo System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(System.Exception)""
IL_00d4: callvirt ""void System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()""
IL_00d9: nop
IL_00da: ldarg.0
IL_00db: ldfld ""int C.<Main>d__0.<>s__3""
IL_00e0: pop
IL_00e1: ldarg.0
IL_00e2: ldnull
IL_00e3: stfld ""object C.<Main>d__0.<>s__2""
// sequence point: }
IL_00e8: nop
IL_00e9: ldarg.0
IL_00ea: ldnull
IL_00eb: stfld ""C C.<Main>d__0.<x>5__1""
// sequence point: System.Console.Write(""return"");
IL_00f0: ldstr ""return""
IL_00f5: call ""void System.Console.Write(string)""
IL_00fa: nop
// sequence point: return 1;
IL_00fb: ldc.i4.1
IL_00fc: stloc.1
IL_00fd: leave.s IL_0119
}
catch System.Exception
{
// async: catch handler, sequence point: <hidden>
IL_00ff: stloc.s V_6
IL_0101: ldarg.0
IL_0102: ldc.i4.s -2
IL_0104: stfld ""int C.<Main>d__0.<>1__state""
IL_0109: ldarg.0
IL_010a: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<Main>d__0.<>t__builder""
IL_010f: ldloc.s V_6
IL_0111: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)""
IL_0116: nop
IL_0117: leave.s IL_012e
}
// sequence point: }
IL_0119: ldarg.0
IL_011a: ldc.i4.s -2
IL_011c: stfld ""int C.<Main>d__0.<>1__state""
// sequence point: <hidden>
IL_0121: ldarg.0
IL_0122: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<Main>d__0.<>t__builder""
IL_0127: ldloc.1
IL_0128: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)""
IL_012d: nop
IL_012e: ret
}
", sequencePoints: "C+<Main>d__0.MoveNext", source: source);
}
[Fact]
[WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")]
public void TestPatternBasedDisposal_Awaitable()
{
string source = @"
public struct C
{
public static async System.Threading.Tasks.Task<int> Main()
{
{
await using var x = new C();
System.Console.Write(""using "");
}
System.Console.Write(""return"");
return 1;
}
public Awaitable DisposeAsync()
{
System.Console.Write($""dispose_start "");
System.Console.Write($""dispose_end "");
return new Awaitable();
}
}
public class Awaitable
{
public Awaiter GetAwaiter() { return new Awaiter(); }
}
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public bool IsCompleted { get { return true; } }
public bool GetResult() { return true; }
public void OnCompleted(System.Action continuation) { }
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "using dispose_start dispose_end return");
}
[Fact]
[WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")]
public void TestPatternBasedDisposal_ReturnsTask()
{
string source = @"
public struct C
{
public static async System.Threading.Tasks.Task<int> Main()
{
{
await using var x = new C();
System.Console.Write(""using "");
}
System.Console.Write(""return"");
return 1;
}
public async System.Threading.Tasks.Task DisposeAsync()
{
System.Console.Write($""dispose_start "");
await System.Threading.Tasks.Task.Yield();
System.Console.Write($""dispose_end "");
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "using dispose_start dispose_end return");
}
[Fact]
[WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")]
public void TestPatternBasedDisposal_ReturnsTaskOfInt()
{
string source = @"
public struct C
{
public static async System.Threading.Tasks.Task<int> Main()
{
{
await using var x = new C();
System.Console.Write(""using "");
}
System.Console.Write(""return"");
return 1;
}
public async System.Threading.Tasks.Task<int> DisposeAsync()
{
System.Console.Write($""dispose_start "");
await System.Threading.Tasks.Task.Yield();
System.Console.Write($""dispose_end "");
return 1;
}
}
";
// it's okay to await `Task<int>` even if we don't care about the result
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "using dispose_start dispose_end return");
}
[Fact]
public void TestInRegularMethod()
{
string source = @"
class C
{
void M()
{
await using var x = new object();
await using (var y = new object()) { }
}
}";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition });
comp.VerifyDiagnostics(
// (6,9): error CS8410: 'object': type used in an async using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method.
// await using var x = new object();
Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "await using var x = new object();").WithArguments("object").WithLocation(6, 9),
// (6,9): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
// await using var x = new object();
Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await").WithLocation(6, 9),
// (7,9): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
// await using (var y = new object()) { }
Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await").WithLocation(7, 9),
// (7,22): error CS8410: 'object': type used in an async using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method.
// await using (var y = new object()) { }
Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "var y = new object()").WithArguments("object").WithLocation(7, 22)
);
}
[Fact]
[WorkItem(30956, "https://github.com/dotnet/roslyn/issues/30956")]
public void GetAwaiterBoxingConversion()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
struct StructAwaitable { }
class Disposable
{
public StructAwaitable DisposeAsync() => new StructAwaitable();
}
static class Extensions
{
public static TaskAwaiter GetAwaiter(this object x)
{
if (x == null) throw new ArgumentNullException(nameof(x));
Console.Write(x);
return Task.CompletedTask.GetAwaiter();
}
}
class Program
{
static async Task Main()
{
await using (new Disposable())
{
}
}
}";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: "StructAwaitable");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
[CompilerTrait(CompilerFeature.AsyncStreams)]
public class CodeGenAwaitUsingTests : CSharpTestBase
{
[Fact]
public void TestWithCSharp7_3()
{
string source = @"
class C : System.IAsyncDisposable
{
async System.Threading.Tasks.Task M()
{
await using (var x = new C())
{
}
}
public System.Threading.Tasks.ValueTask DisposeAsync()
{
throw null;
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (6,9): error CS8652: The feature 'asynchronous using' is not available in C# 7.3. Please use language version 8.0 or greater.
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "await").WithArguments("asynchronous using", "8.0").WithLocation(6, 9)
);
}
[Fact]
public void TestInNonAsyncVoidMethod()
{
string source = @"
class C : System.IAsyncDisposable
{
void M()
{
await using (var x = new C())
{
return;
}
}
public System.Threading.Tasks.ValueTask DisposeAsync()
{
throw null;
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition });
comp.VerifyDiagnostics(
// (6,9): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await").WithLocation(6, 9)
);
}
[Fact]
public void TestInNonAsyncMethodReturningInt()
{
string source = @"
class C : System.IAsyncDisposable
{
int M()
{
await using (var x = new C())
{
return 1;
}
}
public System.Threading.Tasks.ValueTask DisposeAsync()
{
throw null;
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition });
comp.VerifyDiagnostics(
// (6,9): error CS4032: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task<int>'.
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_BadAwaitWithoutAsyncMethod, "await").WithArguments("int").WithLocation(6, 9)
);
}
[Fact]
public void TestInNonAsyncAnonymousMethod()
{
string source = @"
class C : System.IAsyncDisposable
{
void M()
{
System.Action x = () =>
{
await using (var y = new C())
{
return;
}
};
}
public System.Threading.Tasks.ValueTask DisposeAsync()
{
throw null;
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition });
comp.VerifyDiagnostics(
// (8,13): error CS4034: The 'await' operator can only be used within an async lambda expression. Consider marking this lambda expression with the 'async' modifier.
// await using (var y = new C())
Diagnostic(ErrorCode.ERR_BadAwaitWithoutAsyncLambda, "await").WithArguments("lambda expression").WithLocation(8, 13)
);
}
[Fact]
public void TestWithTaskReturningDisposeAsync()
{
string source = @"
using System.Threading.Tasks;
class C : System.IAsyncDisposable
{
public static async Task Main()
{
await using (var y = new C()) { }
}
public async Task DisposeAsync() { }
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (3,11): error CS0738: 'C' does not implement interface member 'IAsyncDisposable.DisposeAsync()'. 'C.DisposeAsync()' cannot implement 'IAsyncDisposable.DisposeAsync()' because it does not have the matching return type of 'ValueTask'.
// class C : System.IAsyncDisposable
Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "System.IAsyncDisposable").WithArguments("C", "System.IAsyncDisposable.DisposeAsync()", "C.DisposeAsync()", "System.Threading.Tasks.ValueTask").WithLocation(3, 11),
// (9,23): 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.
// public async Task DisposeAsync() { }
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "DisposeAsync").WithLocation(9, 23)
);
}
[Fact]
public void TestInAsyncAnonymousMethod()
{
string source = @"
using System.Threading.Tasks;
class C : System.IAsyncDisposable
{
C()
{
System.Console.Write(""C "");
}
public static async Task Main()
{
System.Func<Task> x = async () =>
{
await using (var y = new C())
{
System.Console.Write(""body "");
}
System.Console.Write(""end"");
};
await x();
}
public async ValueTask DisposeAsync()
{
System.Console.Write(""DisposeAsync1 "");
await Task.Yield();
System.Console.Write(""DisposeAsync2 "");
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "C body DisposeAsync1 DisposeAsync2 end");
}
[Fact]
public void TestInUnsafeRegion()
{
string source = @"
class C : System.IAsyncDisposable
{
async System.Threading.Tasks.Task<int> M<T>()
{
unsafe
{
await using (var x = new C())
{
return 1;
}
}
}
public System.Threading.Tasks.ValueTask DisposeAsync()
{
throw null;
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.UnsafeDebugDll);
comp.VerifyDiagnostics(
// (8,13): error CS4004: Cannot await in an unsafe context
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await").WithLocation(8, 13)
);
}
[Fact]
public void TestInLock()
{
string source = @"
class C : System.IAsyncDisposable
{
async System.Threading.Tasks.Task<int> M<T>()
{
lock(this)
{
await using (var x = new C())
{
return 1;
}
}
}
public System.Threading.Tasks.ValueTask DisposeAsync()
{
throw null;
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition });
comp.VerifyDiagnostics(
// (8,13): error CS1996: Cannot await in the body of a lock statement
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_BadAwaitInLock, "await").WithLocation(8, 13)
);
}
[Fact]
public void TestWithObsoleteDisposeAsync()
{
string source = @"
class C : System.IAsyncDisposable
{
public static async System.Threading.Tasks.Task Main()
{
await using (var x = new C())
{
}
}
[System.Obsolete]
public async System.Threading.Tasks.ValueTask DisposeAsync()
{
await System.Threading.Tasks.Task.Yield();
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
// https://github.com/dotnet/roslyn/issues/30257 Confirm whether this behavior is ok (currently matching behavior of obsolete Dispose in non-async using)
}
[Fact]
public void TestWithObsoleteDispose()
{
string source = @"
class C : System.IDisposable
{
public static void Main()
{
using (var x = new C())
{
}
}
[System.Obsolete]
public void Dispose()
{
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition });
comp.VerifyDiagnostics();
}
[Fact]
public void TestInCatchBlock()
{
string source = @"
class C : System.IAsyncDisposable
{
public static async System.Threading.Tasks.Task Main()
{
try
{
System.Console.Write(""try "");
throw new System.ArgumentNullException();
}
catch (System.ArgumentNullException)
{
await using (var x = new C())
{
System.Console.Write(""using "");
}
System.Console.Write(""end"");
}
}
public async System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write($""dispose_start "");
await System.Threading.Tasks.Task.Yield();
System.Console.Write($""dispose_end "");
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "try using dispose_start dispose_end end");
}
[Fact]
public void MissingAwaitInAsyncMethod()
{
string source = @"
class C
{
public static async System.Threading.Tasks.Task Main()
{
System.Action a = () =>
{
System.Action b = async () =>
{
await local();
await using (null) { }
}; // these awaits don't count towards Main method
};
async System.Threading.Tasks.Task local()
{
await local();
await using (null) { }
// neither do these
}
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition });
comp.VerifyDiagnostics(
// (4,53): 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.
// public static async System.Threading.Tasks.Task Main()
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Main").WithLocation(4, 53)
);
}
[Fact]
public void MissingAwaitInAsyncMethod2()
{
string source = @"
class C
{
public static void Main()
{
System.Action lambda1 = async () =>
{
System.Action b = async () =>
{
await local();
await using (null) { }
}; // these awaits don't count towards lambda
};
System.Action lambda2 = async () => await local2(); // this await counts towards lambda
async System.Threading.Tasks.Task local()
{
System.Func<System.Threading.Tasks.Task> c = innerLocal;
async System.Threading.Tasks.Task innerLocal()
{
await local();
await using (null) { }
// these awaits don't count towards lambda either
}
}
async System.Threading.Tasks.Task local2() => await local(); // this await counts towards local function
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition });
comp.VerifyDiagnostics(
// (17,43): 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.
// async System.Threading.Tasks.Task local()
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "local").WithLocation(17, 43),
// (6,42): 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.
// System.Action lambda1 = async () =>
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "=>").WithLocation(6, 42)
);
}
[Fact]
public void TestInFinallyBlock()
{
string source = @"
class C : System.IAsyncDisposable
{
static async System.Threading.Tasks.Task<int> Main()
{
try
{
}
finally
{
await using (var x = new C())
{
System.Console.Write(""using "");
}
}
System.Console.Write(""return"");
return 1;
}
public async System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write($""dispose_start "");
await System.Threading.Tasks.Task.Yield();
System.Console.Write($""dispose_end "");
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "using dispose_start dispose_end return");
}
[Fact]
public void TestThrowingDisposeAsync()
{
string source = @"
class C : System.IAsyncDisposable
{
static async System.Threading.Tasks.Task Main()
{
try
{
await using (var x = new C())
{
System.Console.Write(""using "");
}
}
catch (System.Exception e)
{
System.Console.Write($""caught {e.Message}"");
return;
}
System.Console.Write(""SKIPPED"");
}
public async System.Threading.Tasks.ValueTask DisposeAsync()
{
bool b = true;
if (b) throw new System.Exception(""message"");
System.Console.Write(""SKIPPED"");
await System.Threading.Tasks.Task.Yield();
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "using caught message");
}
[Fact]
public void TestRegularAwaitInFinallyBlock()
{
string source = @"
using System.Threading.Tasks;
class C
{
static async Task<int> Main()
{
try
{
}
finally
{
System.Console.Write(""before "");
await Task.Yield();
System.Console.Write(""after"");
}
return 1;
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "before after");
}
[Fact]
public void TestMissingIAsyncDisposable()
{
string source = @"
class C
{
async System.Threading.Tasks.Task<int> M()
{
await using (new C())
{
}
await using (var x = new C())
{
return 1;
}
}
}
";
var comp = CreateCompilationWithTasksExtensions(source);
comp.VerifyDiagnostics(
// (6,9): error CS0518: Predefined type 'System.IAsyncDisposable' is not defined or imported
// await using (new C())
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.IAsyncDisposable").WithLocation(6, 9),
// (6,22): error CS8410: 'C': type used in an async using statement must be implicitly convertible to 'System.IAsyncDisposable'
// await using (new C())
Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "new C()").WithArguments("C").WithLocation(6, 22),
// (9,9): error CS0518: Predefined type 'System.IAsyncDisposable' is not defined or imported
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.IAsyncDisposable").WithLocation(9, 9),
// (9,22): error CS8410: 'C': type used in an async using statement must be implicitly convertible to 'System.IAsyncDisposable'
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "var x = new C()").WithArguments("C").WithLocation(9, 22)
);
}
[Fact]
public void TestMissingIAsyncDisposableAndMissingValueTaskAndMissingAsync()
{
string source = @"
class C
{
System.Threading.Tasks.Task<int> M()
{
await using (new C())
{
}
await using (var x = new C())
{
return 1;
}
}
}
";
var comp = CreateCompilationWithMscorlib46(source);
comp.MakeTypeMissing(WellKnownType.System_Threading_Tasks_ValueTask);
comp.VerifyDiagnostics(
// (6,9): error CS0518: Predefined type 'System.IAsyncDisposable' is not defined or imported
// await using (new C())
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.IAsyncDisposable").WithLocation(6, 9),
// (6,9): error CS4032: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task<Task<int>>'.
// await using (new C())
Diagnostic(ErrorCode.ERR_BadAwaitWithoutAsyncMethod, "await").WithArguments("System.Threading.Tasks.Task<int>").WithLocation(6, 9),
// (6,22): error CS8410: 'C': type used in an async using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method.
// await using (new C())
Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "new C()").WithArguments("C").WithLocation(6, 22),
// (9,9): error CS0518: Predefined type 'System.IAsyncDisposable' is not defined or imported
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.IAsyncDisposable").WithLocation(9, 9),
// (9,9): error CS4032: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task<Task<int>>'.
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_BadAwaitWithoutAsyncMethod, "await").WithArguments("System.Threading.Tasks.Task<int>").WithLocation(9, 9),
// (9,22): error CS8410: 'C': type used in an async using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method.
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "var x = new C()").WithArguments("C").WithLocation(9, 22),
// (11,20): error CS0029: Cannot implicitly convert type 'int' to 'System.Threading.Tasks.Task<int>'
// return 1;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "System.Threading.Tasks.Task<int>").WithLocation(11, 20)
);
}
[Fact]
public void TestMissingIDisposable()
{
string source = @"
class C
{
int M()
{
using (new C())
{
}
using (var x = new C())
{
return 1;
}
}
}
";
var comp = CreateCompilationWithMscorlib46(source);
comp.MakeTypeMissing(SpecialType.System_IDisposable);
comp.VerifyEmitDiagnostics(
// (6,9): error CS0518: Predefined type 'System.IDisposable' is not defined or imported
// using (new C())
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "using").WithArguments("System.IDisposable").WithLocation(6, 9),
// (6,16): error CS1674: 'C': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using (new C())
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "new C()").WithArguments("C").WithLocation(6, 16),
// (9,9): error CS0518: Predefined type 'System.IDisposable' is not defined or imported
// using (var x = new C())
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "using").WithArguments("System.IDisposable").WithLocation(9, 9),
// (9,16): error CS1674: 'C': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using (var x = new C())
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var x = new C()").WithArguments("C").WithLocation(9, 16)
);
}
[Fact]
public void TestMissingDisposeAsync()
{
string source = @"
namespace System
{
public interface IAsyncDisposable
{
// missing DisposeAsync
}
}
class C : System.IAsyncDisposable
{
async System.Threading.Tasks.Task<int> M()
{
await using (new C()) { }
await using (var x = new C()) { return 1; }
}
}
";
var comp = CreateCompilationWithTasksExtensions(source);
comp.VerifyDiagnostics();
comp.VerifyEmitDiagnostics(
// (13,9): error CS0656: Missing compiler required member 'System.IAsyncDisposable.DisposeAsync'
// await using (new C()) { }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "await").WithArguments("System.IAsyncDisposable", "DisposeAsync").WithLocation(13, 9),
// (14,9): error CS0656: Missing compiler required member 'System.IAsyncDisposable.DisposeAsync'
// await using (var x = new C()) { return 1; }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "await").WithArguments("System.IAsyncDisposable", "DisposeAsync").WithLocation(14, 9)
);
}
[Fact]
public void TestMissingDispose()
{
string source = @"
class C : System.IDisposable
{
int M()
{
using (new C()) { }
using (var x = new C()) { return 1; }
}
public void Dispose()
{
throw null;
}
}
";
var comp = CreateCompilationWithTasksExtensions(source);
comp.MakeMemberMissing(SpecialMember.System_IDisposable__Dispose);
comp.VerifyEmitDiagnostics(
// (6,9): error CS0656: Missing compiler required member 'System.IDisposable.Dispose'
// using (new C()) { }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "using (new C()) { }").WithArguments("System.IDisposable", "Dispose").WithLocation(6, 9),
// (7,9): error CS0656: Missing compiler required member 'System.IDisposable.Dispose'
// using (var x = new C()) { return 1; }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "using (var x = new C()) { return 1; }").WithArguments("System.IDisposable", "Dispose").WithLocation(7, 9)
);
}
[Fact]
public void TestBadDisposeAsync()
{
string source = @"
namespace System
{
public interface IAsyncDisposable
{
int DisposeAsync(); // bad return type
}
}
class C : System.IAsyncDisposable
{
async System.Threading.Tasks.Task<int> M<T>()
{
await using (new C()) { }
await using (var x = new C()) { return 1; }
}
public int DisposeAsync()
{
throw null;
}
}
";
var comp = CreateCompilationWithTasksExtensions(source);
comp.VerifyDiagnostics();
comp.VerifyEmitDiagnostics(
// (13,9): error CS0656: Missing compiler required member 'System.IAsyncDisposable.DisposeAsync'
// await using (new C()) { }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "await").WithArguments("System.IAsyncDisposable", "DisposeAsync").WithLocation(13, 9),
// (14,9): error CS0656: Missing compiler required member 'System.IAsyncDisposable.DisposeAsync'
// await using (var x = new C()) { return 1; }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "await").WithArguments("System.IAsyncDisposable", "DisposeAsync").WithLocation(14, 9)
);
}
[Fact]
public void TestMissingTaskType()
{
string lib_cs = @"
public class Base : System.IAsyncDisposable
{
public System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write(""DisposeAsync"");
return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask);
}
}
";
string comp_cs = @"
public class C : Base
{
public static async System.Threading.Tasks.Task<int> Main()
{
await using (var x = new C())
{
System.Console.Write(""body "");
return 1;
}
}
}
";
var libComp = CreateCompilationWithTasksExtensions(lib_cs + IAsyncDisposableDefinition);
var comp = CreateCompilationWithTasksExtensions(comp_cs, references: new[] { libComp.EmitToImageReference() }, options: TestOptions.DebugExe);
comp.MakeTypeMissing(WellKnownType.System_Threading_Tasks_ValueTask);
comp.VerifyDiagnostics(
// (6,9): error CS0518: Predefined type 'System.Threading.Tasks.ValueTask' is not defined or imported
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.Threading.Tasks.ValueTask").WithLocation(6, 9)
);
}
[Fact]
public void TestWithDeclaration()
{
string source = @"
class C : System.IAsyncDisposable, System.IDisposable
{
public static async System.Threading.Tasks.Task<int> Main()
{
await using (var x = new C())
{
System.Console.Write(""body "");
return 1;
}
}
public System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write(""DisposeAsync"");
return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask);
}
public void Dispose()
{
System.Console.Write(""IGNORED"");
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "body DisposeAsync");
}
[Fact]
public void TestIAsyncDisposableInRegularUsing()
{
string source = @"
class C : System.IAsyncDisposable
{
public static int Main()
{
using (var x = new C())
{
return 1;
}
}
public System.Threading.Tasks.ValueTask DisposeAsync()
=> throw null;
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition });
comp.VerifyDiagnostics(
// (6,16): error CS8418: 'C': type used in a using statement must be implicitly convertible to 'System.IDisposable'. Did you mean 'await using' rather than 'using'?
// using (var x = new C())
Diagnostic(ErrorCode.ERR_NoConvToIDispWrongAsync, "var x = new C()").WithArguments("C").WithLocation(6, 16)
);
}
[Fact]
public void TestIAsyncDisposableInRegularUsing_Expression()
{
string source = @"
class C : System.IAsyncDisposable
{
public static int Main()
{
using (new C())
{
return 1;
}
}
public System.Threading.Tasks.ValueTask DisposeAsync()
=> throw null;
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition });
comp.VerifyDiagnostics(
// (6,16): error CS8418: 'C': type used in a using statement must be implicitly convertible to 'System.IDisposable'. Did you mean 'await using'?
// using (new C())
Diagnostic(ErrorCode.ERR_NoConvToIDispWrongAsync, "new C()").WithArguments("C").WithLocation(6, 16)
);
}
[Fact]
public void TestIAsyncDisposableInRegularUsing_WithDispose()
{
string source = @"
class C : System.IAsyncDisposable, System.IDisposable
{
public static int Main()
{
using (var x = new C())
{
System.Console.Write(""body "");
return 1;
}
}
public System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write(""IGNORED"");
return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask);
}
public void Dispose()
{
System.Console.Write(""Dispose"");
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "body Dispose");
}
[Fact]
public void TestIDisposableInAwaitUsing()
{
string source = @"
class C : System.IDisposable
{
async System.Threading.Tasks.Task<int> M()
{
await using (var x = new C())
{
return 1;
}
}
public void Dispose()
=> throw null;
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition });
comp.VerifyDiagnostics(
// (6,22): error CS8417: 'C': type used in an async using statement must be implicitly convertible to 'System.IAsyncDisposable'. Did you mean 'using' rather than 'await using'?
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_NoConvToIAsyncDispWrongAsync, "var x = new C()").WithArguments("C").WithLocation(6, 22)
);
}
[Fact]
public void TestIDisposableInAwaitUsing_Expression()
{
string source = @"
class C : System.IDisposable
{
async System.Threading.Tasks.Task<int> M()
{
await using (new C())
{
return 1;
}
}
public void Dispose()
=> throw null;
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition });
comp.VerifyDiagnostics(
// (6,22): error CS8417: 'C': type used in an async using statement must be implicitly convertible to 'System.IAsyncDisposable'. Did you mean 'using' rather than 'await using'?
// await using (new C())
Diagnostic(ErrorCode.ERR_NoConvToIAsyncDispWrongAsync, "new C()").WithArguments("C").WithLocation(6, 22)
);
}
[Fact]
public void TestWithDynamicDeclaration_ExplicitInterfaceImplementation()
{
string source = @"
class C : System.IAsyncDisposable
{
public static async System.Threading.Tasks.Task<int> Main()
{
await using (dynamic x = new C())
{
System.Console.Write(""body "");
}
System.Console.Write(""end "");
return 1;
}
System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()
{
System.Console.Write(""DisposeAsync "");
return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask);
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe, references: new[] { CSharpRef });
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "body DisposeAsync end");
}
[Fact]
public void TestWithDynamicDeclaration()
{
string source = @"
class C : System.IAsyncDisposable
{
public static async System.Threading.Tasks.Task<int> Main()
{
await using (dynamic x = new C())
{
System.Console.Write(""body "");
}
System.Console.Write(""end "");
return 1;
}
public System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write(""DisposeAsync "");
return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask);
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe, references: new[] { CSharpRef });
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "body DisposeAsync end");
}
[Fact]
public void TestWithExpression()
{
string source = @"
class C : System.IAsyncDisposable
{
public static async System.Threading.Tasks.Task Main()
{
await using (new C())
{
System.Console.Write(""body "");
return;
}
}
public System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write(""DisposeAsync"");
return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask);
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "body DisposeAsync");
verifier.VerifyIL("C.<Main>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 306 (0x132)
.maxstack 3
.locals init (int V_0,
object V_1,
System.Runtime.CompilerServices.ValueTaskAwaiter V_2,
System.Threading.Tasks.ValueTask V_3,
C.<Main>d__0 V_4,
System.Exception V_5,
int V_6)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<Main>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_000c
IL_000a: br.s IL_0011
IL_000c: br IL_0099
IL_0011: nop
IL_0012: ldarg.0
IL_0013: newobj ""C..ctor()""
IL_0018: stfld ""C C.<Main>d__0.<>s__1""
IL_001d: ldarg.0
IL_001e: ldnull
IL_001f: stfld ""object C.<Main>d__0.<>s__2""
IL_0024: ldarg.0
IL_0025: ldc.i4.0
IL_0026: stfld ""int C.<Main>d__0.<>s__3""
.try
{
IL_002b: nop
IL_002c: ldstr ""body ""
IL_0031: call ""void System.Console.Write(string)""
IL_0036: nop
IL_0037: br.s IL_0039
IL_0039: ldarg.0
IL_003a: ldc.i4.1
IL_003b: stfld ""int C.<Main>d__0.<>s__3""
IL_0040: leave.s IL_004c
}
catch object
{
IL_0042: stloc.1
IL_0043: ldarg.0
IL_0044: ldloc.1
IL_0045: stfld ""object C.<Main>d__0.<>s__2""
IL_004a: leave.s IL_004c
}
IL_004c: ldarg.0
IL_004d: ldfld ""C C.<Main>d__0.<>s__1""
IL_0052: brfalse.s IL_00bd
IL_0054: ldarg.0
IL_0055: ldfld ""C C.<Main>d__0.<>s__1""
IL_005a: callvirt ""System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()""
IL_005f: stloc.3
IL_0060: ldloca.s V_3
IL_0062: call ""System.Runtime.CompilerServices.ValueTaskAwaiter System.Threading.Tasks.ValueTask.GetAwaiter()""
IL_0067: stloc.2
IL_0068: ldloca.s V_2
IL_006a: call ""bool System.Runtime.CompilerServices.ValueTaskAwaiter.IsCompleted.get""
IL_006f: brtrue.s IL_00b5
IL_0071: ldarg.0
IL_0072: ldc.i4.0
IL_0073: dup
IL_0074: stloc.0
IL_0075: stfld ""int C.<Main>d__0.<>1__state""
IL_007a: ldarg.0
IL_007b: ldloc.2
IL_007c: stfld ""System.Runtime.CompilerServices.ValueTaskAwaiter C.<Main>d__0.<>u__1""
IL_0081: ldarg.0
IL_0082: stloc.s V_4
IL_0084: ldarg.0
IL_0085: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder""
IL_008a: ldloca.s V_2
IL_008c: ldloca.s V_4
IL_008e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.ValueTaskAwaiter, C.<Main>d__0>(ref System.Runtime.CompilerServices.ValueTaskAwaiter, ref C.<Main>d__0)""
IL_0093: nop
IL_0094: leave IL_0131
IL_0099: ldarg.0
IL_009a: ldfld ""System.Runtime.CompilerServices.ValueTaskAwaiter C.<Main>d__0.<>u__1""
IL_009f: stloc.2
IL_00a0: ldarg.0
IL_00a1: ldflda ""System.Runtime.CompilerServices.ValueTaskAwaiter C.<Main>d__0.<>u__1""
IL_00a6: initobj ""System.Runtime.CompilerServices.ValueTaskAwaiter""
IL_00ac: ldarg.0
IL_00ad: ldc.i4.m1
IL_00ae: dup
IL_00af: stloc.0
IL_00b0: stfld ""int C.<Main>d__0.<>1__state""
IL_00b5: ldloca.s V_2
IL_00b7: call ""void System.Runtime.CompilerServices.ValueTaskAwaiter.GetResult()""
IL_00bc: nop
IL_00bd: ldarg.0
IL_00be: ldfld ""object C.<Main>d__0.<>s__2""
IL_00c3: stloc.1
IL_00c4: ldloc.1
IL_00c5: brfalse.s IL_00e2
IL_00c7: ldloc.1
IL_00c8: isinst ""System.Exception""
IL_00cd: stloc.s V_5
IL_00cf: ldloc.s V_5
IL_00d1: brtrue.s IL_00d5
IL_00d3: ldloc.1
IL_00d4: throw
IL_00d5: ldloc.s V_5
IL_00d7: call ""System.Runtime.ExceptionServices.ExceptionDispatchInfo System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(System.Exception)""
IL_00dc: callvirt ""void System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()""
IL_00e1: nop
IL_00e2: ldarg.0
IL_00e3: ldfld ""int C.<Main>d__0.<>s__3""
IL_00e8: stloc.s V_6
IL_00ea: ldloc.s V_6
IL_00ec: ldc.i4.1
IL_00ed: beq.s IL_00f1
IL_00ef: br.s IL_00f3
IL_00f1: leave.s IL_011d
IL_00f3: ldarg.0
IL_00f4: ldnull
IL_00f5: stfld ""object C.<Main>d__0.<>s__2""
IL_00fa: ldarg.0
IL_00fb: ldnull
IL_00fc: stfld ""C C.<Main>d__0.<>s__1""
IL_0101: leave.s IL_011d
}
catch System.Exception
{
IL_0103: stloc.s V_5
IL_0105: ldarg.0
IL_0106: ldc.i4.s -2
IL_0108: stfld ""int C.<Main>d__0.<>1__state""
IL_010d: ldarg.0
IL_010e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder""
IL_0113: ldloc.s V_5
IL_0115: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_011a: nop
IL_011b: leave.s IL_0131
}
IL_011d: ldarg.0
IL_011e: ldc.i4.s -2
IL_0120: stfld ""int C.<Main>d__0.<>1__state""
IL_0125: ldarg.0
IL_0126: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder""
IL_012b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_0130: nop
IL_0131: ret
}");
}
[Fact]
public void TestWithNullExpression()
{
string source = @"
class C
{
public static async System.Threading.Tasks.Task Main()
{
await using (null)
{
System.Console.Write(""body"");
return;
}
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "body");
}
[Fact]
public void TestWithMethodName()
{
string source = @"
class C
{
public static async System.Threading.Tasks.Task Main()
{
await using (Main)
{
}
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition });
comp.VerifyDiagnostics(
// (6,22): error CS8410: 'method group': type used in an async using statement must be implicitly convertible to 'System.IAsyncDisposable'
// await using (Main)
Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "Main").WithArguments("method group").WithLocation(6, 22)
);
}
[Fact]
public void TestWithDynamicExpression()
{
string source = @"
class C : System.IAsyncDisposable
{
public static async System.Threading.Tasks.Task Main()
{
dynamic d = new C();
await using (d)
{
System.Console.Write(""body "");
return;
}
}
public System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write(""DisposeAsync"");
return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask);
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe, references: new[] { CSharpRef });
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "body DisposeAsync");
}
[Fact]
public void TestWithStructExpression()
{
string source = @"
struct S : System.IAsyncDisposable
{
public static async System.Threading.Tasks.Task Main()
{
await using (new S())
{
System.Console.Write(""body "");
return;
}
}
public System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write(""DisposeAsync"");
return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask);
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "body DisposeAsync");
verifier.VerifyIL("S.<Main>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 298 (0x12a)
.maxstack 3
.locals init (int V_0,
object V_1,
System.Runtime.CompilerServices.ValueTaskAwaiter V_2,
System.Threading.Tasks.ValueTask V_3,
S.<Main>d__0 V_4,
System.Exception V_5,
int V_6)
IL_0000: ldarg.0
IL_0001: ldfld ""int S.<Main>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_000c
IL_000a: br.s IL_0011
IL_000c: br IL_0098
IL_0011: nop
IL_0012: ldarg.0
IL_0013: ldflda ""S S.<Main>d__0.<>s__1""
IL_0018: initobj ""S""
IL_001e: ldarg.0
IL_001f: ldnull
IL_0020: stfld ""object S.<Main>d__0.<>s__2""
IL_0025: ldarg.0
IL_0026: ldc.i4.0
IL_0027: stfld ""int S.<Main>d__0.<>s__3""
.try
{
IL_002c: nop
IL_002d: ldstr ""body ""
IL_0032: call ""void System.Console.Write(string)""
IL_0037: nop
IL_0038: br.s IL_003a
IL_003a: ldarg.0
IL_003b: ldc.i4.1
IL_003c: stfld ""int S.<Main>d__0.<>s__3""
IL_0041: leave.s IL_004d
}
catch object
{
IL_0043: stloc.1
IL_0044: ldarg.0
IL_0045: ldloc.1
IL_0046: stfld ""object S.<Main>d__0.<>s__2""
IL_004b: leave.s IL_004d
}
IL_004d: ldarg.0
IL_004e: ldflda ""S S.<Main>d__0.<>s__1""
IL_0053: constrained. ""S""
IL_0059: callvirt ""System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()""
IL_005e: stloc.3
IL_005f: ldloca.s V_3
IL_0061: call ""System.Runtime.CompilerServices.ValueTaskAwaiter System.Threading.Tasks.ValueTask.GetAwaiter()""
IL_0066: stloc.2
IL_0067: ldloca.s V_2
IL_0069: call ""bool System.Runtime.CompilerServices.ValueTaskAwaiter.IsCompleted.get""
IL_006e: brtrue.s IL_00b4
IL_0070: ldarg.0
IL_0071: ldc.i4.0
IL_0072: dup
IL_0073: stloc.0
IL_0074: stfld ""int S.<Main>d__0.<>1__state""
IL_0079: ldarg.0
IL_007a: ldloc.2
IL_007b: stfld ""System.Runtime.CompilerServices.ValueTaskAwaiter S.<Main>d__0.<>u__1""
IL_0080: ldarg.0
IL_0081: stloc.s V_4
IL_0083: ldarg.0
IL_0084: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder S.<Main>d__0.<>t__builder""
IL_0089: ldloca.s V_2
IL_008b: ldloca.s V_4
IL_008d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.ValueTaskAwaiter, S.<Main>d__0>(ref System.Runtime.CompilerServices.ValueTaskAwaiter, ref S.<Main>d__0)""
IL_0092: nop
IL_0093: leave IL_0129
IL_0098: ldarg.0
IL_0099: ldfld ""System.Runtime.CompilerServices.ValueTaskAwaiter S.<Main>d__0.<>u__1""
IL_009e: stloc.2
IL_009f: ldarg.0
IL_00a0: ldflda ""System.Runtime.CompilerServices.ValueTaskAwaiter S.<Main>d__0.<>u__1""
IL_00a5: initobj ""System.Runtime.CompilerServices.ValueTaskAwaiter""
IL_00ab: ldarg.0
IL_00ac: ldc.i4.m1
IL_00ad: dup
IL_00ae: stloc.0
IL_00af: stfld ""int S.<Main>d__0.<>1__state""
IL_00b4: ldloca.s V_2
IL_00b6: call ""void System.Runtime.CompilerServices.ValueTaskAwaiter.GetResult()""
IL_00bb: nop
IL_00bc: ldarg.0
IL_00bd: ldfld ""object S.<Main>d__0.<>s__2""
IL_00c2: stloc.1
IL_00c3: ldloc.1
IL_00c4: brfalse.s IL_00e1
IL_00c6: ldloc.1
IL_00c7: isinst ""System.Exception""
IL_00cc: stloc.s V_5
IL_00ce: ldloc.s V_5
IL_00d0: brtrue.s IL_00d4
IL_00d2: ldloc.1
IL_00d3: throw
IL_00d4: ldloc.s V_5
IL_00d6: call ""System.Runtime.ExceptionServices.ExceptionDispatchInfo System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(System.Exception)""
IL_00db: callvirt ""void System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()""
IL_00e0: nop
IL_00e1: ldarg.0
IL_00e2: ldfld ""int S.<Main>d__0.<>s__3""
IL_00e7: stloc.s V_6
IL_00e9: ldloc.s V_6
IL_00eb: ldc.i4.1
IL_00ec: beq.s IL_00f0
IL_00ee: br.s IL_00f2
IL_00f0: leave.s IL_0115
IL_00f2: ldarg.0
IL_00f3: ldnull
IL_00f4: stfld ""object S.<Main>d__0.<>s__2""
IL_00f9: leave.s IL_0115
}
catch System.Exception
{
IL_00fb: stloc.s V_5
IL_00fd: ldarg.0
IL_00fe: ldc.i4.s -2
IL_0100: stfld ""int S.<Main>d__0.<>1__state""
IL_0105: ldarg.0
IL_0106: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder S.<Main>d__0.<>t__builder""
IL_010b: ldloc.s V_5
IL_010d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_0112: nop
IL_0113: leave.s IL_0129
}
IL_0115: ldarg.0
IL_0116: ldc.i4.s -2
IL_0118: stfld ""int S.<Main>d__0.<>1__state""
IL_011d: ldarg.0
IL_011e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder S.<Main>d__0.<>t__builder""
IL_0123: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_0128: nop
IL_0129: ret
}");
}
[Fact]
public void Struct_ExplicitImplementation()
{
string source =
@"using System;
using System.Threading.Tasks;
class C
{
internal bool _disposed;
}
struct S : IAsyncDisposable
{
C _c;
S(C c)
{
_c = c;
}
static async Task Main()
{
var s = new S(new C());
await using (s)
{
}
Console.WriteLine(s._c._disposed);
}
ValueTask IAsyncDisposable.DisposeAsync()
{
_c._disposed = true;
return new ValueTask(Task.CompletedTask);
}
}";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "True");
}
[Fact]
public void TestWithNullableExpression()
{
string source = @"
struct S : System.IAsyncDisposable
{
public static async System.Threading.Tasks.Task Main()
{
S? s = new S();
await using (s)
{
System.Console.Write(""body "");
return;
}
}
public System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write(""DisposeAsync"");
return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask);
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "body DisposeAsync");
}
[Fact]
public void TestWithNullNullableExpression()
{
string source = @"
struct S : System.IAsyncDisposable
{
public static async System.Threading.Tasks.Task Main()
{
S? s = null;
await using (s)
{
System.Console.Write(""body"");
return;
}
}
public System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write(""NOT RELEVANT"");
return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask);
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "body");
}
[Fact]
[WorkItem(24267, "https://github.com/dotnet/roslyn/issues/24267")]
public void AssignsInAsyncWithAwaitUsing()
{
var comp = CreateCompilationWithTasksExtensions(@"
class C
{
public static void M2()
{
int a=0, x, y, z;
L1();
a++;
x++;
y++;
z++;
async void L1()
{
x = 0;
await using (null) { }
y = 0;
// local function exists with a pending branch from the async using, in which `y` was not assigned
}
}
}" + IAsyncDisposableDefinition);
comp.VerifyDiagnostics(
// (10,9): error CS0165: Use of unassigned local variable 'y'
// y++;
Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(10, 9),
// (11,9): error CS0165: Use of unassigned local variable 'z'
// z++;
Diagnostic(ErrorCode.ERR_UseDefViolation, "z").WithArguments("z").WithLocation(11, 9)
);
}
[Fact]
public void TestWithMultipleResources()
{
string source = @"
class S : System.IAsyncDisposable
{
private int _i;
S(int i)
{
System.Console.Write($""ctor{i} "");
_i = i;
}
public static async System.Threading.Tasks.Task Main()
{
await using (S s1 = new S(1), s2 = new S(2))
{
System.Console.Write(""body "");
return;
}
}
public async System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write($""dispose{_i}_start "");
await System.Threading.Tasks.Task.Yield();
System.Console.Write($""dispose{_i}_end "");
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "ctor1 ctor2 body dispose2_start dispose2_end dispose1_start dispose1_end");
}
[Fact]
public void TestWithMultipleResourcesAndException()
{
string source = @"
class S : System.IAsyncDisposable
{
private int _i;
S(int i)
{
System.Console.Write($""ctor{i} "");
_i = i;
}
public static async System.Threading.Tasks.Task Main()
{
try
{
await using (S s1 = new S(1), s2 = new S(2))
{
System.Console.Write(""body "");
throw new System.Exception();
}
}
catch (System.Exception)
{
System.Console.Write(""caught"");
}
}
public System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write($""dispose{_i} "");
return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask);
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "ctor1 ctor2 body dispose2 dispose1 caught");
}
[Fact]
public void TestWithMultipleResourcesAndExceptionInSecondResource()
{
string source = @"
class S : System.IAsyncDisposable
{
private int _i;
S(int i)
{
System.Console.Write($""ctor{i} "");
if (i == 1)
{
_i = i;
}
else
{
throw new System.Exception();
}
}
public static async System.Threading.Tasks.Task Main()
{
try
{
await using (S s1 = new S(1), s2 = new S(2))
{
System.Console.Write(""SKIPPED"");
}
}
catch (System.Exception)
{
System.Console.Write(""caught"");
}
}
public System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write($""dispose{_i} "");
return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask);
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "ctor1 ctor2 dispose1 caught");
}
[Fact]
public void TestAwaitExpressionInfo_IEquatable()
{
string source = @"
public class C
{
void GetAwaiter() { }
void GetResult() { }
bool IsCompleted => true;
}
public class D
{
void GetAwaiter() { }
void GetResult() { }
bool IsCompleted => true;
}
";
var comp = CreateCompilation(source);
var getAwaiter1 = (MethodSymbol)comp.GetMember("C.GetAwaiter");
var isCompleted1 = (PropertySymbol)comp.GetMember("C.IsCompleted");
var getResult1 = (MethodSymbol)comp.GetMember("C.GetResult");
var first = new AwaitExpressionInfo(getAwaiter1.GetPublicSymbol(), isCompleted1.GetPublicSymbol(), getResult1.GetPublicSymbol(), false);
var nulls1 = new AwaitExpressionInfo(null, isCompleted1.GetPublicSymbol(), getResult1.GetPublicSymbol(), false);
var nulls2 = new AwaitExpressionInfo(getAwaiter1.GetPublicSymbol(), null, getResult1.GetPublicSymbol(), false);
var nulls3 = new AwaitExpressionInfo(getAwaiter1.GetPublicSymbol(), isCompleted1.GetPublicSymbol(), null, false);
var nulls4 = new AwaitExpressionInfo(getAwaiter1.GetPublicSymbol(), isCompleted1.GetPublicSymbol(), null, true);
Assert.False(first.Equals(nulls1));
Assert.False(first.Equals(nulls2));
Assert.False(first.Equals(nulls3));
Assert.False(first.Equals(nulls4));
Assert.False(nulls1.Equals(first));
Assert.False(nulls2.Equals(first));
Assert.False(nulls3.Equals(first));
Assert.False(nulls4.Equals(first));
_ = nulls1.GetHashCode();
_ = nulls2.GetHashCode();
_ = nulls3.GetHashCode();
_ = nulls4.GetHashCode();
object nullObj = null;
Assert.False(first.Equals(nullObj));
var getAwaiter2 = (MethodSymbol)comp.GetMember("D.GetAwaiter");
var isCompleted2 = (PropertySymbol)comp.GetMember("D.IsCompleted");
var getResult2 = (MethodSymbol)comp.GetMember("D.GetResult");
var second1 = new AwaitExpressionInfo(getAwaiter2.GetPublicSymbol(), isCompleted1.GetPublicSymbol(), getResult1.GetPublicSymbol(), false);
var second2 = new AwaitExpressionInfo(getAwaiter1.GetPublicSymbol(), isCompleted2.GetPublicSymbol(), getResult1.GetPublicSymbol(), false);
var second3 = new AwaitExpressionInfo(getAwaiter1.GetPublicSymbol(), isCompleted1.GetPublicSymbol(), getResult2.GetPublicSymbol(), false);
var second4 = new AwaitExpressionInfo(getAwaiter2.GetPublicSymbol(), isCompleted2.GetPublicSymbol(), getResult2.GetPublicSymbol(), false);
Assert.False(first.Equals(second1));
Assert.False(first.Equals(second2));
Assert.False(first.Equals(second3));
Assert.False(first.Equals(second4));
Assert.False(second1.Equals(first));
Assert.False(second2.Equals(first));
Assert.False(second3.Equals(first));
Assert.False(second4.Equals(first));
Assert.True(first.Equals(first));
Assert.True(first.Equals((object)first));
var another = new AwaitExpressionInfo(getAwaiter1.GetPublicSymbol(), isCompleted1.GetPublicSymbol(), getResult1.GetPublicSymbol(), false);
Assert.True(first.GetHashCode() == another.GetHashCode());
}
[Fact]
[WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")]
public void TestPatternBasedDisposal_ExtensionMethod()
{
string source = @"
public class C
{
public static async System.Threading.Tasks.Task<int> Main()
{
await using (var x = new C())
{
}
return 1;
}
}
public static class Extensions
{
public static System.Threading.Tasks.ValueTask DisposeAsync(this C c)
=> throw null;
}
";
// extension methods do not contribute to pattern-based disposal
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,22): error CS8410: 'C': type used in an async using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method.
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "var x = new C()").WithArguments("C").WithLocation(6, 22)
);
}
[Fact]
[WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")]
public void TestPatternBasedDisposal_TwoOverloads()
{
string source = @"
public class C
{
public static async System.Threading.Tasks.Task<int> Main()
{
await using (var x = new C())
{
}
return 1;
}
public async System.Threading.Tasks.ValueTask DisposeAsync(int i = 0)
{
System.Console.Write($""dispose"");
await System.Threading.Tasks.Task.Yield();
}
public System.Threading.Tasks.ValueTask DisposeAsync(params string[] s)
=> throw null;
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "dispose");
}
[Fact]
[WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")]
public void TestPatternBasedDisposal_Expression_ExtensionMethod()
{
string source = @"
public class C
{
public static async System.Threading.Tasks.Task<int> Main()
{
await using (new C())
{
}
return 1;
}
}
public static class Extensions
{
public static System.Threading.Tasks.ValueTask DisposeAsync(this C c)
=> throw null;
}
";
// extension methods do not contribute to pattern-based disposal
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (6,22): error CS8410: 'C': type used in an async using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method.
// await using (new C())
Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "new C()").WithArguments("C").WithLocation(6, 22)
);
}
[Fact]
[WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")]
public void TestPatternBasedDisposal_Expression_InstanceMethod()
{
string source = @"
public class C
{
public static async System.Threading.Tasks.Task<int> Main()
{
await using (new C())
{
System.Console.Write(""using "");
}
System.Console.Write(""return"");
return 1;
}
public async System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write($""dispose_start "");
await System.Threading.Tasks.Task.Yield();
System.Console.Write($""dispose_end "");
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "using dispose_start dispose_end return");
}
[Fact]
[WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")]
public void TestPatternBasedDisposal_InstanceMethod()
{
string source = @"
public class C
{
public static async System.Threading.Tasks.Task<int> Main()
{
await using (var x = new C())
{
System.Console.Write(""using "");
}
System.Console.Write(""return"");
return 1;
}
public async System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write($""dispose_start "");
await System.Threading.Tasks.Task.Yield();
System.Console.Write($""dispose_end "");
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "using dispose_start dispose_end return");
}
[Fact]
[WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")]
public void TestPatternBasedDisposal_InterfacePreferredOverInstanceMethod()
{
string source = @"
public class C : System.IAsyncDisposable
{
public static async System.Threading.Tasks.Task<int> Main()
{
await using (var x = new C())
{
System.Console.Write(""using "");
}
System.Console.Write(""return"");
return 1;
}
async System.Threading.Tasks.ValueTask System.IAsyncDisposable.DisposeAsync()
{
System.Console.Write($""dispose_start "");
await System.Threading.Tasks.Task.Yield();
System.Console.Write($""dispose_end "");
}
public System.Threading.Tasks.ValueTask DisposeAsync()
=> throw null;
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "using dispose_start dispose_end return");
}
[Fact]
[WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")]
public void TestPatternBasedDisposal_InstanceMethod_OptionalParameter()
{
string source = @"
public class C
{
public static async System.Threading.Tasks.Task<int> Main()
{
await using (var x = new C())
{
System.Console.Write(""using "");
}
System.Console.Write(""return"");
return 1;
}
public async System.Threading.Tasks.ValueTask DisposeAsync(int i = 0)
{
System.Console.Write($""dispose_start "");
await System.Threading.Tasks.Task.Yield();
System.Console.Write($""dispose_end "");
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "using dispose_start dispose_end return");
}
[Fact]
[WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")]
public void TestPatternBasedDisposal_InstanceMethod_ParamsParameter()
{
string source = @"
public class C
{
public static async System.Threading.Tasks.Task<int> Main()
{
await using (var x = new C())
{
System.Console.Write(""using "");
}
System.Console.Write(""return"");
return 1;
}
public async System.Threading.Tasks.ValueTask DisposeAsync(params int[] x)
{
System.Console.Write($""dispose_start "");
await System.Threading.Tasks.Task.Yield();
System.Console.Write($""dispose_end({x.Length}) "");
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "using dispose_start dispose_end(0) return");
}
[Fact]
[WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")]
public void TestPatternBasedDisposal_InstanceMethod_ReturningVoid()
{
string source = @"
public class C
{
public static async System.Threading.Tasks.Task<int> Main()
{
await using (var x = new C())
{
}
return 1;
}
public void DisposeAsync()
{
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition });
comp.VerifyDiagnostics(
// (6,22): error CS4008: Cannot await 'void'
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_BadAwaitArgVoidCall, "var x = new C()").WithLocation(6, 22)
);
}
[Fact]
[WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")]
public void TestPatternBasedDisposal_InstanceMethod_ReturningInt()
{
string source = @"
public class C
{
public static async System.Threading.Tasks.Task<int> Main()
{
await using (var x = new C())
{
}
return 1;
}
public int DisposeAsync()
=> throw null;
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition });
comp.VerifyDiagnostics(
// (6,22): error CS1061: 'int' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?)
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "var x = new C()").WithArguments("int", "GetAwaiter").WithLocation(6, 22)
);
}
[Fact]
[WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")]
public void TestPatternBasedDisposal_InstanceMethod_Inaccessible()
{
string source = @"
public class D
{
public static async System.Threading.Tasks.Task<int> Main()
{
await using (var x = new C())
{
}
return 1;
}
}
public class C
{
private System.Threading.Tasks.ValueTask DisposeAsync()
=> throw null;
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition });
comp.VerifyDiagnostics(
// (6,22): error CS0122: 'C.DisposeAsync()' is inaccessible due to its protection level
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_BadAccess, "var x = new C()").WithArguments("C.DisposeAsync()").WithLocation(6, 22),
// (6,22): error CS8410: 'C': type used in an async using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method.
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "var x = new C()").WithArguments("C").WithLocation(6, 22)
);
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
[WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")]
public void TestPatternBasedDisposal_InstanceMethod_UsingDeclaration()
{
string source = @"
public class C
{
public static async System.Threading.Tasks.Task<int> Main()
{
{
await using var x = new C();
System.Console.Write(""using "");
}
System.Console.Write(""return"");
return 1;
}
public async System.Threading.Tasks.ValueTask DisposeAsync()
{
System.Console.Write($""dispose_start "");
await System.Threading.Tasks.Task.Yield();
System.Console.Write($""dispose_end "");
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
var verifier = CompileAndVerify(comp, expectedOutput: "using dispose_start dispose_end return");
// Sequence point higlights `await using ...`
verifier.VerifyIL("C.<Main>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 303 (0x12f)
.maxstack 3
.locals init (int V_0,
int V_1,
object V_2,
System.Runtime.CompilerServices.ValueTaskAwaiter V_3,
System.Threading.Tasks.ValueTask V_4,
C.<Main>d__0 V_5,
System.Exception V_6)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<Main>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: <hidden>
IL_0007: ldloc.0
IL_0008: brfalse.s IL_000c
IL_000a: br.s IL_0011
IL_000c: br IL_0091
// sequence point: {
IL_0011: nop
// sequence point: {
IL_0012: nop
// sequence point: await using var x = new C();
IL_0013: ldarg.0
IL_0014: newobj ""C..ctor()""
IL_0019: stfld ""C C.<Main>d__0.<x>5__1""
// sequence point: <hidden>
IL_001e: ldarg.0
IL_001f: ldnull
IL_0020: stfld ""object C.<Main>d__0.<>s__2""
IL_0025: ldarg.0
IL_0026: ldc.i4.0
IL_0027: stfld ""int C.<Main>d__0.<>s__3""
.try
{
// sequence point: System.Console.Write(""using "");
IL_002c: ldstr ""using ""
IL_0031: call ""void System.Console.Write(string)""
IL_0036: nop
// sequence point: <hidden>
IL_0037: leave.s IL_0043
}
catch object
{
// sequence point: <hidden>
IL_0039: stloc.2
IL_003a: ldarg.0
IL_003b: ldloc.2
IL_003c: stfld ""object C.<Main>d__0.<>s__2""
IL_0041: leave.s IL_0043
}
// sequence point: <hidden>
IL_0043: ldarg.0
IL_0044: ldfld ""C C.<Main>d__0.<x>5__1""
IL_0049: brfalse.s IL_00b5
IL_004b: ldarg.0
IL_004c: ldfld ""C C.<Main>d__0.<x>5__1""
IL_0051: callvirt ""System.Threading.Tasks.ValueTask C.DisposeAsync()""
IL_0056: stloc.s V_4
IL_0058: ldloca.s V_4
IL_005a: call ""System.Runtime.CompilerServices.ValueTaskAwaiter System.Threading.Tasks.ValueTask.GetAwaiter()""
IL_005f: stloc.3
// sequence point: <hidden>
IL_0060: ldloca.s V_3
IL_0062: call ""bool System.Runtime.CompilerServices.ValueTaskAwaiter.IsCompleted.get""
IL_0067: brtrue.s IL_00ad
IL_0069: ldarg.0
IL_006a: ldc.i4.0
IL_006b: dup
IL_006c: stloc.0
IL_006d: stfld ""int C.<Main>d__0.<>1__state""
// async: yield
IL_0072: ldarg.0
IL_0073: ldloc.3
IL_0074: stfld ""System.Runtime.CompilerServices.ValueTaskAwaiter C.<Main>d__0.<>u__1""
IL_0079: ldarg.0
IL_007a: stloc.s V_5
IL_007c: ldarg.0
IL_007d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<Main>d__0.<>t__builder""
IL_0082: ldloca.s V_3
IL_0084: ldloca.s V_5
IL_0086: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.ValueTaskAwaiter, C.<Main>d__0>(ref System.Runtime.CompilerServices.ValueTaskAwaiter, ref C.<Main>d__0)""
IL_008b: nop
IL_008c: leave IL_012e
// async: resume
IL_0091: ldarg.0
IL_0092: ldfld ""System.Runtime.CompilerServices.ValueTaskAwaiter C.<Main>d__0.<>u__1""
IL_0097: stloc.3
IL_0098: ldarg.0
IL_0099: ldflda ""System.Runtime.CompilerServices.ValueTaskAwaiter C.<Main>d__0.<>u__1""
IL_009e: initobj ""System.Runtime.CompilerServices.ValueTaskAwaiter""
IL_00a4: ldarg.0
IL_00a5: ldc.i4.m1
IL_00a6: dup
IL_00a7: stloc.0
IL_00a8: stfld ""int C.<Main>d__0.<>1__state""
IL_00ad: ldloca.s V_3
IL_00af: call ""void System.Runtime.CompilerServices.ValueTaskAwaiter.GetResult()""
IL_00b4: nop
// sequence point: <hidden>
IL_00b5: ldarg.0
IL_00b6: ldfld ""object C.<Main>d__0.<>s__2""
IL_00bb: stloc.2
IL_00bc: ldloc.2
IL_00bd: brfalse.s IL_00da
IL_00bf: ldloc.2
IL_00c0: isinst ""System.Exception""
IL_00c5: stloc.s V_6
IL_00c7: ldloc.s V_6
IL_00c9: brtrue.s IL_00cd
IL_00cb: ldloc.2
IL_00cc: throw
IL_00cd: ldloc.s V_6
IL_00cf: call ""System.Runtime.ExceptionServices.ExceptionDispatchInfo System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(System.Exception)""
IL_00d4: callvirt ""void System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()""
IL_00d9: nop
IL_00da: ldarg.0
IL_00db: ldfld ""int C.<Main>d__0.<>s__3""
IL_00e0: pop
IL_00e1: ldarg.0
IL_00e2: ldnull
IL_00e3: stfld ""object C.<Main>d__0.<>s__2""
// sequence point: }
IL_00e8: nop
IL_00e9: ldarg.0
IL_00ea: ldnull
IL_00eb: stfld ""C C.<Main>d__0.<x>5__1""
// sequence point: System.Console.Write(""return"");
IL_00f0: ldstr ""return""
IL_00f5: call ""void System.Console.Write(string)""
IL_00fa: nop
// sequence point: return 1;
IL_00fb: ldc.i4.1
IL_00fc: stloc.1
IL_00fd: leave.s IL_0119
}
catch System.Exception
{
// async: catch handler, sequence point: <hidden>
IL_00ff: stloc.s V_6
IL_0101: ldarg.0
IL_0102: ldc.i4.s -2
IL_0104: stfld ""int C.<Main>d__0.<>1__state""
IL_0109: ldarg.0
IL_010a: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<Main>d__0.<>t__builder""
IL_010f: ldloc.s V_6
IL_0111: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)""
IL_0116: nop
IL_0117: leave.s IL_012e
}
// sequence point: }
IL_0119: ldarg.0
IL_011a: ldc.i4.s -2
IL_011c: stfld ""int C.<Main>d__0.<>1__state""
// sequence point: <hidden>
IL_0121: ldarg.0
IL_0122: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<Main>d__0.<>t__builder""
IL_0127: ldloc.1
IL_0128: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)""
IL_012d: nop
IL_012e: ret
}
", sequencePoints: "C+<Main>d__0.MoveNext", source: source);
}
[Fact]
[WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")]
public void TestPatternBasedDisposal_Awaitable()
{
string source = @"
public struct C
{
public static async System.Threading.Tasks.Task<int> Main()
{
{
await using var x = new C();
System.Console.Write(""using "");
}
System.Console.Write(""return"");
return 1;
}
public Awaitable DisposeAsync()
{
System.Console.Write($""dispose_start "");
System.Console.Write($""dispose_end "");
return new Awaitable();
}
}
public class Awaitable
{
public Awaiter GetAwaiter() { return new Awaiter(); }
}
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public bool IsCompleted { get { return true; } }
public bool GetResult() { return true; }
public void OnCompleted(System.Action continuation) { }
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "using dispose_start dispose_end return");
}
[Fact]
[WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")]
public void TestPatternBasedDisposal_ReturnsTask()
{
string source = @"
public struct C
{
public static async System.Threading.Tasks.Task<int> Main()
{
{
await using var x = new C();
System.Console.Write(""using "");
}
System.Console.Write(""return"");
return 1;
}
public async System.Threading.Tasks.Task DisposeAsync()
{
System.Console.Write($""dispose_start "");
await System.Threading.Tasks.Task.Yield();
System.Console.Write($""dispose_end "");
}
}
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "using dispose_start dispose_end return");
}
[Fact]
[WorkItem(32316, "https://github.com/dotnet/roslyn/issues/32316")]
public void TestPatternBasedDisposal_ReturnsTaskOfInt()
{
string source = @"
public struct C
{
public static async System.Threading.Tasks.Task<int> Main()
{
{
await using var x = new C();
System.Console.Write(""using "");
}
System.Console.Write(""return"");
return 1;
}
public async System.Threading.Tasks.Task<int> DisposeAsync()
{
System.Console.Write($""dispose_start "");
await System.Threading.Tasks.Task.Yield();
System.Console.Write($""dispose_end "");
return 1;
}
}
";
// it's okay to await `Task<int>` even if we don't care about the result
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "using dispose_start dispose_end return");
}
[Fact]
public void TestInRegularMethod()
{
string source = @"
class C
{
void M()
{
await using var x = new object();
await using (var y = new object()) { }
}
}";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition });
comp.VerifyDiagnostics(
// (6,9): error CS8410: 'object': type used in an async using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method.
// await using var x = new object();
Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "await using var x = new object();").WithArguments("object").WithLocation(6, 9),
// (6,9): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
// await using var x = new object();
Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await").WithLocation(6, 9),
// (7,9): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
// await using (var y = new object()) { }
Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await").WithLocation(7, 9),
// (7,22): error CS8410: 'object': type used in an async using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method.
// await using (var y = new object()) { }
Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "var y = new object()").WithArguments("object").WithLocation(7, 22)
);
}
[Fact]
[WorkItem(30956, "https://github.com/dotnet/roslyn/issues/30956")]
public void GetAwaiterBoxingConversion()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
struct StructAwaitable { }
class Disposable
{
public StructAwaitable DisposeAsync() => new StructAwaitable();
}
static class Extensions
{
public static TaskAwaiter GetAwaiter(this object x)
{
if (x == null) throw new ArgumentNullException(nameof(x));
Console.Write(x);
return Task.CompletedTask.GetAwaiter();
}
}
class Program
{
static async Task Main()
{
await using (new Disposable())
{
}
}
}";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: "StructAwaitable");
}
}
}
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Portable/Symbols/Retargeting/RetargetingTypeParameterSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using System.Diagnostics;
using System.Globalization;
namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting
{
/// <summary>
/// Represents a type parameter in a RetargetingModuleSymbol. Essentially this is a wrapper around
/// another TypeParameterSymbol that is responsible for retargeting symbols from one assembly to another.
/// It can retarget symbols for multiple assemblies at the same time.
/// </summary>
internal sealed class RetargetingTypeParameterSymbol
: WrappedTypeParameterSymbol
{
/// <summary>
/// Owning RetargetingModuleSymbol.
/// </summary>
private readonly RetargetingModuleSymbol _retargetingModule;
/// <summary>
/// Retargeted custom attributes
/// </summary>
private ImmutableArray<CSharpAttributeData> _lazyCustomAttributes;
public RetargetingTypeParameterSymbol(RetargetingModuleSymbol retargetingModule, TypeParameterSymbol underlyingTypeParameter)
: base(underlyingTypeParameter)
{
Debug.Assert((object)retargetingModule != null);
Debug.Assert(!(underlyingTypeParameter is RetargetingTypeParameterSymbol));
_retargetingModule = retargetingModule;
}
private RetargetingModuleSymbol.RetargetingSymbolTranslator RetargetingTranslator
{
get
{
return _retargetingModule.RetargetingTranslator;
}
}
public override Symbol ContainingSymbol
{
get
{
return this.RetargetingTranslator.Retarget(_underlyingTypeParameter.ContainingSymbol);
}
}
public override ImmutableArray<CSharpAttributeData> GetAttributes()
{
return this.RetargetingTranslator.GetRetargetedAttributes(_underlyingTypeParameter.GetAttributes(), ref _lazyCustomAttributes);
}
public override AssemblySymbol ContainingAssembly
{
get
{
return _retargetingModule.ContainingAssembly;
}
}
internal override ModuleSymbol ContainingModule
{
get
{
return _retargetingModule;
}
}
internal override ImmutableArray<TypeWithAnnotations> GetConstraintTypes(ConsList<TypeParameterSymbol> inProgress)
{
return this.RetargetingTranslator.Retarget(_underlyingTypeParameter.GetConstraintTypes(inProgress));
}
internal override bool? IsNotNullable
{
get
{
return _underlyingTypeParameter.IsNotNullable;
}
}
internal override ImmutableArray<NamedTypeSymbol> GetInterfaces(ConsList<TypeParameterSymbol> inProgress)
{
return this.RetargetingTranslator.Retarget(_underlyingTypeParameter.GetInterfaces(inProgress));
}
internal override NamedTypeSymbol GetEffectiveBaseClass(ConsList<TypeParameterSymbol> inProgress)
{
return this.RetargetingTranslator.Retarget(_underlyingTypeParameter.GetEffectiveBaseClass(inProgress), RetargetOptions.RetargetPrimitiveTypesByTypeCode);
}
internal override TypeSymbol GetDeducedBaseType(ConsList<TypeParameterSymbol> inProgress)
{
return this.RetargetingTranslator.Retarget(_underlyingTypeParameter.GetDeducedBaseType(inProgress), RetargetOptions.RetargetPrimitiveTypesByTypeCode);
}
internal sealed override CSharpCompilation DeclaringCompilation // perf, not correctness
{
get { return null; }
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using System.Diagnostics;
using System.Globalization;
namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting
{
/// <summary>
/// Represents a type parameter in a RetargetingModuleSymbol. Essentially this is a wrapper around
/// another TypeParameterSymbol that is responsible for retargeting symbols from one assembly to another.
/// It can retarget symbols for multiple assemblies at the same time.
/// </summary>
internal sealed class RetargetingTypeParameterSymbol
: WrappedTypeParameterSymbol
{
/// <summary>
/// Owning RetargetingModuleSymbol.
/// </summary>
private readonly RetargetingModuleSymbol _retargetingModule;
/// <summary>
/// Retargeted custom attributes
/// </summary>
private ImmutableArray<CSharpAttributeData> _lazyCustomAttributes;
public RetargetingTypeParameterSymbol(RetargetingModuleSymbol retargetingModule, TypeParameterSymbol underlyingTypeParameter)
: base(underlyingTypeParameter)
{
Debug.Assert((object)retargetingModule != null);
Debug.Assert(!(underlyingTypeParameter is RetargetingTypeParameterSymbol));
_retargetingModule = retargetingModule;
}
private RetargetingModuleSymbol.RetargetingSymbolTranslator RetargetingTranslator
{
get
{
return _retargetingModule.RetargetingTranslator;
}
}
public override Symbol ContainingSymbol
{
get
{
return this.RetargetingTranslator.Retarget(_underlyingTypeParameter.ContainingSymbol);
}
}
public override ImmutableArray<CSharpAttributeData> GetAttributes()
{
return this.RetargetingTranslator.GetRetargetedAttributes(_underlyingTypeParameter.GetAttributes(), ref _lazyCustomAttributes);
}
public override AssemblySymbol ContainingAssembly
{
get
{
return _retargetingModule.ContainingAssembly;
}
}
internal override ModuleSymbol ContainingModule
{
get
{
return _retargetingModule;
}
}
internal override ImmutableArray<TypeWithAnnotations> GetConstraintTypes(ConsList<TypeParameterSymbol> inProgress)
{
return this.RetargetingTranslator.Retarget(_underlyingTypeParameter.GetConstraintTypes(inProgress));
}
internal override bool? IsNotNullable
{
get
{
return _underlyingTypeParameter.IsNotNullable;
}
}
internal override ImmutableArray<NamedTypeSymbol> GetInterfaces(ConsList<TypeParameterSymbol> inProgress)
{
return this.RetargetingTranslator.Retarget(_underlyingTypeParameter.GetInterfaces(inProgress));
}
internal override NamedTypeSymbol GetEffectiveBaseClass(ConsList<TypeParameterSymbol> inProgress)
{
return this.RetargetingTranslator.Retarget(_underlyingTypeParameter.GetEffectiveBaseClass(inProgress), RetargetOptions.RetargetPrimitiveTypesByTypeCode);
}
internal override TypeSymbol GetDeducedBaseType(ConsList<TypeParameterSymbol> inProgress)
{
return this.RetargetingTranslator.Retarget(_underlyingTypeParameter.GetDeducedBaseType(inProgress), RetargetOptions.RetargetPrimitiveTypesByTypeCode);
}
internal sealed override CSharpCompilation DeclaringCompilation // perf, not correctness
{
get { return null; }
}
}
}
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/CoreTestUtilities/ITestErrorHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public interface ITestErrorHandler
{
/// <summary>
/// Records unexpected exceptions thrown during test executino that can't be immediately
/// reported.
/// </summary>
ImmutableList<Exception> Exceptions { get; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public interface ITestErrorHandler
{
/// <summary>
/// Records unexpected exceptions thrown during test executino that can't be immediately
/// reported.
/// </summary>
ImmutableList<Exception> Exceptions { get; }
}
}
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/Portable/Emit/EditAndContinue/AddedOrChangedMethodInfo.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.CodeGen;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Emit
{
internal readonly struct AddedOrChangedMethodInfo
{
public readonly DebugId MethodId;
// locals:
public readonly ImmutableArray<EncLocalInfo> Locals;
// lambdas, closures:
public readonly ImmutableArray<LambdaDebugInfo> LambdaDebugInfo;
public readonly ImmutableArray<ClosureDebugInfo> ClosureDebugInfo;
// state machines:
public readonly string? StateMachineTypeName;
public readonly ImmutableArray<EncHoistedLocalInfo> StateMachineHoistedLocalSlotsOpt;
public readonly ImmutableArray<Cci.ITypeReference?> StateMachineAwaiterSlotsOpt;
public AddedOrChangedMethodInfo(
DebugId methodId,
ImmutableArray<EncLocalInfo> locals,
ImmutableArray<LambdaDebugInfo> lambdaDebugInfo,
ImmutableArray<ClosureDebugInfo> closureDebugInfo,
string? stateMachineTypeName,
ImmutableArray<EncHoistedLocalInfo> stateMachineHoistedLocalSlotsOpt,
ImmutableArray<Cci.ITypeReference?> stateMachineAwaiterSlotsOpt)
{
// An updated method will carry its id over,
// an added method id has generation set to the current generation ordinal.
Debug.Assert(methodId.Generation >= 0);
// each state machine has to have awaiters:
Debug.Assert(stateMachineAwaiterSlotsOpt.IsDefault == (stateMachineTypeName == null));
// a state machine might not have hoisted variables:
Debug.Assert(stateMachineHoistedLocalSlotsOpt.IsDefault || (stateMachineTypeName != null));
MethodId = methodId;
Locals = locals;
LambdaDebugInfo = lambdaDebugInfo;
ClosureDebugInfo = closureDebugInfo;
StateMachineTypeName = stateMachineTypeName;
StateMachineHoistedLocalSlotsOpt = stateMachineHoistedLocalSlotsOpt;
StateMachineAwaiterSlotsOpt = stateMachineAwaiterSlotsOpt;
}
public AddedOrChangedMethodInfo MapTypes(SymbolMatcher map)
{
var mappedLocals = ImmutableArray.CreateRange(Locals, MapLocalInfo, map);
var mappedHoistedLocalSlots = StateMachineHoistedLocalSlotsOpt.IsDefault ? default :
ImmutableArray.CreateRange(StateMachineHoistedLocalSlotsOpt, MapHoistedLocalSlot, map);
var mappedAwaiterSlots = StateMachineAwaiterSlotsOpt.IsDefault ? default :
ImmutableArray.CreateRange(StateMachineAwaiterSlotsOpt, static (typeRef, map) => (typeRef is null) ? null : map.MapReference(typeRef), map);
return new AddedOrChangedMethodInfo(MethodId, mappedLocals, LambdaDebugInfo, ClosureDebugInfo, StateMachineTypeName, mappedHoistedLocalSlots, mappedAwaiterSlots);
}
private static EncLocalInfo MapLocalInfo(EncLocalInfo info, SymbolMatcher map)
{
Debug.Assert(!info.IsDefault);
if (info.Type is null)
{
Debug.Assert(info.Signature != null);
return info;
}
var typeRef = map.MapReference(info.Type);
RoslynDebug.AssertNotNull(typeRef);
return new EncLocalInfo(info.SlotInfo, typeRef, info.Constraints, info.Signature);
}
private static EncHoistedLocalInfo MapHoistedLocalSlot(EncHoistedLocalInfo info, SymbolMatcher map)
{
if (info.Type is null)
{
return info;
}
var typeRef = map.MapReference(info.Type);
RoslynDebug.AssertNotNull(typeRef);
return new EncHoistedLocalInfo(info.SlotInfo, typeRef);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.CodeGen;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Emit
{
internal readonly struct AddedOrChangedMethodInfo
{
public readonly DebugId MethodId;
// locals:
public readonly ImmutableArray<EncLocalInfo> Locals;
// lambdas, closures:
public readonly ImmutableArray<LambdaDebugInfo> LambdaDebugInfo;
public readonly ImmutableArray<ClosureDebugInfo> ClosureDebugInfo;
// state machines:
public readonly string? StateMachineTypeName;
public readonly ImmutableArray<EncHoistedLocalInfo> StateMachineHoistedLocalSlotsOpt;
public readonly ImmutableArray<Cci.ITypeReference?> StateMachineAwaiterSlotsOpt;
public AddedOrChangedMethodInfo(
DebugId methodId,
ImmutableArray<EncLocalInfo> locals,
ImmutableArray<LambdaDebugInfo> lambdaDebugInfo,
ImmutableArray<ClosureDebugInfo> closureDebugInfo,
string? stateMachineTypeName,
ImmutableArray<EncHoistedLocalInfo> stateMachineHoistedLocalSlotsOpt,
ImmutableArray<Cci.ITypeReference?> stateMachineAwaiterSlotsOpt)
{
// An updated method will carry its id over,
// an added method id has generation set to the current generation ordinal.
Debug.Assert(methodId.Generation >= 0);
// each state machine has to have awaiters:
Debug.Assert(stateMachineAwaiterSlotsOpt.IsDefault == (stateMachineTypeName == null));
// a state machine might not have hoisted variables:
Debug.Assert(stateMachineHoistedLocalSlotsOpt.IsDefault || (stateMachineTypeName != null));
MethodId = methodId;
Locals = locals;
LambdaDebugInfo = lambdaDebugInfo;
ClosureDebugInfo = closureDebugInfo;
StateMachineTypeName = stateMachineTypeName;
StateMachineHoistedLocalSlotsOpt = stateMachineHoistedLocalSlotsOpt;
StateMachineAwaiterSlotsOpt = stateMachineAwaiterSlotsOpt;
}
public AddedOrChangedMethodInfo MapTypes(SymbolMatcher map)
{
var mappedLocals = ImmutableArray.CreateRange(Locals, MapLocalInfo, map);
var mappedHoistedLocalSlots = StateMachineHoistedLocalSlotsOpt.IsDefault ? default :
ImmutableArray.CreateRange(StateMachineHoistedLocalSlotsOpt, MapHoistedLocalSlot, map);
var mappedAwaiterSlots = StateMachineAwaiterSlotsOpt.IsDefault ? default :
ImmutableArray.CreateRange(StateMachineAwaiterSlotsOpt, static (typeRef, map) => (typeRef is null) ? null : map.MapReference(typeRef), map);
return new AddedOrChangedMethodInfo(MethodId, mappedLocals, LambdaDebugInfo, ClosureDebugInfo, StateMachineTypeName, mappedHoistedLocalSlots, mappedAwaiterSlots);
}
private static EncLocalInfo MapLocalInfo(EncLocalInfo info, SymbolMatcher map)
{
Debug.Assert(!info.IsDefault);
if (info.Type is null)
{
Debug.Assert(info.Signature != null);
return info;
}
var typeRef = map.MapReference(info.Type);
RoslynDebug.AssertNotNull(typeRef);
return new EncLocalInfo(info.SlotInfo, typeRef, info.Constraints, info.Signature);
}
private static EncHoistedLocalInfo MapHoistedLocalSlot(EncHoistedLocalInfo info, SymbolMatcher map)
{
if (info.Type is null)
{
return info;
}
var typeRef = map.MapReference(info.Type);
RoslynDebug.AssertNotNull(typeRef);
return new EncHoistedLocalInfo(info.SlotInfo, typeRef);
}
}
}
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/Portable/InternalUtilities/BitArithmeticUtilities.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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 Roslyn.Utilities
{
internal static class BitArithmeticUtilities
{
public static int CountBits(int v)
{
return CountBits(unchecked((uint)v));
}
public static int CountBits(uint v)
{
unchecked
{
v -= ((v >> 1) & 0x55555555u);
v = (v & 0x33333333u) + ((v >> 2) & 0x33333333u);
return (int)((v + (v >> 4) & 0xF0F0F0Fu) * 0x1010101u) >> 24;
}
}
public static int CountBits(long v)
{
return CountBits(unchecked((ulong)v));
}
public static int CountBits(ulong v)
{
unchecked
{
const ulong MASK_01010101010101010101010101010101 = 0x5555555555555555UL;
const ulong MASK_00110011001100110011001100110011 = 0x3333333333333333UL;
const ulong MASK_00001111000011110000111100001111 = 0x0F0F0F0F0F0F0F0FUL;
const ulong MASK_00000000111111110000000011111111 = 0x00FF00FF00FF00FFUL;
const ulong MASK_00000000000000001111111111111111 = 0x0000FFFF0000FFFFUL;
const ulong MASK_11111111111111111111111111111111 = 0x00000000FFFFFFFFUL;
v = (v & MASK_01010101010101010101010101010101) + ((v >> 1) & MASK_01010101010101010101010101010101);
v = (v & MASK_00110011001100110011001100110011) + ((v >> 2) & MASK_00110011001100110011001100110011);
v = (v & MASK_00001111000011110000111100001111) + ((v >> 4) & MASK_00001111000011110000111100001111);
v = (v & MASK_00000000111111110000000011111111) + ((v >> 8) & MASK_00000000111111110000000011111111);
v = (v & MASK_00000000000000001111111111111111) + ((v >> 16) & MASK_00000000000000001111111111111111);
v = (v & MASK_11111111111111111111111111111111) + ((v >> 32) & MASK_11111111111111111111111111111111);
return (int)v;
}
}
internal static uint Align(uint position, uint alignment)
{
Debug.Assert(CountBits(alignment) == 1);
uint result = position & ~(alignment - 1);
if (result == position)
{
return result;
}
return result + alignment;
}
internal static int Align(int position, int alignment)
{
Debug.Assert(position >= 0 && alignment > 0);
Debug.Assert(CountBits(alignment) == 1);
int result = position & ~(alignment - 1);
if (result == position)
{
return result;
}
return result + alignment;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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 Roslyn.Utilities
{
internal static class BitArithmeticUtilities
{
public static int CountBits(int v)
{
return CountBits(unchecked((uint)v));
}
public static int CountBits(uint v)
{
unchecked
{
v -= ((v >> 1) & 0x55555555u);
v = (v & 0x33333333u) + ((v >> 2) & 0x33333333u);
return (int)((v + (v >> 4) & 0xF0F0F0Fu) * 0x1010101u) >> 24;
}
}
public static int CountBits(long v)
{
return CountBits(unchecked((ulong)v));
}
public static int CountBits(ulong v)
{
unchecked
{
const ulong MASK_01010101010101010101010101010101 = 0x5555555555555555UL;
const ulong MASK_00110011001100110011001100110011 = 0x3333333333333333UL;
const ulong MASK_00001111000011110000111100001111 = 0x0F0F0F0F0F0F0F0FUL;
const ulong MASK_00000000111111110000000011111111 = 0x00FF00FF00FF00FFUL;
const ulong MASK_00000000000000001111111111111111 = 0x0000FFFF0000FFFFUL;
const ulong MASK_11111111111111111111111111111111 = 0x00000000FFFFFFFFUL;
v = (v & MASK_01010101010101010101010101010101) + ((v >> 1) & MASK_01010101010101010101010101010101);
v = (v & MASK_00110011001100110011001100110011) + ((v >> 2) & MASK_00110011001100110011001100110011);
v = (v & MASK_00001111000011110000111100001111) + ((v >> 4) & MASK_00001111000011110000111100001111);
v = (v & MASK_00000000111111110000000011111111) + ((v >> 8) & MASK_00000000111111110000000011111111);
v = (v & MASK_00000000000000001111111111111111) + ((v >> 16) & MASK_00000000000000001111111111111111);
v = (v & MASK_11111111111111111111111111111111) + ((v >> 32) & MASK_11111111111111111111111111111111);
return (int)v;
}
}
internal static uint Align(uint position, uint alignment)
{
Debug.Assert(CountBits(alignment) == 1);
uint result = position & ~(alignment - 1);
if (result == position)
{
return result;
}
return result + alignment;
}
internal static int Align(int position, int alignment)
{
Debug.Assert(position >= 0 && alignment > 0);
Debug.Assert(CountBits(alignment) == 1);
int result = position & ~(alignment - 1);
if (result == position)
{
return result;
}
return result + alignment;
}
}
}
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/CachingSourceGenerator.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// We only build the Source Generator in the netstandard target
#if NETSTANDARD
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
namespace CSharpSyntaxGenerator
{
public abstract class CachingSourceGenerator : ISourceGenerator
{
/// <summary>
/// ⚠ This value may be accessed by multiple threads.
/// </summary>
private static readonly WeakReference<CachedSourceGeneratorResult> s_cachedResult = new(null);
protected abstract bool TryGetRelevantInput(in GeneratorExecutionContext context, out AdditionalText? input, out SourceText? inputText);
protected abstract bool TryGenerateSources(
AdditionalText input,
SourceText inputText,
out ImmutableArray<(string hintName, SourceText sourceText)> sources,
out ImmutableArray<Diagnostic> diagnostics,
CancellationToken cancellationToken);
public void Initialize(GeneratorInitializationContext context)
{
}
public void Execute(GeneratorExecutionContext context)
{
if (!TryGetRelevantInput(in context, out var input, out var inputText))
{
return;
}
// Get the current input checksum, which will either be used for verifying the current cache or updating it
// with the new results.
var currentChecksum = inputText.GetChecksum();
// Read the current cached result once to avoid race conditions
if (s_cachedResult.TryGetTarget(out var cachedResult)
&& cachedResult.Checksum.SequenceEqual(currentChecksum))
{
// Add the previously-cached sources, and leave the cache as it was
AddSources(in context, sources: cachedResult.Sources);
return;
}
if (TryGenerateSources(input, inputText, out var sources, out var diagnostics, context.CancellationToken))
{
AddSources(in context, sources);
if (diagnostics.IsEmpty)
{
var result = new CachedSourceGeneratorResult(currentChecksum, sources);
// Default Large Object Heap size threshold
// https://github.com/dotnet/runtime/blob/c9d69e38d0e54bea5d188593ef6c3b30139f3ab1/src/coreclr/src/gc/gc.h#L111
const int Threshold = 85000;
// Overwrite the cached result with the new result. This is an opportunistic cache, so as long as
// the write is atomic (which it is for SetTarget) synchronization is unnecessary. We allocate an
// array on the Large Object Heap (which is always part of Generation 2) and give it a reference to
// the cached object to ensure this weak reference is not reclaimed prior to a full GC pass.
var largeArray = new CachedSourceGeneratorResult[Threshold / Unsafe.SizeOf<CachedSourceGeneratorResult>()];
Debug.Assert(GC.GetGeneration(largeArray) >= 2);
largeArray[0] = result;
s_cachedResult.SetTarget(result);
GC.KeepAlive(largeArray);
}
else
{
// Invalidate the cache since we cannot currently cache diagnostics
s_cachedResult.SetTarget(null);
}
}
else
{
// Invalidate the cache since generation failed
s_cachedResult.SetTarget(null);
}
// Always report the diagnostics (if any)
foreach (var diagnostic in diagnostics)
{
context.ReportDiagnostic(diagnostic);
}
}
private static void AddSources(
in GeneratorExecutionContext context,
ImmutableArray<(string hintName, SourceText sourceText)> sources)
{
foreach (var (hintName, sourceText) in sources)
{
context.AddSource(hintName, sourceText);
}
}
private sealed record CachedSourceGeneratorResult(
ImmutableArray<byte> Checksum,
ImmutableArray<(string hintName, SourceText sourceText)> Sources);
}
}
#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.
// We only build the Source Generator in the netstandard target
#if NETSTANDARD
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
namespace CSharpSyntaxGenerator
{
public abstract class CachingSourceGenerator : ISourceGenerator
{
/// <summary>
/// ⚠ This value may be accessed by multiple threads.
/// </summary>
private static readonly WeakReference<CachedSourceGeneratorResult> s_cachedResult = new(null);
protected abstract bool TryGetRelevantInput(in GeneratorExecutionContext context, out AdditionalText? input, out SourceText? inputText);
protected abstract bool TryGenerateSources(
AdditionalText input,
SourceText inputText,
out ImmutableArray<(string hintName, SourceText sourceText)> sources,
out ImmutableArray<Diagnostic> diagnostics,
CancellationToken cancellationToken);
public void Initialize(GeneratorInitializationContext context)
{
}
public void Execute(GeneratorExecutionContext context)
{
if (!TryGetRelevantInput(in context, out var input, out var inputText))
{
return;
}
// Get the current input checksum, which will either be used for verifying the current cache or updating it
// with the new results.
var currentChecksum = inputText.GetChecksum();
// Read the current cached result once to avoid race conditions
if (s_cachedResult.TryGetTarget(out var cachedResult)
&& cachedResult.Checksum.SequenceEqual(currentChecksum))
{
// Add the previously-cached sources, and leave the cache as it was
AddSources(in context, sources: cachedResult.Sources);
return;
}
if (TryGenerateSources(input, inputText, out var sources, out var diagnostics, context.CancellationToken))
{
AddSources(in context, sources);
if (diagnostics.IsEmpty)
{
var result = new CachedSourceGeneratorResult(currentChecksum, sources);
// Default Large Object Heap size threshold
// https://github.com/dotnet/runtime/blob/c9d69e38d0e54bea5d188593ef6c3b30139f3ab1/src/coreclr/src/gc/gc.h#L111
const int Threshold = 85000;
// Overwrite the cached result with the new result. This is an opportunistic cache, so as long as
// the write is atomic (which it is for SetTarget) synchronization is unnecessary. We allocate an
// array on the Large Object Heap (which is always part of Generation 2) and give it a reference to
// the cached object to ensure this weak reference is not reclaimed prior to a full GC pass.
var largeArray = new CachedSourceGeneratorResult[Threshold / Unsafe.SizeOf<CachedSourceGeneratorResult>()];
Debug.Assert(GC.GetGeneration(largeArray) >= 2);
largeArray[0] = result;
s_cachedResult.SetTarget(result);
GC.KeepAlive(largeArray);
}
else
{
// Invalidate the cache since we cannot currently cache diagnostics
s_cachedResult.SetTarget(null);
}
}
else
{
// Invalidate the cache since generation failed
s_cachedResult.SetTarget(null);
}
// Always report the diagnostics (if any)
foreach (var diagnostic in diagnostics)
{
context.ReportDiagnostic(diagnostic);
}
}
private static void AddSources(
in GeneratorExecutionContext context,
ImmutableArray<(string hintName, SourceText sourceText)> sources)
{
foreach (var (hintName, sourceText) in sources)
{
context.AddSource(hintName, sourceText);
}
}
private sealed record CachedSourceGeneratorResult(
ImmutableArray<byte> Checksum,
ImmutableArray<(string hintName, SourceText sourceText)> Sources);
}
}
#endif
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Portable/Emitter/Model/ModuleReference.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.Emit;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Emit
{
internal sealed class ModuleReference : Cci.IModuleReference, Cci.IFileReference
{
private readonly PEModuleBuilder _moduleBeingBuilt;
private readonly ModuleSymbol _underlyingModule;
internal ModuleReference(PEModuleBuilder moduleBeingBuilt, ModuleSymbol underlyingModule)
{
Debug.Assert(moduleBeingBuilt != null);
Debug.Assert((object)underlyingModule != null);
_moduleBeingBuilt = moduleBeingBuilt;
_underlyingModule = underlyingModule;
}
void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor)
{
visitor.Visit((Cci.IModuleReference)this);
}
string Cci.INamedEntity.Name
{
get
{
return _underlyingModule.MetadataName;
}
}
bool Cci.IFileReference.HasMetadata
{
get
{
return true;
}
}
string Cci.IFileReference.FileName
{
get
{
return _underlyingModule.Name;
}
}
ImmutableArray<byte> Cci.IFileReference.GetHashValue(AssemblyHashAlgorithm algorithmId)
{
return _underlyingModule.GetHash(algorithmId);
}
Cci.IAssemblyReference Cci.IModuleReference.GetContainingAssembly(EmitContext context)
{
if (_moduleBeingBuilt.OutputKind.IsNetModule() &&
ReferenceEquals(_moduleBeingBuilt.SourceModule.ContainingAssembly, _underlyingModule.ContainingAssembly))
{
return null;
}
return _moduleBeingBuilt.Translate(_underlyingModule.ContainingAssembly, context.Diagnostics);
}
public override string ToString()
{
return _underlyingModule.ToString();
}
IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context)
{
return SpecializedCollections.EmptyEnumerable<Cci.ICustomAttribute>();
}
Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context)
{
return null;
}
CodeAnalysis.Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.Emit;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Emit
{
internal sealed class ModuleReference : Cci.IModuleReference, Cci.IFileReference
{
private readonly PEModuleBuilder _moduleBeingBuilt;
private readonly ModuleSymbol _underlyingModule;
internal ModuleReference(PEModuleBuilder moduleBeingBuilt, ModuleSymbol underlyingModule)
{
Debug.Assert(moduleBeingBuilt != null);
Debug.Assert((object)underlyingModule != null);
_moduleBeingBuilt = moduleBeingBuilt;
_underlyingModule = underlyingModule;
}
void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor)
{
visitor.Visit((Cci.IModuleReference)this);
}
string Cci.INamedEntity.Name
{
get
{
return _underlyingModule.MetadataName;
}
}
bool Cci.IFileReference.HasMetadata
{
get
{
return true;
}
}
string Cci.IFileReference.FileName
{
get
{
return _underlyingModule.Name;
}
}
ImmutableArray<byte> Cci.IFileReference.GetHashValue(AssemblyHashAlgorithm algorithmId)
{
return _underlyingModule.GetHash(algorithmId);
}
Cci.IAssemblyReference Cci.IModuleReference.GetContainingAssembly(EmitContext context)
{
if (_moduleBeingBuilt.OutputKind.IsNetModule() &&
ReferenceEquals(_moduleBeingBuilt.SourceModule.ContainingAssembly, _underlyingModule.ContainingAssembly))
{
return null;
}
return _moduleBeingBuilt.Translate(_underlyingModule.ContainingAssembly, context.Diagnostics);
}
public override string ToString()
{
return _underlyingModule.ToString();
}
IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context)
{
return SpecializedCollections.EmptyEnumerable<Cci.ICustomAttribute>();
}
Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context)
{
return null;
}
CodeAnalysis.Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null;
}
}
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/Portable/InternalUtilities/RoslynString.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.CodeAnalysis;
namespace Roslyn.Utilities
{
internal static class RoslynString
{
/// <inheritdoc cref="string.IsNullOrEmpty(string)"/>
public static bool IsNullOrEmpty([NotNullWhen(returnValue: false)] string? value)
=> string.IsNullOrEmpty(value);
#if !NET20
/// <inheritdoc cref="string.IsNullOrWhiteSpace(string)"/>
public static bool IsNullOrWhiteSpace([NotNullWhen(returnValue: false)] string? value)
=> string.IsNullOrWhiteSpace(value);
#endif
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.CodeAnalysis;
namespace Roslyn.Utilities
{
internal static class RoslynString
{
/// <inheritdoc cref="string.IsNullOrEmpty(string)"/>
public static bool IsNullOrEmpty([NotNullWhen(returnValue: false)] string? value)
=> string.IsNullOrEmpty(value);
#if !NET20
/// <inheritdoc cref="string.IsNullOrWhiteSpace(string)"/>
public static bool IsNullOrWhiteSpace([NotNullWhen(returnValue: false)] string? value)
=> string.IsNullOrWhiteSpace(value);
#endif
}
}
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/VisualBasic/Test/Syntax/Scanner/ScanErrorTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
' this place is dedicated to scan related error tests
Public Class ScanErrorTests
#Region "Targeted Error Tests - please arrange tests in the order of error code"
<WorkItem(897923, "DevDiv/Personal")>
<Fact>
Public Sub BC31170ERR_IllegalXmlNameChar()
Dim nameText = "Nc#" & ChrW(7) & "Name"
Dim fullText = "<" & nameText & "/>"
Dim t = DirectCast(SyntaxFactory.ParseExpression(fullText), XmlEmptyElementSyntax)
Assert.Equal(fullText, t.ToFullString())
Assert.Equal(True, t.ContainsDiagnostics)
Assert.Equal(3, t.GetSyntaxErrorsNoTree.Count)
Assert.Equal(31170, t.GetSyntaxErrorsNoTree(2).Code)
End Sub
#End Region
#Region "Mixed Error Tests"
<WorkItem(881821, "DevDiv/Personal")>
<Fact>
Public Sub BC30004ERR_IllegalCharConstant_ScanTwoCharLiteralFollowedByQuote1()
ParseAndVerify(<![CDATA[
" "C
"
]]>,
<errors>
<error id="30648"/>
<error id="30004"/>
</errors>)
End Sub
#End Region
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
' this place is dedicated to scan related error tests
Public Class ScanErrorTests
#Region "Targeted Error Tests - please arrange tests in the order of error code"
<WorkItem(897923, "DevDiv/Personal")>
<Fact>
Public Sub BC31170ERR_IllegalXmlNameChar()
Dim nameText = "Nc#" & ChrW(7) & "Name"
Dim fullText = "<" & nameText & "/>"
Dim t = DirectCast(SyntaxFactory.ParseExpression(fullText), XmlEmptyElementSyntax)
Assert.Equal(fullText, t.ToFullString())
Assert.Equal(True, t.ContainsDiagnostics)
Assert.Equal(3, t.GetSyntaxErrorsNoTree.Count)
Assert.Equal(31170, t.GetSyntaxErrorsNoTree(2).Code)
End Sub
#End Region
#Region "Mixed Error Tests"
<WorkItem(881821, "DevDiv/Personal")>
<Fact>
Public Sub BC30004ERR_IllegalCharConstant_ScanTwoCharLiteralFollowedByQuote1()
ParseAndVerify(<![CDATA[
" "C
"
]]>,
<errors>
<error id="30648"/>
<error id="30004"/>
</errors>)
End Sub
#End Region
End Class
End Namespace
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/StructuredTriviaFormattingRule.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Formatting.Rules;
namespace Microsoft.CodeAnalysis.CSharp.Formatting
{
internal class StructuredTriviaFormattingRule : BaseFormattingRule
{
internal const string Name = "CSharp Structured Trivia Formatting Rule";
public override AdjustNewLinesOperation? GetAdjustNewLinesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation)
{
if (previousToken.Parent is StructuredTriviaSyntax || currentToken.Parent is StructuredTriviaSyntax)
{
return null;
}
return nextOperation.Invoke(in previousToken, in currentToken);
}
public override AdjustSpacesOperation? GetAdjustSpacesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustSpacesOperation nextOperation)
{
if (previousToken.Parent is StructuredTriviaSyntax || currentToken.Parent is StructuredTriviaSyntax)
{
// this doesn't take care of all cases where tokens belong to structured trivia. this is only for cases we care
if (previousToken.Kind() == SyntaxKind.HashToken && SyntaxFacts.IsPreprocessorKeyword(currentToken.Kind()))
{
return CreateAdjustSpacesOperation(space: 0, option: AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
if (previousToken.Kind() == SyntaxKind.RegionKeyword && currentToken.Kind() == SyntaxKind.EndOfDirectiveToken)
{
return CreateAdjustSpacesOperation(space: 0, option: AdjustSpacesOption.PreserveSpaces);
}
if (currentToken.Kind() == SyntaxKind.EndOfDirectiveToken)
{
return CreateAdjustSpacesOperation(space: 0, option: AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
}
return nextOperation.Invoke(in previousToken, in currentToken);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Formatting.Rules;
namespace Microsoft.CodeAnalysis.CSharp.Formatting
{
internal class StructuredTriviaFormattingRule : BaseFormattingRule
{
internal const string Name = "CSharp Structured Trivia Formatting Rule";
public override AdjustNewLinesOperation? GetAdjustNewLinesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation)
{
if (previousToken.Parent is StructuredTriviaSyntax || currentToken.Parent is StructuredTriviaSyntax)
{
return null;
}
return nextOperation.Invoke(in previousToken, in currentToken);
}
public override AdjustSpacesOperation? GetAdjustSpacesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustSpacesOperation nextOperation)
{
if (previousToken.Parent is StructuredTriviaSyntax || currentToken.Parent is StructuredTriviaSyntax)
{
// this doesn't take care of all cases where tokens belong to structured trivia. this is only for cases we care
if (previousToken.Kind() == SyntaxKind.HashToken && SyntaxFacts.IsPreprocessorKeyword(currentToken.Kind()))
{
return CreateAdjustSpacesOperation(space: 0, option: AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
if (previousToken.Kind() == SyntaxKind.RegionKeyword && currentToken.Kind() == SyntaxKind.EndOfDirectiveToken)
{
return CreateAdjustSpacesOperation(space: 0, option: AdjustSpacesOption.PreserveSpaces);
}
if (currentToken.Kind() == SyntaxKind.EndOfDirectiveToken)
{
return CreateAdjustSpacesOperation(space: 0, option: AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
}
return nextOperation.Invoke(in previousToken, in currentToken);
}
}
}
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Impl/CodeModel/MethodXml/SpecialCastKind.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.MethodXml
{
internal enum SpecialCastKind
{
DirectCast,
TryCast
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.MethodXml
{
internal enum SpecialCastKind
{
DirectCast,
TryCast
}
}
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/CSharpTest/SymbolKey/SymbolKeyMetadataVsSourceTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using static Roslyn.Test.Utilities.TestMetadata;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SymbolId
{
public partial class SymbolKeyTest : SymbolKeyTestBase
{
#region "Metadata vs. Source"
[Fact]
public void M2SNamedTypeSymbols01()
{
var src1 = @"using System;
public delegate void D(int p1, string p2);
namespace N1.N2
{
public interface I { }
namespace N3
{
public class C
{
public struct S
{
public enum E { Zero, One, Two }
public void M(int n) { Console.WriteLine(n); }
}
}
}
}
";
var src2 = @"using System;
using N1.N2.N3;
public class App : C
{
private event D myEvent;
internal N1.N2.I Prop { get; set; }
protected C.S.E this[int x] { set { } }
public void M(C.S s) { s.M(123); }
}
";
var comp1 = CreateCompilation(src1);
// Compilation to Compilation
var comp2 = (Compilation)CreateCompilation(src2, new MetadataReference[] { new CSharpCompilationReference(comp1) });
var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType).OrderBy(s => s.Name).ToList();
Assert.Equal(5, originalSymbols.Count);
// ---------------------------
// Metadata symbols
var typesym = comp2.SourceModule.GlobalNamespace.GetTypeMembers("App").FirstOrDefault() as INamedTypeSymbol;
// 'D'
var member01 = (typesym.GetMembers("myEvent").Single() as IEventSymbol).Type;
// 'I'
var member02 = (typesym.GetMembers("Prop").Single() as IPropertySymbol).Type;
// 'C'
var member03 = typesym.BaseType;
// 'S'
var member04 = (typesym.GetMembers("M").Single() as IMethodSymbol).Parameters[0].Type;
// 'E'
var member05 = (typesym.GetMembers(WellKnownMemberNames.Indexer).Single() as IPropertySymbol).Type;
ResolveAndVerifySymbol(member03, originalSymbols[0], comp1, SymbolKeyComparison.None);
ResolveAndVerifySymbol(member01, originalSymbols[1], comp1, SymbolKeyComparison.None);
ResolveAndVerifySymbol(member05, originalSymbols[2], comp1, SymbolKeyComparison.None);
ResolveAndVerifySymbol(member02, originalSymbols[3], comp1, SymbolKeyComparison.None);
ResolveAndVerifySymbol(member04, originalSymbols[4], comp1, SymbolKeyComparison.None);
}
[WorkItem(542700, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542700")]
[Fact]
public void M2SNonTypeMemberSymbols01()
{
var src1 = @"using System;
namespace N1
{
public interface IGoo
{
void M(int p1, int p2);
void M(params short[] ary);
void M(string p1);
void M(ref string p1);
}
public struct S
{
public event Action<S> PublicEvent { add { } remove { } }
public IGoo PublicField;
public string PublicProp { get; set; }
public short this[sbyte p] { get { return p; } }
}
}
";
var src2 = @"using System;
using AN = N1;
public class App
{
static void Main()
{
var obj = new AN.S();
/*<bind0>*/obj.PublicEvent/*</bind0>*/ += EH;
var igoo = /*<bind1>*/obj.PublicField/*</bind1>*/;
/*<bind3>*/igoo.M(/*<bind2>*/obj.PublicProp/*</bind2>*/)/*</bind3>*/;
/*<bind5>*/igoo.M(obj[12], /*<bind4>*/obj[123]/*</bind4>*/)/*</bind5>*/;
}
static void EH(AN.S s) { }
}
";
var comp1 = CreateCompilation(src1);
// Compilation to Assembly
var comp2 = CreateCompilation(src2, new MetadataReference[] { comp1.EmitToImageReference() });
// ---------------------------
// Source symbols
var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.NonTypeMember | SymbolCategory.Parameter).ToList();
originalSymbols = originalSymbols.Where(s => !s.IsAccessor() && s.Kind != SymbolKind.Parameter).OrderBy(s => s.Name).Select(s => s).ToList();
Assert.Equal(8, originalSymbols.Count);
// ---------------------------
// Metadata symbols
var bindingtuples = GetBindingNodesAndModel<ExpressionSyntax>(comp2);
var model = bindingtuples.Item2;
var list = bindingtuples.Item1;
Assert.Equal(6, list.Count);
// event
ResolveAndVerifySymbol(list[0], originalSymbols[4], model, comp1, SymbolKeyComparison.None);
// field
ResolveAndVerifySymbol(list[1], originalSymbols[5], model, comp1, SymbolKeyComparison.None);
// prop
ResolveAndVerifySymbol(list[2], originalSymbols[6], model, comp1, SymbolKeyComparison.None);
// index:
ResolveAndVerifySymbol(list[4], originalSymbols[7], model, comp1, SymbolKeyComparison.None);
// M(string p1)
ResolveAndVerifySymbol(list[3], originalSymbols[2], model, comp1, SymbolKeyComparison.None);
// M(params short[] ary)
ResolveAndVerifySymbol(list[5], originalSymbols[1], model, comp1, SymbolKeyComparison.None);
}
#endregion
#region "Metadata vs. Metadata"
[Fact]
public void M2MMultiTargetingMsCorLib01()
{
var src1 = @"using System;
using System.IO;
public class A
{
public FileInfo GetFileInfo(string path)
{
if (File.Exists(path))
{
return new FileInfo(path);
}
return null;
}
public void PrintInfo(Array ary, ref DateTime time)
{
if (ary != null)
Console.WriteLine(ary);
else
Console.WriteLine(""null"");
time = DateTime.Now;
}
}
";
var src2 = @"using System;
class Test
{
static void Main()
{
var a = new A();
var fi = a.GetFileInfo(null);
Console.WriteLine(fi);
var dt = DateTime.Now;
var ary = Array.CreateInstance(typeof(string), 2);
a.PrintInfo(ary, ref dt);
}
}
";
var comp20 = (Compilation)CreateEmptyCompilation(src1, new[] { Net40.mscorlib });
// "Compilation 2 Assembly"
var comp40 = (Compilation)CreateCompilation(src2, new MetadataReference[] { comp20.EmitToImageReference() });
var typeA = comp20.SourceModule.GlobalNamespace.GetTypeMembers("A").Single();
var mem20_1 = typeA.GetMembers("GetFileInfo").Single() as IMethodSymbol;
var mem20_2 = typeA.GetMembers("PrintInfo").Single() as IMethodSymbol;
// FileInfo
var mtsym20_1 = mem20_1.ReturnType;
Assert.Equal(2, mem20_2.Parameters.Length);
// Array
var mtsym20_2 = mem20_2.Parameters[0].Type;
// ref DateTime
var mtsym20_3 = mem20_2.Parameters[1].Type;
// ====================
var typeTest = comp40.SourceModule.GlobalNamespace.GetTypeMembers("Test").FirstOrDefault();
var mem40 = typeTest.GetMembers("Main").Single() as IMethodSymbol;
var list = GetBlockSyntaxList(mem40);
var model = comp40.GetSemanticModel(comp40.SyntaxTrees.First());
foreach (var body in list)
{
var df = model.AnalyzeDataFlow(body.Statements.First(), body.Statements.Last());
foreach (var local in df.VariablesDeclared)
{
var localType = ((ILocalSymbol)local).Type;
if (local.Name == "fi")
{
ResolveAndVerifySymbol(localType, mtsym20_1, comp20, SymbolKeyComparison.None);
}
else if (local.Name == "ary")
{
ResolveAndVerifySymbol(localType, mtsym20_2, comp20, SymbolKeyComparison.None);
}
else if (local.Name == "dt")
{
ResolveAndVerifySymbol(localType, mtsym20_3, comp20, SymbolKeyComparison.None);
}
}
}
}
[Fact, WorkItem(546255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546255")]
public void M2MMultiTargetingMsCorLib02()
{
var src1 = @"using System;
namespace Mscorlib20
{
public interface IGoo
{
// interface
IDisposable Prop { get; set; }
// class
Exception this[ArgumentException t] { get; }
}
public class CGoo : IGoo
{
// enum
public DayOfWeek PublicField;
// delegate
public event System.Threading.ParameterizedThreadStart PublicEventField;
public IDisposable Prop { get; set; }
public Exception this[ArgumentException t] { get { return t; } }
}
}
";
var src2 = @"using System;
using N20 = Mscorlib20;
class Test
{
public IDisposable M()
{
var obj = new N20::CGoo();
N20.IGoo igoo = obj;
/*<bind0>*/obj.PublicEventField/*</bind0>*/ += /*<bind1>*/MyEveHandler/*</bind1>*/;
var local = /*<bind2>*/igoo[null]/*</bind2>*/;
if (/*<bind3>*/obj.PublicField /*</bind3>*/== DayOfWeek.Friday)
{
return /*<bind4>*/(obj as N20.IGoo).Prop/*</bind4>*/;
}
return null;
}
public void MyEveHandler(object o) { }
}
";
var comp20 = CreateEmptyCompilation(src1, new[] { Net40.mscorlib });
// "Compilation ref Compilation"
var comp40 = CreateCompilation(src2, new[] { new CSharpCompilationReference(comp20) });
var originals = GetSourceSymbols(comp20, SymbolCategory.NonTypeMember | SymbolCategory.Parameter);
var originalSymbols = originals.Where(s => !s.IsAccessor() && s.Kind != SymbolKind.Parameter).OrderBy(s => s.Name).ToList();
// IGoo.Prop, CGoo.Prop, Event, Field, IGoo.This, CGoo.This
Assert.Equal(6, originalSymbols.Count);
// ====================
var bindingtuples = GetBindingNodesAndModel<ExpressionSyntax>(comp40);
var model = bindingtuples.Item2;
var list = bindingtuples.Item1;
Assert.Equal(5, list.Count);
// PublicEventField
ResolveAndVerifySymbol(list[0], originalSymbols[2], model, comp20);
// delegate ParameterizedThreadStart
ResolveAndVerifyTypeSymbol(list[0], (originalSymbols[2] as IEventSymbol).Type, model, comp20);
// MethodGroup
ResolveAndVerifyTypeSymbol(list[1], (originalSymbols[2] as IEventSymbol).Type, model, comp20);
// Indexer
ResolveAndVerifySymbol(list[2], originalSymbols[4], model, comp20);
// class Exception
ResolveAndVerifyTypeSymbol(list[2], (originalSymbols[4] as IPropertySymbol).Type, model, comp20);
// PublicField
ResolveAndVerifySymbol(list[3], originalSymbols[3], model, comp20);
// enum DayOfWeek
ResolveAndVerifyTypeSymbol(list[3], (originalSymbols[3] as IFieldSymbol).Type, model, comp20);
// Prop
ResolveAndVerifySymbol(list[4], originalSymbols[0], model, comp20);
// interface IDisposable
ResolveAndVerifyTypeSymbol(list[4], (originalSymbols[0] as IPropertySymbol).Type, model, comp20);
}
[Fact, WorkItem(546255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546255")]
public void M2MMultiTargetingMsCorLib03()
{
var src1 = @"using System;
namespace Mscorlib20
{
public interface IGoo
{
// interface
IDisposable Prop { get; set; }
// class
Exception this[ArgumentException t] { get; }
}
public class CGoo : IGoo
{
// explicit
IDisposable IGoo.Prop { get; set; }
Exception IGoo.this[ArgumentException t] { get { return t; } }
}
}
";
var src2 = @"using System;
using N20 = Mscorlib20;
class Test
{
public IDisposable M()
{
N20.IGoo igoo = new N20::CGoo();
var local = /*<bind0>*/igoo[new ArgumentException()]/*</bind0>*/;
return /*<bind1>*/igoo.Prop/*</bind1>*/;
}
}
";
var comp20 = CreateEmptyCompilation(src1, new[] { Net40.mscorlib });
// "Compilation ref Compilation"
var comp40 = CreateCompilation(src2, new[] { new CSharpCompilationReference(comp20) });
var originals = GetSourceSymbols(comp20, SymbolCategory.NonTypeMember | SymbolCategory.Parameter);
var originalSymbols = originals.Where(s => !s.IsAccessor() && s.Kind != SymbolKind.Parameter).OrderBy(s => s.Name).ToList();
// CGoo.Prop, CGoo.This, IGoo.Prop, IGoo.This
Assert.Equal(4, originalSymbols.Count);
// ====================
var bindingtuples = GetBindingNodesAndModel<ExpressionSyntax>(comp40);
var model = bindingtuples.Item2;
var list = bindingtuples.Item1;
Assert.Equal(2, list.Count);
// Indexer
ResolveAndVerifySymbol(list[0], originalSymbols[3], model, comp20);
// class Exception
ResolveAndVerifyTypeSymbol(list[0], (originalSymbols[3] as IPropertySymbol).Type, model, comp20);
// Prop
ResolveAndVerifySymbol(list[1], originalSymbols[2], model, comp20);
// interface IDisposable
ResolveAndVerifyTypeSymbol(list[1], (originalSymbols[2] as IPropertySymbol).Type, model, comp20);
}
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using static Roslyn.Test.Utilities.TestMetadata;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SymbolId
{
public partial class SymbolKeyTest : SymbolKeyTestBase
{
#region "Metadata vs. Source"
[Fact]
public void M2SNamedTypeSymbols01()
{
var src1 = @"using System;
public delegate void D(int p1, string p2);
namespace N1.N2
{
public interface I { }
namespace N3
{
public class C
{
public struct S
{
public enum E { Zero, One, Two }
public void M(int n) { Console.WriteLine(n); }
}
}
}
}
";
var src2 = @"using System;
using N1.N2.N3;
public class App : C
{
private event D myEvent;
internal N1.N2.I Prop { get; set; }
protected C.S.E this[int x] { set { } }
public void M(C.S s) { s.M(123); }
}
";
var comp1 = CreateCompilation(src1);
// Compilation to Compilation
var comp2 = (Compilation)CreateCompilation(src2, new MetadataReference[] { new CSharpCompilationReference(comp1) });
var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType).OrderBy(s => s.Name).ToList();
Assert.Equal(5, originalSymbols.Count);
// ---------------------------
// Metadata symbols
var typesym = comp2.SourceModule.GlobalNamespace.GetTypeMembers("App").FirstOrDefault() as INamedTypeSymbol;
// 'D'
var member01 = (typesym.GetMembers("myEvent").Single() as IEventSymbol).Type;
// 'I'
var member02 = (typesym.GetMembers("Prop").Single() as IPropertySymbol).Type;
// 'C'
var member03 = typesym.BaseType;
// 'S'
var member04 = (typesym.GetMembers("M").Single() as IMethodSymbol).Parameters[0].Type;
// 'E'
var member05 = (typesym.GetMembers(WellKnownMemberNames.Indexer).Single() as IPropertySymbol).Type;
ResolveAndVerifySymbol(member03, originalSymbols[0], comp1, SymbolKeyComparison.None);
ResolveAndVerifySymbol(member01, originalSymbols[1], comp1, SymbolKeyComparison.None);
ResolveAndVerifySymbol(member05, originalSymbols[2], comp1, SymbolKeyComparison.None);
ResolveAndVerifySymbol(member02, originalSymbols[3], comp1, SymbolKeyComparison.None);
ResolveAndVerifySymbol(member04, originalSymbols[4], comp1, SymbolKeyComparison.None);
}
[WorkItem(542700, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542700")]
[Fact]
public void M2SNonTypeMemberSymbols01()
{
var src1 = @"using System;
namespace N1
{
public interface IGoo
{
void M(int p1, int p2);
void M(params short[] ary);
void M(string p1);
void M(ref string p1);
}
public struct S
{
public event Action<S> PublicEvent { add { } remove { } }
public IGoo PublicField;
public string PublicProp { get; set; }
public short this[sbyte p] { get { return p; } }
}
}
";
var src2 = @"using System;
using AN = N1;
public class App
{
static void Main()
{
var obj = new AN.S();
/*<bind0>*/obj.PublicEvent/*</bind0>*/ += EH;
var igoo = /*<bind1>*/obj.PublicField/*</bind1>*/;
/*<bind3>*/igoo.M(/*<bind2>*/obj.PublicProp/*</bind2>*/)/*</bind3>*/;
/*<bind5>*/igoo.M(obj[12], /*<bind4>*/obj[123]/*</bind4>*/)/*</bind5>*/;
}
static void EH(AN.S s) { }
}
";
var comp1 = CreateCompilation(src1);
// Compilation to Assembly
var comp2 = CreateCompilation(src2, new MetadataReference[] { comp1.EmitToImageReference() });
// ---------------------------
// Source symbols
var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.NonTypeMember | SymbolCategory.Parameter).ToList();
originalSymbols = originalSymbols.Where(s => !s.IsAccessor() && s.Kind != SymbolKind.Parameter).OrderBy(s => s.Name).Select(s => s).ToList();
Assert.Equal(8, originalSymbols.Count);
// ---------------------------
// Metadata symbols
var bindingtuples = GetBindingNodesAndModel<ExpressionSyntax>(comp2);
var model = bindingtuples.Item2;
var list = bindingtuples.Item1;
Assert.Equal(6, list.Count);
// event
ResolveAndVerifySymbol(list[0], originalSymbols[4], model, comp1, SymbolKeyComparison.None);
// field
ResolveAndVerifySymbol(list[1], originalSymbols[5], model, comp1, SymbolKeyComparison.None);
// prop
ResolveAndVerifySymbol(list[2], originalSymbols[6], model, comp1, SymbolKeyComparison.None);
// index:
ResolveAndVerifySymbol(list[4], originalSymbols[7], model, comp1, SymbolKeyComparison.None);
// M(string p1)
ResolveAndVerifySymbol(list[3], originalSymbols[2], model, comp1, SymbolKeyComparison.None);
// M(params short[] ary)
ResolveAndVerifySymbol(list[5], originalSymbols[1], model, comp1, SymbolKeyComparison.None);
}
#endregion
#region "Metadata vs. Metadata"
[Fact]
public void M2MMultiTargetingMsCorLib01()
{
var src1 = @"using System;
using System.IO;
public class A
{
public FileInfo GetFileInfo(string path)
{
if (File.Exists(path))
{
return new FileInfo(path);
}
return null;
}
public void PrintInfo(Array ary, ref DateTime time)
{
if (ary != null)
Console.WriteLine(ary);
else
Console.WriteLine(""null"");
time = DateTime.Now;
}
}
";
var src2 = @"using System;
class Test
{
static void Main()
{
var a = new A();
var fi = a.GetFileInfo(null);
Console.WriteLine(fi);
var dt = DateTime.Now;
var ary = Array.CreateInstance(typeof(string), 2);
a.PrintInfo(ary, ref dt);
}
}
";
var comp20 = (Compilation)CreateEmptyCompilation(src1, new[] { Net40.mscorlib });
// "Compilation 2 Assembly"
var comp40 = (Compilation)CreateCompilation(src2, new MetadataReference[] { comp20.EmitToImageReference() });
var typeA = comp20.SourceModule.GlobalNamespace.GetTypeMembers("A").Single();
var mem20_1 = typeA.GetMembers("GetFileInfo").Single() as IMethodSymbol;
var mem20_2 = typeA.GetMembers("PrintInfo").Single() as IMethodSymbol;
// FileInfo
var mtsym20_1 = mem20_1.ReturnType;
Assert.Equal(2, mem20_2.Parameters.Length);
// Array
var mtsym20_2 = mem20_2.Parameters[0].Type;
// ref DateTime
var mtsym20_3 = mem20_2.Parameters[1].Type;
// ====================
var typeTest = comp40.SourceModule.GlobalNamespace.GetTypeMembers("Test").FirstOrDefault();
var mem40 = typeTest.GetMembers("Main").Single() as IMethodSymbol;
var list = GetBlockSyntaxList(mem40);
var model = comp40.GetSemanticModel(comp40.SyntaxTrees.First());
foreach (var body in list)
{
var df = model.AnalyzeDataFlow(body.Statements.First(), body.Statements.Last());
foreach (var local in df.VariablesDeclared)
{
var localType = ((ILocalSymbol)local).Type;
if (local.Name == "fi")
{
ResolveAndVerifySymbol(localType, mtsym20_1, comp20, SymbolKeyComparison.None);
}
else if (local.Name == "ary")
{
ResolveAndVerifySymbol(localType, mtsym20_2, comp20, SymbolKeyComparison.None);
}
else if (local.Name == "dt")
{
ResolveAndVerifySymbol(localType, mtsym20_3, comp20, SymbolKeyComparison.None);
}
}
}
}
[Fact, WorkItem(546255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546255")]
public void M2MMultiTargetingMsCorLib02()
{
var src1 = @"using System;
namespace Mscorlib20
{
public interface IGoo
{
// interface
IDisposable Prop { get; set; }
// class
Exception this[ArgumentException t] { get; }
}
public class CGoo : IGoo
{
// enum
public DayOfWeek PublicField;
// delegate
public event System.Threading.ParameterizedThreadStart PublicEventField;
public IDisposable Prop { get; set; }
public Exception this[ArgumentException t] { get { return t; } }
}
}
";
var src2 = @"using System;
using N20 = Mscorlib20;
class Test
{
public IDisposable M()
{
var obj = new N20::CGoo();
N20.IGoo igoo = obj;
/*<bind0>*/obj.PublicEventField/*</bind0>*/ += /*<bind1>*/MyEveHandler/*</bind1>*/;
var local = /*<bind2>*/igoo[null]/*</bind2>*/;
if (/*<bind3>*/obj.PublicField /*</bind3>*/== DayOfWeek.Friday)
{
return /*<bind4>*/(obj as N20.IGoo).Prop/*</bind4>*/;
}
return null;
}
public void MyEveHandler(object o) { }
}
";
var comp20 = CreateEmptyCompilation(src1, new[] { Net40.mscorlib });
// "Compilation ref Compilation"
var comp40 = CreateCompilation(src2, new[] { new CSharpCompilationReference(comp20) });
var originals = GetSourceSymbols(comp20, SymbolCategory.NonTypeMember | SymbolCategory.Parameter);
var originalSymbols = originals.Where(s => !s.IsAccessor() && s.Kind != SymbolKind.Parameter).OrderBy(s => s.Name).ToList();
// IGoo.Prop, CGoo.Prop, Event, Field, IGoo.This, CGoo.This
Assert.Equal(6, originalSymbols.Count);
// ====================
var bindingtuples = GetBindingNodesAndModel<ExpressionSyntax>(comp40);
var model = bindingtuples.Item2;
var list = bindingtuples.Item1;
Assert.Equal(5, list.Count);
// PublicEventField
ResolveAndVerifySymbol(list[0], originalSymbols[2], model, comp20);
// delegate ParameterizedThreadStart
ResolveAndVerifyTypeSymbol(list[0], (originalSymbols[2] as IEventSymbol).Type, model, comp20);
// MethodGroup
ResolveAndVerifyTypeSymbol(list[1], (originalSymbols[2] as IEventSymbol).Type, model, comp20);
// Indexer
ResolveAndVerifySymbol(list[2], originalSymbols[4], model, comp20);
// class Exception
ResolveAndVerifyTypeSymbol(list[2], (originalSymbols[4] as IPropertySymbol).Type, model, comp20);
// PublicField
ResolveAndVerifySymbol(list[3], originalSymbols[3], model, comp20);
// enum DayOfWeek
ResolveAndVerifyTypeSymbol(list[3], (originalSymbols[3] as IFieldSymbol).Type, model, comp20);
// Prop
ResolveAndVerifySymbol(list[4], originalSymbols[0], model, comp20);
// interface IDisposable
ResolveAndVerifyTypeSymbol(list[4], (originalSymbols[0] as IPropertySymbol).Type, model, comp20);
}
[Fact, WorkItem(546255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546255")]
public void M2MMultiTargetingMsCorLib03()
{
var src1 = @"using System;
namespace Mscorlib20
{
public interface IGoo
{
// interface
IDisposable Prop { get; set; }
// class
Exception this[ArgumentException t] { get; }
}
public class CGoo : IGoo
{
// explicit
IDisposable IGoo.Prop { get; set; }
Exception IGoo.this[ArgumentException t] { get { return t; } }
}
}
";
var src2 = @"using System;
using N20 = Mscorlib20;
class Test
{
public IDisposable M()
{
N20.IGoo igoo = new N20::CGoo();
var local = /*<bind0>*/igoo[new ArgumentException()]/*</bind0>*/;
return /*<bind1>*/igoo.Prop/*</bind1>*/;
}
}
";
var comp20 = CreateEmptyCompilation(src1, new[] { Net40.mscorlib });
// "Compilation ref Compilation"
var comp40 = CreateCompilation(src2, new[] { new CSharpCompilationReference(comp20) });
var originals = GetSourceSymbols(comp20, SymbolCategory.NonTypeMember | SymbolCategory.Parameter);
var originalSymbols = originals.Where(s => !s.IsAccessor() && s.Kind != SymbolKind.Parameter).OrderBy(s => s.Name).ToList();
// CGoo.Prop, CGoo.This, IGoo.Prop, IGoo.This
Assert.Equal(4, originalSymbols.Count);
// ====================
var bindingtuples = GetBindingNodesAndModel<ExpressionSyntax>(comp40);
var model = bindingtuples.Item2;
var list = bindingtuples.Item1;
Assert.Equal(2, list.Count);
// Indexer
ResolveAndVerifySymbol(list[0], originalSymbols[3], model, comp20);
// class Exception
ResolveAndVerifyTypeSymbol(list[0], (originalSymbols[3] as IPropertySymbol).Type, model, comp20);
// Prop
ResolveAndVerifySymbol(list[1], originalSymbols[2], model, comp20);
// interface IDisposable
ResolveAndVerifyTypeSymbol(list[1], (originalSymbols[2] as IPropertySymbol).Type, model, comp20);
}
#endregion
}
}
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Tools/ExternalAccess/FSharp/Editor/Implementation/Debugging/IFSharpLanguageDebugInfoService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor.Implementation.Debugging
{
internal interface IFSharpLanguageDebugInfoService
{
Task<FSharpDebugLocationInfo> GetLocationInfoAsync(Document document, int position, CancellationToken cancellationToken);
/// <summary>
/// Find an appropriate span to pass the debugger given a point in a snapshot. Optionally
/// pass back a string to pass to the debugger instead if no good span can be found. For
/// example, if the user hovers on "var" then we actually want to pass the fully qualified
/// name of the type that 'var' binds to, to the debugger.
/// </summary>
Task<FSharpDebugDataTipInfo> GetDataTipInfoAsync(Document document, int position, CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor.Implementation.Debugging
{
internal interface IFSharpLanguageDebugInfoService
{
Task<FSharpDebugLocationInfo> GetLocationInfoAsync(Document document, int position, CancellationToken cancellationToken);
/// <summary>
/// Find an appropriate span to pass the debugger given a point in a snapshot. Optionally
/// pass back a string to pass to the debugger instead if no good span can be found. For
/// example, if the user hovers on "var" then we actually want to pass the fully qualified
/// name of the type that 'var' binds to, to the debugger.
/// </summary>
Task<FSharpDebugDataTipInfo> GetDataTipInfoAsync(Document document, int position, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioWorkspaceImpl.AbstractRemoveDocumentUndoUnit.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.OLE.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
internal partial class VisualStudioWorkspaceImpl
{
private abstract class AbstractRemoveDocumentUndoUnit : AbstractAddRemoveUndoUnit
{
protected readonly DocumentId DocumentId;
protected AbstractRemoveDocumentUndoUnit(
VisualStudioWorkspaceImpl workspace,
DocumentId documentId)
: base(workspace, documentId.ProjectId)
{
DocumentId = documentId;
}
protected abstract IReadOnlyList<DocumentId> GetDocumentIds(Project fromProject);
protected abstract TextDocument? GetDocument(Solution currentSolution);
public override void Do(IOleUndoManager pUndoManager)
{
var currentSolution = Workspace.CurrentSolution;
var fromProject = currentSolution.GetProject(FromProjectId);
if (fromProject != null &&
GetDocumentIds(fromProject).Contains(DocumentId))
{
var updatedProject = fromProject.RemoveDocument(DocumentId);
Workspace.TryApplyChanges(updatedProject.Solution);
}
}
public override void GetDescription(out string pBstr)
{
var currentSolution = Workspace.CurrentSolution;
var document = GetDocument(currentSolution);
var documentName = document?.Name ?? "";
pBstr = string.Format(FeaturesResources.Remove_document_0, documentName);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.OLE.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
internal partial class VisualStudioWorkspaceImpl
{
private abstract class AbstractRemoveDocumentUndoUnit : AbstractAddRemoveUndoUnit
{
protected readonly DocumentId DocumentId;
protected AbstractRemoveDocumentUndoUnit(
VisualStudioWorkspaceImpl workspace,
DocumentId documentId)
: base(workspace, documentId.ProjectId)
{
DocumentId = documentId;
}
protected abstract IReadOnlyList<DocumentId> GetDocumentIds(Project fromProject);
protected abstract TextDocument? GetDocument(Solution currentSolution);
public override void Do(IOleUndoManager pUndoManager)
{
var currentSolution = Workspace.CurrentSolution;
var fromProject = currentSolution.GetProject(FromProjectId);
if (fromProject != null &&
GetDocumentIds(fromProject).Contains(DocumentId))
{
var updatedProject = fromProject.RemoveDocument(DocumentId);
Workspace.TryApplyChanges(updatedProject.Solution);
}
}
public override void GetDescription(out string pBstr)
{
var currentSolution = Workspace.CurrentSolution;
var document = GetDocument(currentSolution);
var documentName = document?.Name ?? "";
pBstr = string.Format(FeaturesResources.Remove_document_0, documentName);
}
}
}
}
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/Core/Portable/Utilities/GeneratorDriverRunResultExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.CodeAnalysis;
namespace Microsoft.CodeAnalysis.Utilities
{
internal static class GeneratorDriverRunResultExtensions
{
public static bool TryGetGeneratorAndHint(
this GeneratorDriverRunResult? generatorRunResult,
SyntaxTree tree,
[NotNullWhen(true)] out ISourceGenerator? generator,
[NotNullWhen(true)] out string? generatedSourceHintName)
{
if (generatorRunResult != null)
{
foreach (var generatorResult in generatorRunResult.Results)
{
foreach (var generatedSource in generatorResult.GeneratedSources)
{
if (generatedSource.SyntaxTree == tree)
{
generator = generatorResult.Generator;
generatedSourceHintName = generatedSource.HintName;
return true;
}
}
}
}
generator = null;
generatedSourceHintName = 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.Diagnostics.CodeAnalysis;
namespace Microsoft.CodeAnalysis.Utilities
{
internal static class GeneratorDriverRunResultExtensions
{
public static bool TryGetGeneratorAndHint(
this GeneratorDriverRunResult? generatorRunResult,
SyntaxTree tree,
[NotNullWhen(true)] out ISourceGenerator? generator,
[NotNullWhen(true)] out string? generatedSourceHintName)
{
if (generatorRunResult != null)
{
foreach (var generatorResult in generatorRunResult.Results)
{
foreach (var generatedSource in generatorResult.GeneratedSources)
{
if (generatedSource.SyntaxTree == tree)
{
generator = generatorResult.Generator;
generatedSourceHintName = generatedSource.HintName;
return true;
}
}
}
}
generator = null;
generatedSourceHintName = null;
return false;
}
}
}
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Test/Semantic/Semantics/ImplicitlyTypeArraysTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class ImplicitlyTypeArraysTests : SemanticModelTestBase
{
#region "Functionality tests"
[Fact]
public void ImplicitlyTypedArrayLocal()
{
var compilation = CreateCompilation(@"
class M {}
class C
{
public void F()
{
var a = new[] { new M() };
}
}
");
compilation.VerifyDiagnostics();
var method = (SourceMemberMethodSymbol)compilation.GlobalNamespace.GetTypeMembers("C").Single().GetMembers("F").Single();
var diagnostics = new DiagnosticBag();
var block = MethodCompiler.BindMethodBody(method, new TypeCompilationState(method.ContainingType, compilation, null), new BindingDiagnosticBag(diagnostics));
var locDecl = (BoundLocalDeclaration)block.Statements.Single();
var localA = (ArrayTypeSymbol)locDecl.DeclaredTypeOpt.Display;
var typeM = compilation.GlobalNamespace.GetMember<TypeSymbol>("M");
Assert.Equal(typeM, localA.ElementType);
}
[Fact]
public void ImplicitlyTypedArray_BindArrayInitializer()
{
var text = @"
class C
{
public void F()
{
var a = "";
var b = new[] { ""hello"", /*<bind>*/ a /*</bind>*/, null};
}
}
";
var tree = Parse(text);
var comp = CreateCompilation(tree);
var model = comp.GetSemanticModel(tree);
var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree));
var sym = model.GetSymbolInfo(expr);
Assert.Equal(SymbolKind.Local, sym.Symbol.Kind);
var info = model.GetTypeInfo(expr);
Assert.NotNull(info.Type);
Assert.NotNull(info.ConvertedType);
}
[Fact]
public void ImplicitlyTypedArray_BindImplicitlyTypedLocal()
{
var text = @"
class C
{
public void F()
{
/*<bind>*/ var a /*</bind>*/ = new[] { ""hello"", "", null};
}
}
";
var tree = Parse(text);
var comp = CreateCompilation(tree);
var model = comp.GetSemanticModel(tree);
var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree));
var symInfo = model.GetSymbolInfo(expr);
Assert.Equal("System.String[]", symInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.ArrayType, symInfo.Symbol.Kind);
var typeInfo = model.GetTypeInfo(expr);
Assert.NotNull(typeInfo.Type);
Assert.NotNull(typeInfo.ConvertedType);
}
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class ImplicitlyTypeArraysTests : SemanticModelTestBase
{
#region "Functionality tests"
[Fact]
public void ImplicitlyTypedArrayLocal()
{
var compilation = CreateCompilation(@"
class M {}
class C
{
public void F()
{
var a = new[] { new M() };
}
}
");
compilation.VerifyDiagnostics();
var method = (SourceMemberMethodSymbol)compilation.GlobalNamespace.GetTypeMembers("C").Single().GetMembers("F").Single();
var diagnostics = new DiagnosticBag();
var block = MethodCompiler.BindMethodBody(method, new TypeCompilationState(method.ContainingType, compilation, null), new BindingDiagnosticBag(diagnostics));
var locDecl = (BoundLocalDeclaration)block.Statements.Single();
var localA = (ArrayTypeSymbol)locDecl.DeclaredTypeOpt.Display;
var typeM = compilation.GlobalNamespace.GetMember<TypeSymbol>("M");
Assert.Equal(typeM, localA.ElementType);
}
[Fact]
public void ImplicitlyTypedArray_BindArrayInitializer()
{
var text = @"
class C
{
public void F()
{
var a = "";
var b = new[] { ""hello"", /*<bind>*/ a /*</bind>*/, null};
}
}
";
var tree = Parse(text);
var comp = CreateCompilation(tree);
var model = comp.GetSemanticModel(tree);
var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree));
var sym = model.GetSymbolInfo(expr);
Assert.Equal(SymbolKind.Local, sym.Symbol.Kind);
var info = model.GetTypeInfo(expr);
Assert.NotNull(info.Type);
Assert.NotNull(info.ConvertedType);
}
[Fact]
public void ImplicitlyTypedArray_BindImplicitlyTypedLocal()
{
var text = @"
class C
{
public void F()
{
/*<bind>*/ var a /*</bind>*/ = new[] { ""hello"", "", null};
}
}
";
var tree = Parse(text);
var comp = CreateCompilation(tree);
var model = comp.GetSemanticModel(tree);
var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree));
var symInfo = model.GetSymbolInfo(expr);
Assert.Equal("System.String[]", symInfo.Symbol.ToTestDisplayString());
Assert.Equal(SymbolKind.ArrayType, symInfo.Symbol.Kind);
var typeInfo = model.GetTypeInfo(expr);
Assert.NotNull(typeInfo.Type);
Assert.NotNull(typeInfo.ConvertedType);
}
#endregion
}
}
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Impl/ProjectSystem/CPS/CPSProject_ExternalErrorReporting.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.VisualStudio.LanguageServices.Implementation.TaskList;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.CPS
{
internal sealed partial class CPSProject : IVsReportExternalErrors, IVsLanguageServiceBuildErrorReporter2
{
private ProjectExternalErrorReporter GetExternalErrorReporter()
{
var errorReporter = _externalErrorReporter.Value;
if (errorReporter == null)
{
throw new InvalidOperationException("The language of the project doesn't support external errors.");
}
return errorReporter;
}
public int ClearAllErrors()
=> GetExternalErrorReporter().ClearAllErrors();
public int AddNewErrors(IVsEnumExternalErrors pErrors)
=> GetExternalErrorReporter().AddNewErrors(pErrors);
public int GetErrors(out IVsEnumExternalErrors pErrors)
=> GetExternalErrorReporter().GetErrors(out pErrors);
public int ReportError(string bstrErrorMessage, string bstrErrorId, VSTASKPRIORITY nPriority, int iLine, int iColumn, string bstrFileName)
=> GetExternalErrorReporter().ReportError(bstrErrorMessage, bstrErrorId, nPriority, iLine, iColumn, bstrFileName);
public int ClearErrors()
=> GetExternalErrorReporter().ClearErrors();
public void ReportError2(string bstrErrorMessage, string bstrErrorId, VSTASKPRIORITY nPriority, int iStartLine, int iStartColumn, int iEndLine, int iEndColumn, string bstrFileName)
=> GetExternalErrorReporter().ReportError2(bstrErrorMessage, bstrErrorId, nPriority, iStartLine, iStartColumn, iEndLine, iEndColumn, bstrFileName);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.VisualStudio.LanguageServices.Implementation.TaskList;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.CPS
{
internal sealed partial class CPSProject : IVsReportExternalErrors, IVsLanguageServiceBuildErrorReporter2
{
private ProjectExternalErrorReporter GetExternalErrorReporter()
{
var errorReporter = _externalErrorReporter.Value;
if (errorReporter == null)
{
throw new InvalidOperationException("The language of the project doesn't support external errors.");
}
return errorReporter;
}
public int ClearAllErrors()
=> GetExternalErrorReporter().ClearAllErrors();
public int AddNewErrors(IVsEnumExternalErrors pErrors)
=> GetExternalErrorReporter().AddNewErrors(pErrors);
public int GetErrors(out IVsEnumExternalErrors pErrors)
=> GetExternalErrorReporter().GetErrors(out pErrors);
public int ReportError(string bstrErrorMessage, string bstrErrorId, VSTASKPRIORITY nPriority, int iLine, int iColumn, string bstrFileName)
=> GetExternalErrorReporter().ReportError(bstrErrorMessage, bstrErrorId, nPriority, iLine, iColumn, bstrFileName);
public int ClearErrors()
=> GetExternalErrorReporter().ClearErrors();
public void ReportError2(string bstrErrorMessage, string bstrErrorId, VSTASKPRIORITY nPriority, int iStartLine, int iStartColumn, int iEndLine, int iEndColumn, string bstrFileName)
=> GetExternalErrorReporter().ReportError2(bstrErrorMessage, bstrErrorId, nPriority, iStartLine, iStartColumn, iEndLine, iEndColumn, bstrFileName);
}
}
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Xaml/Impl/Features/Completion/XamlCompletionItem.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text.Adornments;
namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Completion
{
internal class XamlCompletionItem
{
public string[] CommitCharacters { get; set; }
public XamlCommitCharacters? XamlCommitCharacters { get; set; }
public string DisplayText { get; set; }
public string InsertText { get; set; }
public string Detail { get; set; }
public string FilterText { get; set; }
public string SortText { get; set; }
public bool? Preselect { get; set; }
public TextSpan? Span { get; set; }
public XamlCompletionKind Kind { get; set; }
public ClassifiedTextElement Description { get; set; }
public ImageElement Icon { get; set; }
public ISymbol Symbol { get; set; }
public XamlEventDescription? EventDescription { get; set; }
public bool RetriggerCompletion { get; set; }
public bool IsSnippet { get; set; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text.Adornments;
namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Completion
{
internal class XamlCompletionItem
{
public string[] CommitCharacters { get; set; }
public XamlCommitCharacters? XamlCommitCharacters { get; set; }
public string DisplayText { get; set; }
public string InsertText { get; set; }
public string Detail { get; set; }
public string FilterText { get; set; }
public string SortText { get; set; }
public bool? Preselect { get; set; }
public TextSpan? Span { get; set; }
public XamlCompletionKind Kind { get; set; }
public ClassifiedTextElement Description { get; set; }
public ImageElement Icon { get; set; }
public ISymbol Symbol { get; set; }
public XamlEventDescription? EventDescription { get; set; }
public bool RetriggerCompletion { get; set; }
public bool IsSnippet { get; set; }
}
}
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/Core.Cocoa/Snippets/CSharpSnippets/SnippetCommandHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion;
using Microsoft.VisualStudio.LanguageServices.Implementation.Snippets;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Text.Editor.Expansion;
using Microsoft.VisualStudio.UI;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Snippets
{
[Export(typeof(ICommandHandler))]
[ContentType(CodeAnalysis.Editor.ContentTypeNames.CSharpContentType)]
[Name("CSharp Snippets")]
[Order(After = PredefinedCompletionNames.CompletionCommandHandler)]
[Order(After = CodeAnalysis.Editor.PredefinedCommandHandlerNames.SignatureHelpAfterCompletion)]
internal sealed class SnippetCommandHandler :
AbstractSnippetCommandHandler,
ICommandHandler<SurroundWithCommandArgs>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public SnippetCommandHandler(IThreadingContext threadingContext, IExpansionServiceProvider expansionServiceProvider, IExpansionManager expansionManager)
: base(threadingContext, expansionServiceProvider, expansionManager)
{
}
public bool ExecuteCommand(SurroundWithCommandArgs args, CommandExecutionContext context)
{
AssertIsForeground();
if (!AreSnippetsEnabled(args))
{
return false;
}
return TryInvokeInsertionUI(args.TextView, args.SubjectBuffer, surroundWith: true);
}
public CommandState GetCommandState(SurroundWithCommandArgs args)
{
AssertIsForeground();
if (!AreSnippetsEnabled(args))
{
return CommandState.Unspecified;
}
if (!CodeAnalysis.Workspace.TryGetWorkspace(args.SubjectBuffer.AsTextContainer(), out var workspace))
{
return CommandState.Unspecified;
}
if (!workspace.CanApplyChange(ApplyChangesKind.ChangeDocument))
{
return CommandState.Unspecified;
}
return CommandState.Available;
}
protected override AbstractSnippetExpansionClient GetSnippetExpansionClient(ITextView textView, ITextBuffer subjectBuffer)
{
if (!textView.Properties.TryGetProperty(typeof(AbstractSnippetExpansionClient), out AbstractSnippetExpansionClient expansionClient))
{
expansionClient = new SnippetExpansionClient(ThreadingContext, subjectBuffer.ContentType, textView, subjectBuffer, ExpansionServiceProvider);
textView.Properties.AddProperty(typeof(AbstractSnippetExpansionClient), expansionClient);
}
return expansionClient;
}
protected override bool TryInvokeInsertionUI(ITextView textView, ITextBuffer subjectBuffer, bool surroundWith = false)
{
ExpansionServiceProvider.GetExpansionService(textView).InvokeInsertionUI(
GetSnippetExpansionClient(textView, subjectBuffer),
subjectBuffer.ContentType,
types: surroundWith ? new[] { "SurroundsWith" } : new[] { "Expansion", "SurroundsWith" },
includeNullType: true,
kinds: null,
includeNullKind: false,
prefixText: surroundWith ? GettextCatalog.GetString("Surround With") : GettextCatalog.GetString("Insert Snippet"),
completionChar: null);
return true;
}
protected override bool IsSnippetExpansionContext(Document document, int startPosition, CancellationToken cancellationToken)
{
var syntaxTree = document.GetRequiredSyntaxTreeSynchronously(cancellationToken);
var token = syntaxTree.GetRoot(cancellationToken).FindToken(startPosition);
var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(startPosition);
return !(trivia.IsKind(SyntaxKind.MultiLineCommentTrivia) || trivia.IsKind(SyntaxKind.SingleLineCommentTrivia) || token.IsKind(SyntaxKind.StringLiteralToken));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion;
using Microsoft.VisualStudio.LanguageServices.Implementation.Snippets;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Text.Editor.Expansion;
using Microsoft.VisualStudio.UI;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Snippets
{
[Export(typeof(ICommandHandler))]
[ContentType(CodeAnalysis.Editor.ContentTypeNames.CSharpContentType)]
[Name("CSharp Snippets")]
[Order(After = PredefinedCompletionNames.CompletionCommandHandler)]
[Order(After = CodeAnalysis.Editor.PredefinedCommandHandlerNames.SignatureHelpAfterCompletion)]
internal sealed class SnippetCommandHandler :
AbstractSnippetCommandHandler,
ICommandHandler<SurroundWithCommandArgs>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public SnippetCommandHandler(IThreadingContext threadingContext, IExpansionServiceProvider expansionServiceProvider, IExpansionManager expansionManager)
: base(threadingContext, expansionServiceProvider, expansionManager)
{
}
public bool ExecuteCommand(SurroundWithCommandArgs args, CommandExecutionContext context)
{
AssertIsForeground();
if (!AreSnippetsEnabled(args))
{
return false;
}
return TryInvokeInsertionUI(args.TextView, args.SubjectBuffer, surroundWith: true);
}
public CommandState GetCommandState(SurroundWithCommandArgs args)
{
AssertIsForeground();
if (!AreSnippetsEnabled(args))
{
return CommandState.Unspecified;
}
if (!CodeAnalysis.Workspace.TryGetWorkspace(args.SubjectBuffer.AsTextContainer(), out var workspace))
{
return CommandState.Unspecified;
}
if (!workspace.CanApplyChange(ApplyChangesKind.ChangeDocument))
{
return CommandState.Unspecified;
}
return CommandState.Available;
}
protected override AbstractSnippetExpansionClient GetSnippetExpansionClient(ITextView textView, ITextBuffer subjectBuffer)
{
if (!textView.Properties.TryGetProperty(typeof(AbstractSnippetExpansionClient), out AbstractSnippetExpansionClient expansionClient))
{
expansionClient = new SnippetExpansionClient(ThreadingContext, subjectBuffer.ContentType, textView, subjectBuffer, ExpansionServiceProvider);
textView.Properties.AddProperty(typeof(AbstractSnippetExpansionClient), expansionClient);
}
return expansionClient;
}
protected override bool TryInvokeInsertionUI(ITextView textView, ITextBuffer subjectBuffer, bool surroundWith = false)
{
ExpansionServiceProvider.GetExpansionService(textView).InvokeInsertionUI(
GetSnippetExpansionClient(textView, subjectBuffer),
subjectBuffer.ContentType,
types: surroundWith ? new[] { "SurroundsWith" } : new[] { "Expansion", "SurroundsWith" },
includeNullType: true,
kinds: null,
includeNullKind: false,
prefixText: surroundWith ? GettextCatalog.GetString("Surround With") : GettextCatalog.GetString("Insert Snippet"),
completionChar: null);
return true;
}
protected override bool IsSnippetExpansionContext(Document document, int startPosition, CancellationToken cancellationToken)
{
var syntaxTree = document.GetRequiredSyntaxTreeSynchronously(cancellationToken);
var token = syntaxTree.GetRoot(cancellationToken).FindToken(startPosition);
var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(startPosition);
return !(trivia.IsKind(SyntaxKind.MultiLineCommentTrivia) || trivia.IsKind(SyntaxKind.SingleLineCommentTrivia) || token.IsKind(SyntaxKind.StringLiteralToken));
}
}
}
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Utilities/ImportsClauseComparer.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Utilities
Friend Class ImportsClauseComparer
Implements IComparer(Of ImportsClauseSyntax)
Public Shared ReadOnly NormalInstance As IComparer(Of ImportsClauseSyntax) = New ImportsClauseComparer()
Private ReadOnly _nameComparer As IComparer(Of NameSyntax)
Private ReadOnly _tokenComparer As IComparer(Of SyntaxToken)
Private Sub New()
_nameComparer = NameSyntaxComparer.Create(TokenComparer.NormalInstance)
_tokenComparer = TokenComparer.NormalInstance
End Sub
Public Sub New(tokenComparer As IComparer(Of SyntaxToken))
_nameComparer = NameSyntaxComparer.Create(tokenComparer)
_tokenComparer = tokenComparer
End Sub
Friend Function Compare(x As ImportsClauseSyntax, y As ImportsClauseSyntax) As Integer Implements IComparer(Of ImportsClauseSyntax).Compare
Dim imports1 = TryCast(x, SimpleImportsClauseSyntax)
Dim imports2 = TryCast(y, SimpleImportsClauseSyntax)
Dim xml1 = TryCast(x, XmlNamespaceImportsClauseSyntax)
Dim xml2 = TryCast(y, XmlNamespaceImportsClauseSyntax)
If xml1 IsNot Nothing AndAlso xml2 Is Nothing Then
Return 1
ElseIf xml1 Is Nothing AndAlso xml2 IsNot Nothing Then
Return -1
ElseIf xml1 IsNot Nothing AndAlso xml2 IsNot Nothing Then
Return CompareXmlNames(
DirectCast(xml1.XmlNamespace.Name, XmlNameSyntax),
DirectCast(xml2.XmlNamespace.Name, XmlNameSyntax))
ElseIf imports1 IsNot Nothing AndAlso imports2 IsNot Nothing Then
If imports1.Alias IsNot Nothing AndAlso imports2.Alias Is Nothing Then
Return 1
ElseIf imports1.Alias Is Nothing AndAlso imports2.Alias IsNot Nothing Then
Return -1
ElseIf imports1.Alias IsNot Nothing AndAlso imports2.Alias IsNot Nothing Then
Return _tokenComparer.Compare(imports1.Alias.Identifier, imports2.Alias.Identifier)
Else
Return _nameComparer.Compare(imports1.Name, imports2.Name)
End If
End If
Return 0
End Function
Private Function CompareXmlNames(xmlName1 As XmlNameSyntax, xmlName2 As XmlNameSyntax) As Integer
Dim tokens1 = xmlName1.DescendantTokens().Where(Function(t) t.Kind = SyntaxKind.IdentifierToken).ToList()
Dim tokens2 = xmlName2.DescendantTokens().Where(Function(t) t.Kind = SyntaxKind.IdentifierToken).ToList()
For i = 0 To Math.Min(tokens1.Count - 1, tokens2.Count - 1)
Dim compare = _tokenComparer.Compare(tokens1(i), tokens2(i))
If compare <> 0 Then
Return compare
End If
Next
Return tokens1.Count - tokens2.Count
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.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Utilities
Friend Class ImportsClauseComparer
Implements IComparer(Of ImportsClauseSyntax)
Public Shared ReadOnly NormalInstance As IComparer(Of ImportsClauseSyntax) = New ImportsClauseComparer()
Private ReadOnly _nameComparer As IComparer(Of NameSyntax)
Private ReadOnly _tokenComparer As IComparer(Of SyntaxToken)
Private Sub New()
_nameComparer = NameSyntaxComparer.Create(TokenComparer.NormalInstance)
_tokenComparer = TokenComparer.NormalInstance
End Sub
Public Sub New(tokenComparer As IComparer(Of SyntaxToken))
_nameComparer = NameSyntaxComparer.Create(tokenComparer)
_tokenComparer = tokenComparer
End Sub
Friend Function Compare(x As ImportsClauseSyntax, y As ImportsClauseSyntax) As Integer Implements IComparer(Of ImportsClauseSyntax).Compare
Dim imports1 = TryCast(x, SimpleImportsClauseSyntax)
Dim imports2 = TryCast(y, SimpleImportsClauseSyntax)
Dim xml1 = TryCast(x, XmlNamespaceImportsClauseSyntax)
Dim xml2 = TryCast(y, XmlNamespaceImportsClauseSyntax)
If xml1 IsNot Nothing AndAlso xml2 Is Nothing Then
Return 1
ElseIf xml1 Is Nothing AndAlso xml2 IsNot Nothing Then
Return -1
ElseIf xml1 IsNot Nothing AndAlso xml2 IsNot Nothing Then
Return CompareXmlNames(
DirectCast(xml1.XmlNamespace.Name, XmlNameSyntax),
DirectCast(xml2.XmlNamespace.Name, XmlNameSyntax))
ElseIf imports1 IsNot Nothing AndAlso imports2 IsNot Nothing Then
If imports1.Alias IsNot Nothing AndAlso imports2.Alias Is Nothing Then
Return 1
ElseIf imports1.Alias Is Nothing AndAlso imports2.Alias IsNot Nothing Then
Return -1
ElseIf imports1.Alias IsNot Nothing AndAlso imports2.Alias IsNot Nothing Then
Return _tokenComparer.Compare(imports1.Alias.Identifier, imports2.Alias.Identifier)
Else
Return _nameComparer.Compare(imports1.Name, imports2.Name)
End If
End If
Return 0
End Function
Private Function CompareXmlNames(xmlName1 As XmlNameSyntax, xmlName2 As XmlNameSyntax) As Integer
Dim tokens1 = xmlName1.DescendantTokens().Where(Function(t) t.Kind = SyntaxKind.IdentifierToken).ToList()
Dim tokens2 = xmlName2.DescendantTokens().Where(Function(t) t.Kind = SyntaxKind.IdentifierToken).ToList()
For i = 0 To Math.Min(tokens1.Count - 1, tokens2.Count - 1)
Dim compare = _tokenComparer.Compare(tokens1(i), tokens2(i))
If compare <> 0 Then
Return compare
End If
Next
Return tokens1.Count - tokens2.Count
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/VisualBasic/Portable/Binding/GetTypeBinder.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' This binder is for binding the argument to GetType. It traverses
''' the syntax marking each open type ("unbound generic type" in the
''' VB spec) as either allowed or not allowed, so that BindType can
''' appropriately return either the corresponding type symbol or an
''' error type.
''' </summary>
Friend Class GetTypeBinder
Inherits Binder
Private ReadOnly _allowedMap As Dictionary(Of GenericNameSyntax, Boolean)
Private ReadOnly _isTypeExpressionOpen As Boolean
Friend Sub New(typeExpression As ExpressionSyntax, containingBinder As Binder)
MyBase.New(containingBinder)
OpenTypeVisitor.Visit(typeExpression, _allowedMap, _isTypeExpressionOpen)
End Sub
Friend ReadOnly Property IsTypeExpressionOpen As Boolean
Get
Return _isTypeExpressionOpen
End Get
End Property
Public Overrides Function IsUnboundTypeAllowed(Syntax As GenericNameSyntax) As Boolean
Dim allowed As Boolean
Return _allowedMap IsNot Nothing AndAlso _allowedMap.TryGetValue(Syntax, allowed) AndAlso allowed
End Function
''' <summary>
''' This visitor walks over a type expression looking for open types.
''' Open types are allowed if an only if:
''' 1) There is no constructed generic type elsewhere in the visited syntax; and
''' 2) The open type is not used as a type argument or array/nullable
''' element type.
''' </summary>
Private Class OpenTypeVisitor
Inherits VisualBasicSyntaxVisitor
Private _allowedMap As Dictionary(Of GenericNameSyntax, Boolean) = Nothing
Private _seenConstructed As Boolean = False
Private _seenGeneric As Boolean = False
''' <param name="typeSyntax">The argument to typeof.</param>
''' <param name="allowedMap">
''' Keys are GenericNameSyntax nodes representing unbound generic types.
''' Values are false if the node should result in an error and true otherwise.
''' </param>
''' <param name="isOpenType">True if no constructed generic type was encountered.</param>
Public Overloads Shared Sub Visit(typeSyntax As ExpressionSyntax, <Out()> ByRef allowedMap As Dictionary(Of GenericNameSyntax, Boolean), <Out()> isOpenType As Boolean)
Dim visitor = New OpenTypeVisitor()
visitor.Visit(typeSyntax)
allowedMap = visitor._allowedMap
isOpenType = visitor._seenGeneric AndAlso Not visitor._seenConstructed
End Sub
Public Overrides Sub VisitGenericName(node As GenericNameSyntax)
_seenGeneric = True
Dim typeArguments As SeparatedSyntaxList(Of TypeSyntax) = node.TypeArgumentList.Arguments
' Missing type arguments are represented as missing name syntax
Dim isOpenType = typeArguments.AllAreMissingIdentifierName
If isOpenType Then
If _allowedMap Is Nothing Then
_allowedMap = New Dictionary(Of GenericNameSyntax, Boolean)()
End If
_allowedMap(node) = Not _seenConstructed
Else
_seenConstructed = True
For Each arg As TypeSyntax In typeArguments
Visit(arg)
Next
End If
End Sub
Public Overrides Sub VisitQualifiedName(node As QualifiedNameSyntax)
Dim seenConstructedBeforeRight As Boolean = _seenConstructed
' Visit Right first because it's smaller (to make backtracking cheaper).
Visit(node.Right)
Dim seenConstructedBeforeLeft As Boolean = _seenConstructed
Visit(node.Left)
' If the first time we saw a constructed type was in Left, then we need to re-visit Right
If Not seenConstructedBeforeRight AndAlso Not seenConstructedBeforeLeft AndAlso _seenConstructed Then
Visit(node.Right)
End If
End Sub
Public Overrides Sub VisitArrayType(node As ArrayTypeSyntax)
_seenConstructed = True
Visit(node.ElementType)
End Sub
Public Overrides Sub VisitNullableType(node As NullableTypeSyntax)
_seenConstructed = True
Visit(node.ElementType)
End Sub
End Class
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' This binder is for binding the argument to GetType. It traverses
''' the syntax marking each open type ("unbound generic type" in the
''' VB spec) as either allowed or not allowed, so that BindType can
''' appropriately return either the corresponding type symbol or an
''' error type.
''' </summary>
Friend Class GetTypeBinder
Inherits Binder
Private ReadOnly _allowedMap As Dictionary(Of GenericNameSyntax, Boolean)
Private ReadOnly _isTypeExpressionOpen As Boolean
Friend Sub New(typeExpression As ExpressionSyntax, containingBinder As Binder)
MyBase.New(containingBinder)
OpenTypeVisitor.Visit(typeExpression, _allowedMap, _isTypeExpressionOpen)
End Sub
Friend ReadOnly Property IsTypeExpressionOpen As Boolean
Get
Return _isTypeExpressionOpen
End Get
End Property
Public Overrides Function IsUnboundTypeAllowed(Syntax As GenericNameSyntax) As Boolean
Dim allowed As Boolean
Return _allowedMap IsNot Nothing AndAlso _allowedMap.TryGetValue(Syntax, allowed) AndAlso allowed
End Function
''' <summary>
''' This visitor walks over a type expression looking for open types.
''' Open types are allowed if an only if:
''' 1) There is no constructed generic type elsewhere in the visited syntax; and
''' 2) The open type is not used as a type argument or array/nullable
''' element type.
''' </summary>
Private Class OpenTypeVisitor
Inherits VisualBasicSyntaxVisitor
Private _allowedMap As Dictionary(Of GenericNameSyntax, Boolean) = Nothing
Private _seenConstructed As Boolean = False
Private _seenGeneric As Boolean = False
''' <param name="typeSyntax">The argument to typeof.</param>
''' <param name="allowedMap">
''' Keys are GenericNameSyntax nodes representing unbound generic types.
''' Values are false if the node should result in an error and true otherwise.
''' </param>
''' <param name="isOpenType">True if no constructed generic type was encountered.</param>
Public Overloads Shared Sub Visit(typeSyntax As ExpressionSyntax, <Out()> ByRef allowedMap As Dictionary(Of GenericNameSyntax, Boolean), <Out()> isOpenType As Boolean)
Dim visitor = New OpenTypeVisitor()
visitor.Visit(typeSyntax)
allowedMap = visitor._allowedMap
isOpenType = visitor._seenGeneric AndAlso Not visitor._seenConstructed
End Sub
Public Overrides Sub VisitGenericName(node As GenericNameSyntax)
_seenGeneric = True
Dim typeArguments As SeparatedSyntaxList(Of TypeSyntax) = node.TypeArgumentList.Arguments
' Missing type arguments are represented as missing name syntax
Dim isOpenType = typeArguments.AllAreMissingIdentifierName
If isOpenType Then
If _allowedMap Is Nothing Then
_allowedMap = New Dictionary(Of GenericNameSyntax, Boolean)()
End If
_allowedMap(node) = Not _seenConstructed
Else
_seenConstructed = True
For Each arg As TypeSyntax In typeArguments
Visit(arg)
Next
End If
End Sub
Public Overrides Sub VisitQualifiedName(node As QualifiedNameSyntax)
Dim seenConstructedBeforeRight As Boolean = _seenConstructed
' Visit Right first because it's smaller (to make backtracking cheaper).
Visit(node.Right)
Dim seenConstructedBeforeLeft As Boolean = _seenConstructed
Visit(node.Left)
' If the first time we saw a constructed type was in Left, then we need to re-visit Right
If Not seenConstructedBeforeRight AndAlso Not seenConstructedBeforeLeft AndAlso _seenConstructed Then
Visit(node.Right)
End If
End Sub
Public Overrides Sub VisitArrayType(node As ArrayTypeSyntax)
_seenConstructed = True
Visit(node.ElementType)
End Sub
Public Overrides Sub VisitNullableType(node As NullableTypeSyntax)
_seenConstructed = True
Visit(node.ElementType)
End Sub
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/VisualBasic/Portable/Editing/VisualBasicImportAdder.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editing
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Editing
<ExportLanguageService(GetType(ImportAdderService), LanguageNames.VisualBasic), [Shared]>
Partial Friend Class VisualBasicImportAdder
Inherits ImportAdderService
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Protected Overrides Function GetExplicitNamespaceSymbol(node As SyntaxNode, model As SemanticModel) As INamespaceSymbol
Dim qname = TryCast(node, QualifiedNameSyntax)
If qname IsNot Nothing Then
Return GetExplicitNamespaceSymbol(qname, qname.Left, model)
End If
Dim maccess = TryCast(node, MemberAccessExpressionSyntax)
If maccess IsNot Nothing Then
Return GetExplicitNamespaceSymbol(maccess, maccess.Expression, model)
End If
Return Nothing
End Function
Protected Overrides Sub AddPotentiallyConflictingImports(model As SemanticModel,
container As SyntaxNode,
namespaceSymbols As ImmutableArray(Of INamespaceSymbol),
conflicts As HashSet(Of INamespaceSymbol),
cancellationToken As CancellationToken)
Dim walker = New ConflictWalker(model, namespaceSymbols, conflicts, cancellationToken)
walker.Visit(container)
End Sub
Private Overloads Shared Function GetExplicitNamespaceSymbol(fullName As ExpressionSyntax, namespacePart As ExpressionSyntax, model As SemanticModel) As INamespaceSymbol
' name must refer to something that is not a namespace, but be qualified with a namespace.
Dim Symbol = model.GetSymbolInfo(fullName).Symbol
Dim nsSymbol = TryCast(model.GetSymbolInfo(namespacePart).Symbol, INamespaceSymbol)
If Symbol IsNot Nothing AndAlso Symbol.Kind <> SymbolKind.Namespace AndAlso nsSymbol IsNot Nothing Then
' use the symbols containing namespace, and not the potentially less than fully qualified namespace in the full name expression.
Dim ns = Symbol.ContainingNamespace
If ns IsNot Nothing Then
Return model.Compilation.GetCompilationNamespace(ns)
End If
End If
Return Nothing
End Function
Private Class ConflictWalker
Inherits VisualBasicSyntaxWalker
Implements IEqualityComparer(Of (name As String, arity As Integer))
Private ReadOnly _cancellationToken As CancellationToken
Private ReadOnly _model As SemanticModel
''' <summary>
''' A mapping containing the simple names And arity of all namespace members, mapped to the import that
''' they're brought in by.
''' </summary>
Private ReadOnly _importedTypesAndNamespaces As MultiDictionary(Of (name As String, arity As Integer), INamespaceSymbol)
''' <summary>
''' A mapping containing the simple names of all members, mapped to the import that they're brought in by.
''' Members are imported in through modules in vb. This doesn't keep track of arity because methods can be
''' called with type arguments.
''' </summary>
Private ReadOnly _importedMembers As MultiDictionary(Of String, INamespaceSymbol)
''' <summary>
''' A mapping containing the simple names of all extension methods, mapped to the import that they're
''' brought in by. This doesn't keep track of arity because methods can be called with type arguments.
''' </summary>
Private ReadOnly _importedExtensionMethods As MultiDictionary(Of String, INamespaceSymbol)
Private ReadOnly _conflictNamespaces As HashSet(Of INamespaceSymbol)
''' <summary>
''' Track if we're in an anonymous method or not. If so, because of how the language binds lambdas and
''' overloads, we'll assume any method access we see inside (instance or otherwise) could end up conflicting
''' with an extension method we might pull in.
''' </summary>
Private _inAnonymousMethod As Boolean
Public Sub New(
model As SemanticModel,
namespaceSymbols As ImmutableArray(Of INamespaceSymbol),
conflictNamespaces As HashSet(Of INamespaceSymbol),
cancellationToken As CancellationToken)
MyBase.New(SyntaxWalkerDepth.StructuredTrivia)
_model = model
_cancellationToken = cancellationToken
_conflictNamespaces = conflictNamespaces
_importedTypesAndNamespaces = New MultiDictionary(Of (name As String, arity As Integer), INamespaceSymbol)(Me)
_importedMembers = New MultiDictionary(Of String, INamespaceSymbol)(VisualBasicSyntaxFacts.Instance.StringComparer)
_importedExtensionMethods = New MultiDictionary(Of String, INamespaceSymbol)(VisualBasicSyntaxFacts.Instance.StringComparer)
AddImportedMembers(namespaceSymbols)
End Sub
Private Sub AddImportedMembers(namespaceSymbols As ImmutableArray(Of INamespaceSymbol))
For Each ns In namespaceSymbols
For Each typeOrNamespace In ns.GetMembers()
_importedTypesAndNamespaces.Add((typeOrNamespace.Name, typeOrNamespace.GetArity()), ns)
Dim type = TryCast(typeOrNamespace, INamedTypeSymbol)
If type?.MightContainExtensionMethods Then
For Each member In type.GetMembers()
Dim method = TryCast(member, IMethodSymbol)
If method?.IsExtensionMethod Then
_importedExtensionMethods.Add(method.Name, ns)
End If
Next
End If
If type?.TypeKind = TypeKind.Module Then
' modules make their members available to the containing scope.
For Each member In type.GetMembers()
Dim moduleType = TryCast(member, INamedTypeSymbol)
If moduleType IsNot Nothing Then
_importedTypesAndNamespaces.Add((moduleType.Name, moduleType.GetArity()), ns)
Else
_importedMembers.Add(member.Name, ns)
End If
Next
End If
Next
Next
End Sub
Public Overrides Sub VisitMultiLineLambdaExpression(node As MultiLineLambdaExpressionSyntax)
' lambdas are interesting. Say you have
'
' Goo(sub (x) x.M())
'
' sub Goo(act as Action(of C))
' sub Goo(act as Action(of integer))
'
' class C : public sub M()
'
' This Is legal code where the lambda body Is calling the instance method. However, if we introduce a
' using that brings in an extension method 'M' on 'int', then the above will become ambiguous. This is
' because lambda binding will try each interpretation separately And eliminate the ones that fail.
' Adding the import will make the int form succeed, causing ambiguity.
'
' To deal with that, we keep track of if we're in a lambda, and we conservatively assume that a method
' access (even to a non-extension method) could conflict with an extension method brought in.
Dim previousInAnonymousMethod = _inAnonymousMethod
_inAnonymousMethod = True
MyBase.VisitMultiLineLambdaExpression(node)
_inAnonymousMethod = previousInAnonymousMethod
End Sub
Public Overrides Sub VisitSingleLineLambdaExpression(node As SingleLineLambdaExpressionSyntax)
Dim previousInAnonymousMethod = _inAnonymousMethod
_inAnonymousMethod = True
MyBase.VisitSingleLineLambdaExpression(node)
_inAnonymousMethod = previousInAnonymousMethod
End Sub
Private Sub CheckName(node As NameSyntax, name As String)
' Check to see if we have an standalone identifier (Or identifier on the left of a dot). If so, then we
' don't want to bring in any imports that would bring in the same name And could then potentially
' conflict here.
If node.IsRightSideOfDotOrBang Then
Return
End If
_conflictNamespaces.AddRange(_importedTypesAndNamespaces((name, node.Arity)))
_conflictNamespaces.AddRange(_importedMembers(name))
End Sub
Public Overrides Sub VisitIdentifierName(node As IdentifierNameSyntax)
MyBase.VisitIdentifierName(node)
CheckName(node, node.Identifier.ValueText)
End Sub
Public Overrides Sub VisitGenericName(node As GenericNameSyntax)
MyBase.VisitGenericName(node)
CheckName(node, node.Identifier.ValueText)
End Sub
Public Overrides Sub VisitMemberAccessExpression(node As MemberAccessExpressionSyntax)
MyBase.VisitMemberAccessExpression(node)
' Check to see if we have a reference to an extension method. If so, then pulling in an import could
' bring in an extension that conflicts with that.
Dim method = TryCast(_model.GetSymbolInfo(node.Name, _cancellationToken).GetAnySymbol(), IMethodSymbol)
If method IsNot Nothing Then
' see explanation in VisitSimpleLambdaExpression for the _inAnonymousMethod check
If method.IsReducedExtension() OrElse _inAnonymousMethod Then
_conflictNamespaces.AddRange(_importedExtensionMethods(method.Name))
End If
End If
End Sub
Public Shadows Function Equals(
x As (name As String, arity As Integer),
y As (name As String, arity As Integer)) As Boolean Implements IEqualityComparer(Of (name As String, arity As Integer)).Equals
Return x.arity = y.arity AndAlso
VisualBasicSyntaxFacts.Instance.StringComparer.Equals(x.name, y.name)
End Function
Public Shadows Function GetHashCode(obj As (name As String, arity As Integer)) As Integer Implements IEqualityComparer(Of (name As String, arity As Integer)).GetHashCode
Return Hash.Combine(obj.arity,
VisualBasicSyntaxFacts.Instance.StringComparer.GetHashCode(obj.name))
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 System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editing
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Editing
<ExportLanguageService(GetType(ImportAdderService), LanguageNames.VisualBasic), [Shared]>
Partial Friend Class VisualBasicImportAdder
Inherits ImportAdderService
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Protected Overrides Function GetExplicitNamespaceSymbol(node As SyntaxNode, model As SemanticModel) As INamespaceSymbol
Dim qname = TryCast(node, QualifiedNameSyntax)
If qname IsNot Nothing Then
Return GetExplicitNamespaceSymbol(qname, qname.Left, model)
End If
Dim maccess = TryCast(node, MemberAccessExpressionSyntax)
If maccess IsNot Nothing Then
Return GetExplicitNamespaceSymbol(maccess, maccess.Expression, model)
End If
Return Nothing
End Function
Protected Overrides Sub AddPotentiallyConflictingImports(model As SemanticModel,
container As SyntaxNode,
namespaceSymbols As ImmutableArray(Of INamespaceSymbol),
conflicts As HashSet(Of INamespaceSymbol),
cancellationToken As CancellationToken)
Dim walker = New ConflictWalker(model, namespaceSymbols, conflicts, cancellationToken)
walker.Visit(container)
End Sub
Private Overloads Shared Function GetExplicitNamespaceSymbol(fullName As ExpressionSyntax, namespacePart As ExpressionSyntax, model As SemanticModel) As INamespaceSymbol
' name must refer to something that is not a namespace, but be qualified with a namespace.
Dim Symbol = model.GetSymbolInfo(fullName).Symbol
Dim nsSymbol = TryCast(model.GetSymbolInfo(namespacePart).Symbol, INamespaceSymbol)
If Symbol IsNot Nothing AndAlso Symbol.Kind <> SymbolKind.Namespace AndAlso nsSymbol IsNot Nothing Then
' use the symbols containing namespace, and not the potentially less than fully qualified namespace in the full name expression.
Dim ns = Symbol.ContainingNamespace
If ns IsNot Nothing Then
Return model.Compilation.GetCompilationNamespace(ns)
End If
End If
Return Nothing
End Function
Private Class ConflictWalker
Inherits VisualBasicSyntaxWalker
Implements IEqualityComparer(Of (name As String, arity As Integer))
Private ReadOnly _cancellationToken As CancellationToken
Private ReadOnly _model As SemanticModel
''' <summary>
''' A mapping containing the simple names And arity of all namespace members, mapped to the import that
''' they're brought in by.
''' </summary>
Private ReadOnly _importedTypesAndNamespaces As MultiDictionary(Of (name As String, arity As Integer), INamespaceSymbol)
''' <summary>
''' A mapping containing the simple names of all members, mapped to the import that they're brought in by.
''' Members are imported in through modules in vb. This doesn't keep track of arity because methods can be
''' called with type arguments.
''' </summary>
Private ReadOnly _importedMembers As MultiDictionary(Of String, INamespaceSymbol)
''' <summary>
''' A mapping containing the simple names of all extension methods, mapped to the import that they're
''' brought in by. This doesn't keep track of arity because methods can be called with type arguments.
''' </summary>
Private ReadOnly _importedExtensionMethods As MultiDictionary(Of String, INamespaceSymbol)
Private ReadOnly _conflictNamespaces As HashSet(Of INamespaceSymbol)
''' <summary>
''' Track if we're in an anonymous method or not. If so, because of how the language binds lambdas and
''' overloads, we'll assume any method access we see inside (instance or otherwise) could end up conflicting
''' with an extension method we might pull in.
''' </summary>
Private _inAnonymousMethod As Boolean
Public Sub New(
model As SemanticModel,
namespaceSymbols As ImmutableArray(Of INamespaceSymbol),
conflictNamespaces As HashSet(Of INamespaceSymbol),
cancellationToken As CancellationToken)
MyBase.New(SyntaxWalkerDepth.StructuredTrivia)
_model = model
_cancellationToken = cancellationToken
_conflictNamespaces = conflictNamespaces
_importedTypesAndNamespaces = New MultiDictionary(Of (name As String, arity As Integer), INamespaceSymbol)(Me)
_importedMembers = New MultiDictionary(Of String, INamespaceSymbol)(VisualBasicSyntaxFacts.Instance.StringComparer)
_importedExtensionMethods = New MultiDictionary(Of String, INamespaceSymbol)(VisualBasicSyntaxFacts.Instance.StringComparer)
AddImportedMembers(namespaceSymbols)
End Sub
Private Sub AddImportedMembers(namespaceSymbols As ImmutableArray(Of INamespaceSymbol))
For Each ns In namespaceSymbols
For Each typeOrNamespace In ns.GetMembers()
_importedTypesAndNamespaces.Add((typeOrNamespace.Name, typeOrNamespace.GetArity()), ns)
Dim type = TryCast(typeOrNamespace, INamedTypeSymbol)
If type?.MightContainExtensionMethods Then
For Each member In type.GetMembers()
Dim method = TryCast(member, IMethodSymbol)
If method?.IsExtensionMethod Then
_importedExtensionMethods.Add(method.Name, ns)
End If
Next
End If
If type?.TypeKind = TypeKind.Module Then
' modules make their members available to the containing scope.
For Each member In type.GetMembers()
Dim moduleType = TryCast(member, INamedTypeSymbol)
If moduleType IsNot Nothing Then
_importedTypesAndNamespaces.Add((moduleType.Name, moduleType.GetArity()), ns)
Else
_importedMembers.Add(member.Name, ns)
End If
Next
End If
Next
Next
End Sub
Public Overrides Sub VisitMultiLineLambdaExpression(node As MultiLineLambdaExpressionSyntax)
' lambdas are interesting. Say you have
'
' Goo(sub (x) x.M())
'
' sub Goo(act as Action(of C))
' sub Goo(act as Action(of integer))
'
' class C : public sub M()
'
' This Is legal code where the lambda body Is calling the instance method. However, if we introduce a
' using that brings in an extension method 'M' on 'int', then the above will become ambiguous. This is
' because lambda binding will try each interpretation separately And eliminate the ones that fail.
' Adding the import will make the int form succeed, causing ambiguity.
'
' To deal with that, we keep track of if we're in a lambda, and we conservatively assume that a method
' access (even to a non-extension method) could conflict with an extension method brought in.
Dim previousInAnonymousMethod = _inAnonymousMethod
_inAnonymousMethod = True
MyBase.VisitMultiLineLambdaExpression(node)
_inAnonymousMethod = previousInAnonymousMethod
End Sub
Public Overrides Sub VisitSingleLineLambdaExpression(node As SingleLineLambdaExpressionSyntax)
Dim previousInAnonymousMethod = _inAnonymousMethod
_inAnonymousMethod = True
MyBase.VisitSingleLineLambdaExpression(node)
_inAnonymousMethod = previousInAnonymousMethod
End Sub
Private Sub CheckName(node As NameSyntax, name As String)
' Check to see if we have an standalone identifier (Or identifier on the left of a dot). If so, then we
' don't want to bring in any imports that would bring in the same name And could then potentially
' conflict here.
If node.IsRightSideOfDotOrBang Then
Return
End If
_conflictNamespaces.AddRange(_importedTypesAndNamespaces((name, node.Arity)))
_conflictNamespaces.AddRange(_importedMembers(name))
End Sub
Public Overrides Sub VisitIdentifierName(node As IdentifierNameSyntax)
MyBase.VisitIdentifierName(node)
CheckName(node, node.Identifier.ValueText)
End Sub
Public Overrides Sub VisitGenericName(node As GenericNameSyntax)
MyBase.VisitGenericName(node)
CheckName(node, node.Identifier.ValueText)
End Sub
Public Overrides Sub VisitMemberAccessExpression(node As MemberAccessExpressionSyntax)
MyBase.VisitMemberAccessExpression(node)
' Check to see if we have a reference to an extension method. If so, then pulling in an import could
' bring in an extension that conflicts with that.
Dim method = TryCast(_model.GetSymbolInfo(node.Name, _cancellationToken).GetAnySymbol(), IMethodSymbol)
If method IsNot Nothing Then
' see explanation in VisitSimpleLambdaExpression for the _inAnonymousMethod check
If method.IsReducedExtension() OrElse _inAnonymousMethod Then
_conflictNamespaces.AddRange(_importedExtensionMethods(method.Name))
End If
End If
End Sub
Public Shadows Function Equals(
x As (name As String, arity As Integer),
y As (name As String, arity As Integer)) As Boolean Implements IEqualityComparer(Of (name As String, arity As Integer)).Equals
Return x.arity = y.arity AndAlso
VisualBasicSyntaxFacts.Instance.StringComparer.Equals(x.name, y.name)
End Function
Public Shadows Function GetHashCode(obj As (name As String, arity As Integer)) As Integer Implements IEqualityComparer(Of (name As String, arity As Integer)).GetHashCode
Return Hash.Combine(obj.arity,
VisualBasicSyntaxFacts.Instance.StringComparer.GetHashCode(obj.name))
End Function
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Test/Emit/CodeGen/PatternTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public class PatternTests : EmitMetadataTestBase
{
#region Miscellaneous
[Fact, WorkItem(18811, "https://github.com/dotnet/roslyn/issues/18811")]
public void MissingNullable_01()
{
var source = @"namespace System {
public class Object { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
}
static class C {
public static bool M() => ((object)123) is int i;
}
";
var compilation = CreateEmptyCompilation(source, options: TestOptions.ReleaseDll);
compilation.GetDiagnostics().Verify();
compilation.GetEmitDiagnostics().Verify(
// warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options.
Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1)
);
}
[Fact, WorkItem(18811, "https://github.com/dotnet/roslyn/issues/18811")]
public void MissingNullable_02()
{
var source = @"namespace System {
public class Object { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public struct Nullable<T> where T : struct { }
}
static class C {
public static bool M() => ((object)123) is int i;
}
";
var compilation = CreateEmptyCompilation(source, options: TestOptions.UnsafeReleaseDll);
compilation.GetDiagnostics().Verify();
compilation.GetEmitDiagnostics().Verify(
// warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options.
Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion)
);
}
[Fact]
public void MissingNullable_03()
{
var source = @"namespace System {
public class Object { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public struct Nullable<T> where T : struct { }
}
static class C {
static void M1(int? x)
{
switch (x)
{
case int i: break;
}
}
static bool M2(int? x) => x is int i;
}
";
var compilation = CreateEmptyCompilation(source, options: TestOptions.UnsafeReleaseDll);
compilation.GetDiagnostics().Verify();
compilation.GetEmitDiagnostics().Verify(
// warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options.
Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1),
// (14,18): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue'
// case int i: break;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(14, 18),
// (14,18): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault'
// case int i: break;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(14, 18),
// (14,18): error CS0656: Missing compiler required member 'System.Nullable`1.get_Value'
// case int i: break;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "get_Value").WithLocation(14, 18),
// (17,36): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue'
// static bool M2(int? x) => x is int i;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(17, 36),
// (17,36): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault'
// static bool M2(int? x) => x is int i;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(17, 36),
// (17,36): error CS0656: Missing compiler required member 'System.Nullable`1.get_Value'
// static bool M2(int? x) => x is int i;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "get_Value").WithLocation(17, 36)
);
}
[Fact]
public void MissingNullable_04()
{
var source = @"namespace System {
public class Object { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public struct Nullable<T> where T : struct { public T GetValueOrDefault() => default(T); }
}
static class C {
static void M1(int? x)
{
switch (x)
{
case int i: break;
}
}
static bool M2(int? x) => x is int i;
}
";
var compilation = CreateEmptyCompilation(source, options: TestOptions.UnsafeReleaseDll);
compilation.GetDiagnostics().Verify();
compilation.GetEmitDiagnostics().Verify(
// warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options.
Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1),
// (14,18): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue'
// case int i: break;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(14, 18),
// (17,36): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue'
// static bool M2(int? x) => x is int i;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(17, 36)
);
}
[Fact, WorkItem(17266, "https://github.com/dotnet/roslyn/issues/17266")]
public void DoubleEvaluation01()
{
var source =
@"using System;
public class C
{
public static void Main()
{
if (TryGet() is int index)
{
Console.WriteLine(index);
}
}
public static int? TryGet()
{
Console.WriteLine(""eval"");
return null;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics();
var expectedOutput = @"eval";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("C.Main",
@"{
// Code size 42 (0x2a)
.maxstack 1
.locals init (int V_0, //index
bool V_1,
int? V_2)
IL_0000: nop
IL_0001: call ""int? C.TryGet()""
IL_0006: stloc.2
IL_0007: ldloca.s V_2
IL_0009: call ""bool int?.HasValue.get""
IL_000e: brfalse.s IL_001b
IL_0010: ldloca.s V_2
IL_0012: call ""int int?.GetValueOrDefault()""
IL_0017: stloc.0
IL_0018: ldc.i4.1
IL_0019: br.s IL_001c
IL_001b: ldc.i4.0
IL_001c: stloc.1
IL_001d: ldloc.1
IL_001e: brfalse.s IL_0029
IL_0020: nop
IL_0021: ldloc.0
IL_0022: call ""void System.Console.WriteLine(int)""
IL_0027: nop
IL_0028: nop
IL_0029: ret
}");
compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("C.Main",
@"{
// Code size 30 (0x1e)
.maxstack 1
.locals init (int V_0, //index
int? V_1)
IL_0000: call ""int? C.TryGet()""
IL_0005: stloc.1
IL_0006: ldloca.s V_1
IL_0008: call ""bool int?.HasValue.get""
IL_000d: brfalse.s IL_001d
IL_000f: ldloca.s V_1
IL_0011: call ""int int?.GetValueOrDefault()""
IL_0016: stloc.0
IL_0017: ldloc.0
IL_0018: call ""void System.Console.WriteLine(int)""
IL_001d: ret
}");
}
[Fact, WorkItem(19122, "https://github.com/dotnet/roslyn/issues/19122")]
public void PatternCrash_01()
{
var source = @"using System;
using System.Collections.Generic;
using System.Linq;
public class Class2 : IDisposable
{
public Class2(bool parameter = false)
{
}
public void Dispose()
{
}
}
class X<T>
{
IdentityAccessor<T> idAccessor = new IdentityAccessor<T>();
void Y<U>() where U : T
{
// BUG: The following line is the problem
if (GetT().FirstOrDefault(p => idAccessor.GetId(p) == Guid.Empty) is U u)
{
}
}
IEnumerable<T> GetT()
{
yield return default(T);
}
}
class IdentityAccessor<T>
{
public Guid GetId(T t)
{
return Guid.Empty;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("X<T>.Y<U>",
@"{
// Code size 61 (0x3d)
.maxstack 3
.locals init (U V_0, //u
bool V_1,
T V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call ""System.Collections.Generic.IEnumerable<T> X<T>.GetT()""
IL_0007: ldarg.0
IL_0008: ldftn ""bool X<T>.<Y>b__1_0<U>(T)""
IL_000e: newobj ""System.Func<T, bool>..ctor(object, System.IntPtr)""
IL_0013: call ""T System.Linq.Enumerable.FirstOrDefault<T>(System.Collections.Generic.IEnumerable<T>, System.Func<T, bool>)""
IL_0018: stloc.2
IL_0019: ldloc.2
IL_001a: box ""T""
IL_001f: isinst ""U""
IL_0024: brfalse.s IL_0035
IL_0026: ldloc.2
IL_0027: box ""T""
IL_002c: unbox.any ""U""
IL_0031: stloc.0
IL_0032: ldc.i4.1
IL_0033: br.s IL_0036
IL_0035: ldc.i4.0
IL_0036: stloc.1
IL_0037: ldloc.1
IL_0038: brfalse.s IL_003c
IL_003a: nop
IL_003b: nop
IL_003c: ret
}");
}
[Fact, WorkItem(24522, "https://github.com/dotnet/roslyn/issues/24522")]
public void IgnoreDeclaredConversion_01()
{
var source =
@"class Base<T>
{
public static implicit operator Derived(Base<T> obj)
{
return new Derived();
}
}
class Derived : Base<object>
{
}
class Program
{
static void Main(string[] args)
{
Base<object> x = new Derived();
System.Console.WriteLine(x is Derived);
System.Console.WriteLine(x is Derived y);
switch (x)
{
case Derived z: System.Console.WriteLine(true); break;
}
System.Console.WriteLine(null != (x as Derived));
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics();
var expectedOutput =
@"True
True
True
True";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("Program.Main",
@"{
// Code size 84 (0x54)
.maxstack 2
.locals init (Base<object> V_0, //x
Derived V_1, //y
Derived V_2, //z
Base<object> V_3,
Base<object> V_4)
IL_0000: nop
IL_0001: newobj ""Derived..ctor()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: isinst ""Derived""
IL_000d: ldnull
IL_000e: cgt.un
IL_0010: call ""void System.Console.WriteLine(bool)""
IL_0015: nop
IL_0016: ldloc.0
IL_0017: isinst ""Derived""
IL_001c: stloc.1
IL_001d: ldloc.1
IL_001e: ldnull
IL_001f: cgt.un
IL_0021: call ""void System.Console.WriteLine(bool)""
IL_0026: nop
IL_0027: ldloc.0
IL_0028: stloc.s V_4
IL_002a: ldloc.s V_4
IL_002c: stloc.3
IL_002d: ldloc.3
IL_002e: isinst ""Derived""
IL_0033: stloc.2
IL_0034: ldloc.2
IL_0035: brtrue.s IL_0039
IL_0037: br.s IL_0044
IL_0039: br.s IL_003b
IL_003b: ldc.i4.1
IL_003c: call ""void System.Console.WriteLine(bool)""
IL_0041: nop
IL_0042: br.s IL_0044
IL_0044: ldloc.0
IL_0045: isinst ""Derived""
IL_004a: ldnull
IL_004b: cgt.un
IL_004d: call ""void System.Console.WriteLine(bool)""
IL_0052: nop
IL_0053: ret
}");
}
[Fact]
public void DoublePattern01()
{
var source =
@"using System;
class Program
{
static bool P1(double d) => d is double.NaN;
static bool P2(float f) => f is float.NaN;
static bool P3(double d) => d is 3.14d;
static bool P4(float f) => f is 3.14f;
static bool P5(object o)
{
switch (o)
{
case double.NaN: return true;
case float.NaN: return true;
case 3.14d: return true;
case 3.14f: return true;
default: return false;
}
}
public static void Main(string[] args)
{
Console.Write(P1(double.NaN));
Console.Write(P1(1.0));
Console.Write(P2(float.NaN));
Console.Write(P2(1.0f));
Console.Write(P3(3.14));
Console.Write(P3(double.NaN));
Console.Write(P4(3.14f));
Console.Write(P4(float.NaN));
Console.Write(P5(double.NaN));
Console.Write(P5(0.0d));
Console.Write(P5(float.NaN));
Console.Write(P5(0.0f));
Console.Write(P5(3.14d));
Console.Write(P5(125));
Console.Write(P5(3.14f));
Console.Write(P5(1.0f));
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics();
var expectedOutput = @"TrueFalseTrueFalseTrueFalseTrueFalseTrueFalseTrueFalseTrueFalseTrueFalse";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("Program.P1",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""bool double.IsNaN(double)""
IL_0006: ret
}");
compVerifier.VerifyIL("Program.P2",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""bool float.IsNaN(float)""
IL_0006: ret
}");
compVerifier.VerifyIL("Program.P3",
@"{
// Code size 13 (0xd)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.r8 3.14
IL_000a: ceq
IL_000c: ret
}");
compVerifier.VerifyIL("Program.P4",
@"{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.r4 3.14
IL_0006: ceq
IL_0008: ret
}");
compVerifier.VerifyIL("Program.P5",
@"{
// Code size 103 (0x67)
.maxstack 2
.locals init (object V_0,
double V_1,
float V_2,
object V_3,
bool V_4)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.3
IL_0003: ldloc.3
IL_0004: stloc.0
IL_0005: ldloc.0
IL_0006: isinst ""double""
IL_000b: brfalse.s IL_002a
IL_000d: ldloc.0
IL_000e: unbox.any ""double""
IL_0013: stloc.1
IL_0014: ldloc.1
IL_0015: ldc.r8 3.14
IL_001e: beq.s IL_0055
IL_0020: ldloc.1
IL_0021: call ""bool double.IsNaN(double)""
IL_0026: brtrue.s IL_004b
IL_0028: br.s IL_005f
IL_002a: ldloc.0
IL_002b: isinst ""float""
IL_0030: brfalse.s IL_005f
IL_0032: ldloc.0
IL_0033: unbox.any ""float""
IL_0038: stloc.2
IL_0039: ldloc.2
IL_003a: ldc.r4 3.14
IL_003f: beq.s IL_005a
IL_0041: ldloc.2
IL_0042: call ""bool float.IsNaN(float)""
IL_0047: brtrue.s IL_0050
IL_0049: br.s IL_005f
IL_004b: ldc.i4.1
IL_004c: stloc.s V_4
IL_004e: br.s IL_0064
IL_0050: ldc.i4.1
IL_0051: stloc.s V_4
IL_0053: br.s IL_0064
IL_0055: ldc.i4.1
IL_0056: stloc.s V_4
IL_0058: br.s IL_0064
IL_005a: ldc.i4.1
IL_005b: stloc.s V_4
IL_005d: br.s IL_0064
IL_005f: ldc.i4.0
IL_0060: stloc.s V_4
IL_0062: br.s IL_0064
IL_0064: ldloc.s V_4
IL_0066: ret
}");
}
[Fact]
public void DecimalEquality()
{
// demonstrate that pattern-matching against a decimal constant is
// at least as efficient as simply using ==
var source =
@"using System;
public class C
{
public static void Main()
{
Console.Write(M1(1.0m));
Console.Write(M2(1.0m));
Console.Write(M1(2.0m));
Console.Write(M2(2.0m));
}
static int M1(decimal d)
{
if (M(d) is 1.0m) return 1;
return 0;
}
static int M2(decimal d)
{
if (M(d) == 1.0m) return 1;
return 0;
}
public static decimal M(decimal d)
{
return d;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics();
var expectedOutput = @"1100";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("C.M1",
@"{
// Code size 37 (0x25)
.maxstack 6
.locals init (bool V_0,
int V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call ""decimal C.M(decimal)""
IL_0007: ldc.i4.s 10
IL_0009: ldc.i4.0
IL_000a: ldc.i4.0
IL_000b: ldc.i4.0
IL_000c: ldc.i4.1
IL_000d: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0012: call ""bool decimal.op_Equality(decimal, decimal)""
IL_0017: stloc.0
IL_0018: ldloc.0
IL_0019: brfalse.s IL_001f
IL_001b: ldc.i4.1
IL_001c: stloc.1
IL_001d: br.s IL_0023
IL_001f: ldc.i4.0
IL_0020: stloc.1
IL_0021: br.s IL_0023
IL_0023: ldloc.1
IL_0024: ret
}");
compVerifier.VerifyIL("C.M2",
@"{
// Code size 37 (0x25)
.maxstack 6
.locals init (bool V_0,
int V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call ""decimal C.M(decimal)""
IL_0007: ldc.i4.s 10
IL_0009: ldc.i4.0
IL_000a: ldc.i4.0
IL_000b: ldc.i4.0
IL_000c: ldc.i4.1
IL_000d: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0012: call ""bool decimal.op_Equality(decimal, decimal)""
IL_0017: stloc.0
IL_0018: ldloc.0
IL_0019: brfalse.s IL_001f
IL_001b: ldc.i4.1
IL_001c: stloc.1
IL_001d: br.s IL_0023
IL_001f: ldc.i4.0
IL_0020: stloc.1
IL_0021: br.s IL_0023
IL_0023: ldloc.1
IL_0024: ret
}");
compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("C.M1",
@"{
// Code size 28 (0x1c)
.maxstack 6
IL_0000: ldarg.0
IL_0001: call ""decimal C.M(decimal)""
IL_0006: ldc.i4.s 10
IL_0008: ldc.i4.0
IL_0009: ldc.i4.0
IL_000a: ldc.i4.0
IL_000b: ldc.i4.1
IL_000c: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0011: call ""bool decimal.op_Equality(decimal, decimal)""
IL_0016: brfalse.s IL_001a
IL_0018: ldc.i4.1
IL_0019: ret
IL_001a: ldc.i4.0
IL_001b: ret
}");
compVerifier.VerifyIL("C.M2",
@"{
// Code size 28 (0x1c)
.maxstack 6
IL_0000: ldarg.0
IL_0001: call ""decimal C.M(decimal)""
IL_0006: ldc.i4.s 10
IL_0008: ldc.i4.0
IL_0009: ldc.i4.0
IL_000a: ldc.i4.0
IL_000b: ldc.i4.1
IL_000c: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0011: call ""bool decimal.op_Equality(decimal, decimal)""
IL_0016: brfalse.s IL_001a
IL_0018: ldc.i4.1
IL_0019: ret
IL_001a: ldc.i4.0
IL_001b: ret
}");
}
[Fact, WorkItem(16878, "https://github.com/dotnet/roslyn/issues/16878")]
public void RedundantNullCheck()
{
var source =
@"public class C
{
static int M1(bool? b1, bool b2)
{
switch (b1)
{
case null:
return 1;
case var _ when b2:
return 2;
case true:
return 3;
case false:
return 4;
}
}
static int M2(object o, bool b)
{
switch (o)
{
case string a when b:
return 1;
case string a:
return 2;
}
return 3;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M1",
@"{
// Code size 35 (0x23)
.maxstack 1
.locals init (bool? V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool bool?.HasValue.get""
IL_0009: brfalse.s IL_0018
IL_000b: br.s IL_001a
IL_000d: ldloca.s V_0
IL_000f: call ""bool bool?.GetValueOrDefault()""
IL_0014: brtrue.s IL_001f
IL_0016: br.s IL_0021
IL_0018: ldc.i4.1
IL_0019: ret
IL_001a: ldarg.1
IL_001b: brfalse.s IL_000d
IL_001d: ldc.i4.2
IL_001e: ret
IL_001f: ldc.i4.3
IL_0020: ret
IL_0021: ldc.i4.4
IL_0022: ret
}");
compVerifier.VerifyIL("C.M2",
@"{
// Code size 19 (0x13)
.maxstack 1
.locals init (string V_0) //a
IL_0000: ldarg.0
IL_0001: isinst ""string""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0011
IL_000a: ldarg.1
IL_000b: brfalse.s IL_000f
IL_000d: ldc.i4.1
IL_000e: ret
IL_000f: ldc.i4.2
IL_0010: ret
IL_0011: ldc.i4.3
IL_0012: ret
}");
}
[Fact, WorkItem(12813, "https://github.com/dotnet/roslyn/issues/12813")]
public void NoBoxingOnIntegerConstantPattern()
{
var source =
@"public class C
{
static bool M1(int x)
{
return x is 42;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M1",
@"{
// Code size 6 (0x6)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 42
IL_0003: ceq
IL_0005: ret
}");
}
[Fact, WorkItem(40403, "https://github.com/dotnet/roslyn/issues/40403")]
public void RefParameter_StoreToTemp()
{
var source =
@"public class C
{
static bool M1(ref object x)
{
return x is 42;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M1",
@"{
// Code size 24 (0x18)
.maxstack 2
.locals init (object V_0)
IL_0000: ldarg.0
IL_0001: ldind.ref
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: isinst ""int""
IL_0009: brfalse.s IL_0016
IL_000b: ldloc.0
IL_000c: unbox.any ""int""
IL_0011: ldc.i4.s 42
IL_0013: ceq
IL_0015: ret
IL_0016: ldc.i4.0
IL_0017: ret
}");
}
[Fact, WorkItem(40403, "https://github.com/dotnet/roslyn/issues/40403")]
public void RefLocal_StoreToTemp()
{
var source =
@"public class C
{
static bool M1(bool b, ref object x, ref object y)
{
ref object z = ref b ? ref x : ref y;
return z is 42;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M1",
@"{
// Code size 30 (0x1e)
.maxstack 2
.locals init (object V_0)
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0006
IL_0003: ldarg.2
IL_0004: br.s IL_0007
IL_0006: ldarg.1
IL_0007: ldind.ref
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: isinst ""int""
IL_000f: brfalse.s IL_001c
IL_0011: ldloc.0
IL_0012: unbox.any ""int""
IL_0017: ldc.i4.s 42
IL_0019: ceq
IL_001b: ret
IL_001c: ldc.i4.0
IL_001d: ret
}");
}
[Fact, WorkItem(40403, "https://github.com/dotnet/roslyn/issues/40403")]
public void InParameter_StoreToTemp()
{
var source =
@"public class C
{
static bool M1(in object x)
{
return x is 42;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M1",
@"{
// Code size 24 (0x18)
.maxstack 2
.locals init (object V_0)
IL_0000: ldarg.0
IL_0001: ldind.ref
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: isinst ""int""
IL_0009: brfalse.s IL_0016
IL_000b: ldloc.0
IL_000c: unbox.any ""int""
IL_0011: ldc.i4.s 42
IL_0013: ceq
IL_0015: ret
IL_0016: ldc.i4.0
IL_0017: ret
}");
}
[Fact, WorkItem(40403, "https://github.com/dotnet/roslyn/issues/40403")]
public void RefReadonlyLocal_StoreToTemp()
{
var source =
@"public class C
{
static bool M1(bool b, in object x, in object y)
{
ref readonly object z = ref b ? ref x : ref y;
return z is 42;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M1",
@"{
// Code size 30 (0x1e)
.maxstack 2
.locals init (object V_0)
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0006
IL_0003: ldarg.2
IL_0004: br.s IL_0007
IL_0006: ldarg.1
IL_0007: ldind.ref
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: isinst ""int""
IL_000f: brfalse.s IL_001c
IL_0011: ldloc.0
IL_0012: unbox.any ""int""
IL_0017: ldc.i4.s 42
IL_0019: ceq
IL_001b: ret
IL_001c: ldc.i4.0
IL_001d: ret
}");
}
[Fact, WorkItem(40403, "https://github.com/dotnet/roslyn/issues/40403")]
public void OutParameter_StoreToTemp()
{
var source =
@"public class C
{
static bool M1(out object x)
{
x = null;
return x is 42;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M1",
@"{
// Code size 27 (0x1b)
.maxstack 2
.locals init (object V_0)
IL_0000: ldarg.0
IL_0001: ldnull
IL_0002: stind.ref
IL_0003: ldarg.0
IL_0004: ldind.ref
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: isinst ""int""
IL_000c: brfalse.s IL_0019
IL_000e: ldloc.0
IL_000f: unbox.any ""int""
IL_0014: ldc.i4.s 42
IL_0016: ceq
IL_0018: ret
IL_0019: ldc.i4.0
IL_001a: ret
}");
}
[Fact, WorkItem(22654, "https://github.com/dotnet/roslyn/issues/22654")]
public void NoRedundantTypeCheck()
{
var source =
@"using System;
public class C
{
public void SwitchBasedPatternMatching(object o)
{
switch (o)
{
case int n when n == 1:
Console.WriteLine(""1""); break;
case string s:
Console.WriteLine(""s""); break;
case int n when n == 2:
Console.WriteLine(""2""); break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.SwitchBasedPatternMatching",
@"{
// Code size 69 (0x45)
.maxstack 2
.locals init (int V_0, //n
object V_1)
IL_0000: ldarg.1
IL_0001: stloc.1
IL_0002: ldloc.1
IL_0003: isinst ""int""
IL_0008: brfalse.s IL_0013
IL_000a: ldloc.1
IL_000b: unbox.any ""int""
IL_0010: stloc.0
IL_0011: br.s IL_001c
IL_0013: ldloc.1
IL_0014: isinst ""string""
IL_0019: brtrue.s IL_002b
IL_001b: ret
IL_001c: ldloc.0
IL_001d: ldc.i4.1
IL_001e: bne.un.s IL_0036
IL_0020: ldstr ""1""
IL_0025: call ""void System.Console.WriteLine(string)""
IL_002a: ret
IL_002b: ldstr ""s""
IL_0030: call ""void System.Console.WriteLine(string)""
IL_0035: ret
IL_0036: ldloc.0
IL_0037: ldc.i4.2
IL_0038: bne.un.s IL_0044
IL_003a: ldstr ""2""
IL_003f: call ""void System.Console.WriteLine(string)""
IL_0044: ret
}");
}
[Fact, WorkItem(15437, "https://github.com/dotnet/roslyn/issues/15437")]
public void IsTypeDiscard()
{
var source =
@"public class C
{
public bool IsString(object o)
{
return o is string _;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.IsString",
@"{
// Code size 10 (0xa)
.maxstack 2
IL_0000: ldarg.1
IL_0001: isinst ""string""
IL_0006: ldnull
IL_0007: cgt.un
IL_0009: ret
}");
}
[Fact, WorkItem(19150, "https://github.com/dotnet/roslyn/issues/19150")]
public void RedundantHasValue()
{
var source =
@"using System;
public class C
{
public static void M(int? x)
{
switch (x)
{
case int i:
Console.Write(i);
break;
case null:
Console.Write(""null"");
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M",
@"{
// Code size 33 (0x21)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""bool int?.HasValue.get""
IL_0007: brfalse.s IL_0016
IL_0009: ldarga.s V_0
IL_000b: call ""int int?.GetValueOrDefault()""
IL_0010: call ""void System.Console.Write(int)""
IL_0015: ret
IL_0016: ldstr ""null""
IL_001b: call ""void System.Console.Write(string)""
IL_0020: ret
}");
}
[Fact, WorkItem(19153, "https://github.com/dotnet/roslyn/issues/19153")]
public void RedundantBox()
{
var source = @"using System;
public class C
{
public static void M<T, U>(U x) where T : U
{
// when T is not known to be a reference type, there is an unboxing conversion from
// a type parameter U to T, provided T depends on U.
switch (x)
{
case T i:
Console.Write(i);
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M<T, U>(U)",
@"{
// Code size 35 (0x23)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box ""U""
IL_0006: isinst ""T""
IL_000b: brfalse.s IL_0022
IL_000d: ldarg.0
IL_000e: box ""U""
IL_0013: unbox.any ""T""
IL_0018: box ""T""
IL_001d: call ""void System.Console.Write(object)""
IL_0022: ret
}");
}
[Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")]
public void NoRedundantPropertyRead01()
{
var source = @"using System;
public class Person {
public string Name { get; set; }
}
public class C {
public void M(Person p) {
switch (p) {
case { Name: ""Bill"" }:
Console.WriteLine(""Hey Bill!"");
break;
case { Name: ""Bob"" }:
Console.WriteLine(""Hey Bob!"");
break;
case { Name: var name }:
Console.WriteLine($""Hello {name}!"");
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M",
@"{
// Code size 82 (0x52)
.maxstack 3
.locals init (string V_0) //name
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0051
IL_0003: ldarg.1
IL_0004: callvirt ""string Person.Name.get""
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: ldstr ""Bill""
IL_0010: call ""bool string.op_Equality(string, string)""
IL_0015: brtrue.s IL_0026
IL_0017: ldloc.0
IL_0018: ldstr ""Bob""
IL_001d: call ""bool string.op_Equality(string, string)""
IL_0022: brtrue.s IL_0031
IL_0024: br.s IL_003c
IL_0026: ldstr ""Hey Bill!""
IL_002b: call ""void System.Console.WriteLine(string)""
IL_0030: ret
IL_0031: ldstr ""Hey Bob!""
IL_0036: call ""void System.Console.WriteLine(string)""
IL_003b: ret
IL_003c: ldstr ""Hello ""
IL_0041: ldloc.0
IL_0042: ldstr ""!""
IL_0047: call ""string string.Concat(string, string, string)""
IL_004c: call ""void System.Console.WriteLine(string)""
IL_0051: ret
}");
}
[Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")]
public void NoRedundantPropertyRead02()
{
var source = @"using System;
public class Person {
public string Name { get; set; }
public int Age;
}
public class C {
public void M(Person p) {
switch (p) {
case Person { Name: var name, Age: 0}:
Console.WriteLine($""Hello baby { name }!"");
break;
case Person { Name: var name }:
Console.WriteLine($""Hello { name }!"");
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M",
@"{
// Code size 64 (0x40)
.maxstack 3
.locals init (string V_0, //name
string V_1) //name
IL_0000: ldarg.1
IL_0001: brfalse.s IL_003f
IL_0003: ldarg.1
IL_0004: callvirt ""string Person.Name.get""
IL_0009: stloc.0
IL_000a: ldarg.1
IL_000b: ldfld ""int Person.Age""
IL_0010: brtrue.s IL_0028
IL_0012: ldstr ""Hello baby ""
IL_0017: ldloc.0
IL_0018: ldstr ""!""
IL_001d: call ""string string.Concat(string, string, string)""
IL_0022: call ""void System.Console.WriteLine(string)""
IL_0027: ret
IL_0028: ldloc.0
IL_0029: stloc.1
IL_002a: ldstr ""Hello ""
IL_002f: ldloc.1
IL_0030: ldstr ""!""
IL_0035: call ""string string.Concat(string, string, string)""
IL_003a: call ""void System.Console.WriteLine(string)""
IL_003f: ret
}");
}
[Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")]
public void NoRedundantPropertyRead03()
{
var source = @"using System;
public class Person {
public string Name { get; set; }
}
public class Student : Person { }
public class C {
public void M(Person p) {
switch (p) {
case { Name: ""Bill"" }:
Console.WriteLine(""Hey Bill!"");
break;
case Student { Name: var name }:
Console.WriteLine($""Hello student { name}!"");
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M",
@"{
// Code size 65 (0x41)
.maxstack 3
.locals init (string V_0) //name
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0040
IL_0003: ldarg.1
IL_0004: callvirt ""string Person.Name.get""
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: ldstr ""Bill""
IL_0010: call ""bool string.op_Equality(string, string)""
IL_0015: brtrue.s IL_0020
IL_0017: ldarg.1
IL_0018: isinst ""Student""
IL_001d: brtrue.s IL_002b
IL_001f: ret
IL_0020: ldstr ""Hey Bill!""
IL_0025: call ""void System.Console.WriteLine(string)""
IL_002a: ret
IL_002b: ldstr ""Hello student ""
IL_0030: ldloc.0
IL_0031: ldstr ""!""
IL_0036: call ""string string.Concat(string, string, string)""
IL_003b: call ""void System.Console.WriteLine(string)""
IL_0040: ret
}");
}
[Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")]
public void NoRedundantPropertyRead04()
{
// Cannot combine the evaluations of name here, since we first check if p is Teacher,
// and only if that fails check if p is null.
// Combining the evaluations would mean first checking if p is null, then evaluating name, then checking if p is Teacher.
// This would not necessarily be more performant.
var source = @"using System;
public class Person {
public string Name { get; set; }
}
public class Teacher : Person { }
public class C {
public void M(Person p) {
switch (p) {
case Teacher { Name: var name }:
Console.WriteLine($""Hello teacher { name}!"");
break;
case Person { Name: var name }:
Console.WriteLine($""Hello { name}!"");
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M",
@"{
// Code size 75 (0x4b)
.maxstack 3
.locals init (string V_0, //name
string V_1) //name
IL_0000: ldarg.1
IL_0001: isinst ""Teacher""
IL_0006: brfalse.s IL_0011
IL_0008: ldarg.1
IL_0009: callvirt ""string Person.Name.get""
IL_000e: stloc.0
IL_000f: br.s IL_001d
IL_0011: ldarg.1
IL_0012: brfalse.s IL_004a
IL_0014: ldarg.1
IL_0015: callvirt ""string Person.Name.get""
IL_001a: stloc.0
IL_001b: br.s IL_0033
IL_001d: ldstr ""Hello teacher ""
IL_0022: ldloc.0
IL_0023: ldstr ""!""
IL_0028: call ""string string.Concat(string, string, string)""
IL_002d: call ""void System.Console.WriteLine(string)""
IL_0032: ret
IL_0033: ldloc.0
IL_0034: stloc.1
IL_0035: ldstr ""Hello ""
IL_003a: ldloc.1
IL_003b: ldstr ""!""
IL_0040: call ""string string.Concat(string, string, string)""
IL_0045: call ""void System.Console.WriteLine(string)""
IL_004a: ret
}
");
}
[Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")]
public void NoRedundantPropertyRead05()
{
// Cannot combine the evaluations of name here, since we first check if p is Teacher,
// and only if that fails check if p is Student.
// Combining the evaluations would mean first checking if p is null,
// then evaluating name,
// then checking if p is Teacher,
// then checking if p is Student.
// This would not necessarily be more performant.
var source = @"using System;
public class Person {
public string Name { get; set; }
}
public class Student : Person { }
public class Teacher : Person { }
public class C {
public void M(Person p) {
switch (p) {
case Teacher { Name: var name }:
Console.WriteLine($""Hello teacher { name}!"");
break;
case Student { Name: var name }:
Console.WriteLine($""Hello student { name}!"");
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M",
@"{
// Code size 80 (0x50)
.maxstack 3
.locals init (string V_0, //name
string V_1) //name
IL_0000: ldarg.1
IL_0001: isinst ""Teacher""
IL_0006: brfalse.s IL_0011
IL_0008: ldarg.1
IL_0009: callvirt ""string Person.Name.get""
IL_000e: stloc.0
IL_000f: br.s IL_0022
IL_0011: ldarg.1
IL_0012: isinst ""Student""
IL_0017: brfalse.s IL_004f
IL_0019: ldarg.1
IL_001a: callvirt ""string Person.Name.get""
IL_001f: stloc.0
IL_0020: br.s IL_0038
IL_0022: ldstr ""Hello teacher ""
IL_0027: ldloc.0
IL_0028: ldstr ""!""
IL_002d: call ""string string.Concat(string, string, string)""
IL_0032: call ""void System.Console.WriteLine(string)""
IL_0037: ret
IL_0038: ldloc.0
IL_0039: stloc.1
IL_003a: ldstr ""Hello student ""
IL_003f: ldloc.1
IL_0040: ldstr ""!""
IL_0045: call ""string string.Concat(string, string, string)""
IL_004a: call ""void System.Console.WriteLine(string)""
IL_004f: ret
}
");
}
[Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")]
public void NoRedundantPropertyRead06()
{
var source = @"using System;
public class Person {
public string Name { get; set; }
}
public class Student : Person { }
public class C {
public void M(Person p) {
switch (p) {
case { Name: { Length: 0 } }:
Console.WriteLine(""Hello!"");
break;
case Student { Name: { Length : 1 } }:
Console.WriteLine($""Hello student!"");
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M",
@"{
// Code size 58 (0x3a)
.maxstack 2
.locals init (string V_0,
int V_1)
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0039
IL_0003: ldarg.1
IL_0004: callvirt ""string Person.Name.get""
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_0039
IL_000d: ldloc.0
IL_000e: callvirt ""int string.Length.get""
IL_0013: stloc.1
IL_0014: ldloc.1
IL_0015: brfalse.s IL_0024
IL_0017: ldarg.1
IL_0018: isinst ""Student""
IL_001d: brfalse.s IL_0039
IL_001f: ldloc.1
IL_0020: ldc.i4.1
IL_0021: beq.s IL_002f
IL_0023: ret
IL_0024: ldstr ""Hello!""
IL_0029: call ""void System.Console.WriteLine(string)""
IL_002e: ret
IL_002f: ldstr ""Hello student!""
IL_0034: call ""void System.Console.WriteLine(string)""
IL_0039: ret
}");
}
[Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")]
public void NoRedundantPropertyRead07()
{
// Cannot combine the evaluations of name here, since we first check if name is MemoryStream,
// and only if that fails check if name is null.
// Combining the evaluations would mean first checking if name is null, then evaluating name, then checking if p is Teacher.
// This would not necessarily be more performant.
var source = @"using System;
using System.IO;
public class Person {
public Stream Name { get; set; }
}
public class C {
public void M(Person p) {
switch (p) {
case Person { Name: MemoryStream { Length: 1 } }:
Console.WriteLine(""Your Names A MemoryStream!"");
break;
case Person { Name: { Length : var x } }:
Console.WriteLine(""Your Names A Stream!"");
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M",
@"{
// Code size 66 (0x42)
.maxstack 2
.locals init (System.IO.Stream V_0,
System.IO.MemoryStream V_1)
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0041
IL_0003: ldarg.1
IL_0004: callvirt ""System.IO.Stream Person.Name.get""
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: isinst ""System.IO.MemoryStream""
IL_0010: stloc.1
IL_0011: ldloc.1
IL_0012: brfalse.s IL_0020
IL_0014: ldloc.1
IL_0015: callvirt ""long System.IO.Stream.Length.get""
IL_001a: ldc.i4.1
IL_001b: conv.i8
IL_001c: beq.s IL_002c
IL_001e: br.s IL_0023
IL_0020: ldloc.0
IL_0021: brfalse.s IL_0041
IL_0023: ldloc.0
IL_0024: callvirt ""long System.IO.Stream.Length.get""
IL_0029: pop
IL_002a: br.s IL_0037
IL_002c: ldstr ""Your Names A MemoryStream!""
IL_0031: call ""void System.Console.WriteLine(string)""
IL_0036: ret
IL_0037: ldstr ""Your Names A Stream!""
IL_003c: call ""void System.Console.WriteLine(string)""
IL_0041: ret
}");
}
[Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")]
public void NoRedundantPropertyRead08()
{
var source = @"
public class Person {
public string Name { get; set; }
}
public class Student : Person { }
public class C {
public string M(Person p) {
return p switch {
{ Name: ""Bill"" } => ""Hey Bill!"",
Student { Name: var name } => ""Hello student { name}!"",
_ => null,
};
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M",
@"{
// Code size 51 (0x33)
.maxstack 2
.locals init (string V_0)
IL_0000: ldarg.1
IL_0001: brfalse.s IL_002f
IL_0003: ldarg.1
IL_0004: callvirt ""string Person.Name.get""
IL_0009: ldstr ""Bill""
IL_000e: call ""bool string.op_Equality(string, string)""
IL_0013: brtrue.s IL_001f
IL_0015: ldarg.1
IL_0016: isinst ""Student""
IL_001b: brtrue.s IL_0027
IL_001d: br.s IL_002f
IL_001f: ldstr ""Hey Bill!""
IL_0024: stloc.0
IL_0025: br.s IL_0031
IL_0027: ldstr ""Hello student { name}!""
IL_002c: stloc.0
IL_002d: br.s IL_0031
IL_002f: ldnull
IL_0030: stloc.0
IL_0031: ldloc.0
IL_0032: ret
}");
}
[Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")]
public void NoRedundantPropertyRead09()
{
var source = @"using System;
public class Person {
public virtual string Name { get; set; }
}
public class Student : Person { }
public class C {
public void M(Person p) {
switch (p) {
case { Name: ""Bill"" }:
Console.WriteLine(""Hey Bill!"");
break;
case Student { Name: var name }:
Console.WriteLine($""Hello student { name}!"");
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M",
@"{
// Code size 65 (0x41)
.maxstack 3
.locals init (string V_0) //name
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0040
IL_0003: ldarg.1
IL_0004: callvirt ""string Person.Name.get""
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: ldstr ""Bill""
IL_0010: call ""bool string.op_Equality(string, string)""
IL_0015: brtrue.s IL_0020
IL_0017: ldarg.1
IL_0018: isinst ""Student""
IL_001d: brtrue.s IL_002b
IL_001f: ret
IL_0020: ldstr ""Hey Bill!""
IL_0025: call ""void System.Console.WriteLine(string)""
IL_002a: ret
IL_002b: ldstr ""Hello student ""
IL_0030: ldloc.0
IL_0031: ldstr ""!""
IL_0036: call ""string string.Concat(string, string, string)""
IL_003b: call ""void System.Console.WriteLine(string)""
IL_0040: ret
}");
}
[Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")]
public void NoRedundantPropertyRead10()
{
// Currently we don't combine these redundant property reads.
// However we could do so in the future.
var source = @"using System;
public abstract class Person {
public abstract string Name { get; set; }
}
public class Student : Person {
public override string Name { get; set; }
}
public class C {
public void M(Person p) {
switch (p) {
case { Name: ""Bill"" }:
Console.WriteLine(""Hey Bill!"");
break;
case Student { Name: var name }:
Console.WriteLine($""Hello student { name}!"");
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M",
@"{
// Code size 73 (0x49)
.maxstack 3
.locals init (string V_0, //name
Student V_1)
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0048
IL_0003: ldarg.1
IL_0004: callvirt ""string Person.Name.get""
IL_0009: ldstr ""Bill""
IL_000e: call ""bool string.op_Equality(string, string)""
IL_0013: brtrue.s IL_0028
IL_0015: ldarg.1
IL_0016: isinst ""Student""
IL_001b: stloc.1
IL_001c: ldloc.1
IL_001d: brfalse.s IL_0048
IL_001f: ldloc.1
IL_0020: callvirt ""string Person.Name.get""
IL_0025: stloc.0
IL_0026: br.s IL_0033
IL_0028: ldstr ""Hey Bill!""
IL_002d: call ""void System.Console.WriteLine(string)""
IL_0032: ret
IL_0033: ldstr ""Hello student ""
IL_0038: ldloc.0
IL_0039: ldstr ""!""
IL_003e: call ""string string.Concat(string, string, string)""
IL_0043: call ""void System.Console.WriteLine(string)""
IL_0048: ret
}");
}
[Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")]
public void CombiningRedundantPropertyReadsDoesNotChangeNullabilityAnalysis01()
{
// Currently we don't combine the redundant property reads at all.
// However this could be improved in the future so this test is important
var source = @"using System;
#nullable enable
public class Person {
public virtual string? Name { get; }
}
public class Student : Person {
public override string Name { get => base.Name ?? """"; }
}
public class C {
public void M(Person p) {
switch (p) {
case { Name: ""Bill""}:
Console.WriteLine(""Hey Bill!"");
break;
case Student { Name: var name }:
Console.WriteLine($""Student has name of length { name.Length }!"");
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M",
@"{
// Code size 78 (0x4e)
.maxstack 2
.locals init (string V_0, //name
Student V_1)
IL_0000: ldarg.1
IL_0001: brfalse.s IL_004d
IL_0003: ldarg.1
IL_0004: callvirt ""string Person.Name.get""
IL_0009: ldstr ""Bill""
IL_000e: call ""bool string.op_Equality(string, string)""
IL_0013: brtrue.s IL_0028
IL_0015: ldarg.1
IL_0016: isinst ""Student""
IL_001b: stloc.1
IL_001c: ldloc.1
IL_001d: brfalse.s IL_004d
IL_001f: ldloc.1
IL_0020: callvirt ""string Person.Name.get""
IL_0025: stloc.0
IL_0026: br.s IL_0033
IL_0028: ldstr ""Hey Bill!""
IL_002d: call ""void System.Console.WriteLine(string)""
IL_0032: ret
IL_0033: ldstr ""Student has name of length {0}!""
IL_0038: ldloc.0
IL_0039: callvirt ""int string.Length.get""
IL_003e: box ""int""
IL_0043: call ""string string.Format(string, object)""
IL_0048: call ""void System.Console.WriteLine(string)""
IL_004d: ret
}");
}
[Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")]
public void CombiningRedundantPropertyReadsDoesNotChangeNullabilityAnalysis02()
{
var source = @"using System;
#nullable enable
public class Person {
public string? Name { get;}
}
public class Student : Person {
}
public class C {
public void M(Person p) {
switch (p) {
case { Name: var name } when name is null:
Console.WriteLine($""Hey { name }"");
break;
case Student { Name: var name } when name != null:
Console.WriteLine($""Student has name of length { name.Length }!"");
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M",
@"{
// Code size 75 (0x4b)
.maxstack 2
.locals init (string V_0, //name
string V_1, //name
Person V_2)
IL_0000: ldarg.1
IL_0001: stloc.2
IL_0002: ldloc.2
IL_0003: brfalse.s IL_004a
IL_0005: ldloc.2
IL_0006: callvirt ""string Person.Name.get""
IL_000b: stloc.0
IL_000c: br.s IL_0017
IL_000e: ldloc.2
IL_000f: isinst ""Student""
IL_0014: brtrue.s IL_002b
IL_0016: ret
IL_0017: ldloc.0
IL_0018: brtrue.s IL_000e
IL_001a: ldstr ""Hey ""
IL_001f: ldloc.0
IL_0020: call ""string string.Concat(string, string)""
IL_0025: call ""void System.Console.WriteLine(string)""
IL_002a: ret
IL_002b: ldloc.0
IL_002c: stloc.1
IL_002d: ldloc.1
IL_002e: brfalse.s IL_004a
IL_0030: ldstr ""Student has name of length {0}!""
IL_0035: ldloc.1
IL_0036: callvirt ""int string.Length.get""
IL_003b: box ""int""
IL_0040: call ""string string.Format(string, object)""
IL_0045: call ""void System.Console.WriteLine(string)""
IL_004a: ret
}");
}
[Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")]
public void CombiningRedundantPropertyReadsDoesNotChangeNullabilityAnalysis03()
{
var source = @"using System;
#nullable enable
public class Person {
public string? Name { get; }
}
public class Student : Person {
}
public class C {
public void M(Person p) {
switch (p) {
case { Name: string name }:
Console.WriteLine($""Hey {name}"");
break;
case Student { Name: var name }:
Console.WriteLine($""Student has name of length { name.Length }!"");
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics(
// (19,66): warning CS8602: Dereference of a possibly null reference.
// Console.WriteLine($"Student has name of length { name.Length }!");
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "name").WithLocation(19, 66));
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M",
@"{
// Code size 68 (0x44)
.maxstack 2
.locals init (string V_0, //name
string V_1) //name
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0043
IL_0003: ldarg.1
IL_0004: callvirt ""string Person.Name.get""
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brtrue.s IL_0016
IL_000d: ldarg.1
IL_000e: isinst ""Student""
IL_0013: brtrue.s IL_0027
IL_0015: ret
IL_0016: ldstr ""Hey ""
IL_001b: ldloc.0
IL_001c: call ""string string.Concat(string, string)""
IL_0021: call ""void System.Console.WriteLine(string)""
IL_0026: ret
IL_0027: ldloc.0
IL_0028: stloc.1
IL_0029: ldstr ""Student has name of length {0}!""
IL_002e: ldloc.1
IL_002f: callvirt ""int string.Length.get""
IL_0034: box ""int""
IL_0039: call ""string string.Format(string, object)""
IL_003e: call ""void System.Console.WriteLine(string)""
IL_0043: ret
}");
}
[Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")]
public void DoNotCombineDifferentPropertyReadsWithSameName()
{
var source = @"using System;
public class Person {
public string Name { get; set; }
}
public class Student : Person {
public new string Name { get; set; }
}
public class C {
public void M(Person p) {
switch (p) {
case { Name: ""Bill"" }:
Console.WriteLine(""Hey Bill!"");
break;
case Student { Name: var name }:
Console.WriteLine($""Hello student { name}!"");
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M",
@"{
// Code size 73 (0x49)
.maxstack 3
.locals init (string V_0, //name
Student V_1)
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0048
IL_0003: ldarg.1
IL_0004: callvirt ""string Person.Name.get""
IL_0009: ldstr ""Bill""
IL_000e: call ""bool string.op_Equality(string, string)""
IL_0013: brtrue.s IL_0028
IL_0015: ldarg.1
IL_0016: isinst ""Student""
IL_001b: stloc.1
IL_001c: ldloc.1
IL_001d: brfalse.s IL_0048
IL_001f: ldloc.1
IL_0020: callvirt ""string Student.Name.get""
IL_0025: stloc.0
IL_0026: br.s IL_0033
IL_0028: ldstr ""Hey Bill!""
IL_002d: call ""void System.Console.WriteLine(string)""
IL_0032: ret
IL_0033: ldstr ""Hello student ""
IL_0038: ldloc.0
IL_0039: ldstr ""!""
IL_003e: call ""string string.Concat(string, string, string)""
IL_0043: call ""void System.Console.WriteLine(string)""
IL_0048: ret
}");
}
[Fact, WorkItem(20641, "https://github.com/dotnet/roslyn/issues/20641")]
public void PatternsVsAs01()
{
var source = @"using System.Collections;
using System.Collections.Generic;
class Program
{
static void Main() { }
internal static bool TryGetCount1<T>(IEnumerable<T> source, out int count)
{
ICollection nonGeneric = source as ICollection;
if (nonGeneric != null)
{
count = nonGeneric.Count;
return true;
}
ICollection<T> generic = source as ICollection<T>;
if (generic != null)
{
count = generic.Count;
return true;
}
count = -1;
return false;
}
internal static bool TryGetCount2<T>(IEnumerable<T> source, out int count)
{
switch (source)
{
case ICollection nonGeneric:
count = nonGeneric.Count;
return true;
case ICollection<T> generic:
count = generic.Count;
return true;
default:
count = -1;
return false;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("Program.TryGetCount1<T>",
@"{
// Code size 45 (0x2d)
.maxstack 2
.locals init (System.Collections.ICollection V_0, //nonGeneric
System.Collections.Generic.ICollection<T> V_1) //generic
IL_0000: ldarg.0
IL_0001: isinst ""System.Collections.ICollection""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0014
IL_000a: ldarg.1
IL_000b: ldloc.0
IL_000c: callvirt ""int System.Collections.ICollection.Count.get""
IL_0011: stind.i4
IL_0012: ldc.i4.1
IL_0013: ret
IL_0014: ldarg.0
IL_0015: isinst ""System.Collections.Generic.ICollection<T>""
IL_001a: stloc.1
IL_001b: ldloc.1
IL_001c: brfalse.s IL_0028
IL_001e: ldarg.1
IL_001f: ldloc.1
IL_0020: callvirt ""int System.Collections.Generic.ICollection<T>.Count.get""
IL_0025: stind.i4
IL_0026: ldc.i4.1
IL_0027: ret
IL_0028: ldarg.1
IL_0029: ldc.i4.m1
IL_002a: stind.i4
IL_002b: ldc.i4.0
IL_002c: ret
}");
compVerifier.VerifyIL("Program.TryGetCount2<T>",
@"{
// Code size 47 (0x2f)
.maxstack 2
.locals init (System.Collections.ICollection V_0, //nonGeneric
System.Collections.Generic.ICollection<T> V_1) //generic
IL_0000: ldarg.0
IL_0001: isinst ""System.Collections.ICollection""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brtrue.s IL_0016
IL_000a: ldarg.0
IL_000b: isinst ""System.Collections.Generic.ICollection<T>""
IL_0010: stloc.1
IL_0011: ldloc.1
IL_0012: brtrue.s IL_0020
IL_0014: br.s IL_002a
IL_0016: ldarg.1
IL_0017: ldloc.0
IL_0018: callvirt ""int System.Collections.ICollection.Count.get""
IL_001d: stind.i4
IL_001e: ldc.i4.1
IL_001f: ret
IL_0020: ldarg.1
IL_0021: ldloc.1
IL_0022: callvirt ""int System.Collections.Generic.ICollection<T>.Count.get""
IL_0027: stind.i4
IL_0028: ldc.i4.1
IL_0029: ret
IL_002a: ldarg.1
IL_002b: ldc.i4.m1
IL_002c: stind.i4
IL_002d: ldc.i4.0
IL_002e: ret
}");
}
[Fact, WorkItem(20641, "https://github.com/dotnet/roslyn/issues/20641")]
public void PatternsVsAs02()
{
var source = @"using System.Collections;
class Program
{
static void Main() { }
internal static bool IsEmpty1(IEnumerable source)
{
var c = source as ICollection;
return c != null && c.Count > 0;
}
internal static bool IsEmpty2(IEnumerable source)
{
return source is ICollection c && c.Count > 0;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("Program.IsEmpty1",
@"{
// Code size 22 (0x16)
.maxstack 2
.locals init (System.Collections.ICollection V_0) //c
IL_0000: ldarg.0
IL_0001: isinst ""System.Collections.ICollection""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0014
IL_000a: ldloc.0
IL_000b: callvirt ""int System.Collections.ICollection.Count.get""
IL_0010: ldc.i4.0
IL_0011: cgt
IL_0013: ret
IL_0014: ldc.i4.0
IL_0015: ret
}");
compVerifier.VerifyIL("Program.IsEmpty2",
@"{
// Code size 22 (0x16)
.maxstack 2
.locals init (System.Collections.ICollection V_0) //c
IL_0000: ldarg.0
IL_0001: isinst ""System.Collections.ICollection""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0014
IL_000a: ldloc.0
IL_000b: callvirt ""int System.Collections.ICollection.Count.get""
IL_0010: ldc.i4.0
IL_0011: cgt
IL_0013: ret
IL_0014: ldc.i4.0
IL_0015: ret
}");
}
[Fact]
[WorkItem(20641, "https://github.com/dotnet/roslyn/issues/20641")]
[WorkItem(1395, "https://github.com/dotnet/csharplang/issues/1395")]
public void TupleSwitch01()
{
var source = @"using System;
public class Door
{
public DoorState State;
public enum DoorState { Opened, Closed, Locked }
public enum Action { Open, Close, Lock, Unlock }
public void Act0(Action action, bool haveKey = false)
{
Console.Write($""{State} {action}{(haveKey ? "" withKey"" : null)}"");
State = ChangeState0(State, action, haveKey);
Console.WriteLine($"" -> {State}"");
}
public void Act1(Action action, bool haveKey = false)
{
Console.Write($""{State} {action}{(haveKey ? "" withKey"" : null)}"");
State = ChangeState1(State, action, haveKey);
Console.WriteLine($"" -> {State}"");
}
public static DoorState ChangeState0(DoorState state, Action action, bool haveKey = false)
{
switch (state, action)
{
case (DoorState.Opened, Action.Close):
return DoorState.Closed;
case (DoorState.Closed, Action.Open):
return DoorState.Opened;
case (DoorState.Closed, Action.Lock) when haveKey:
return DoorState.Locked;
case (DoorState.Locked, Action.Unlock) when haveKey:
return DoorState.Closed;
case var (oldState, _):
return oldState;
}
}
public static DoorState ChangeState1(DoorState state, Action action, bool haveKey = false) =>
(state, action) switch {
(DoorState.Opened, Action.Close) => DoorState.Closed,
(DoorState.Closed, Action.Open) => DoorState.Opened,
(DoorState.Closed, Action.Lock) when haveKey => DoorState.Locked,
(DoorState.Locked, Action.Unlock) when haveKey => DoorState.Closed,
_ => state };
}
class Program
{
static void Main(string[] args)
{
var door = new Door();
door.Act0(Door.Action.Close);
door.Act0(Door.Action.Lock);
door.Act0(Door.Action.Lock, true);
door.Act0(Door.Action.Open);
door.Act0(Door.Action.Unlock);
door.Act0(Door.Action.Unlock, true);
door.Act0(Door.Action.Open);
Console.WriteLine();
door = new Door();
door.Act1(Door.Action.Close);
door.Act1(Door.Action.Lock);
door.Act1(Door.Action.Lock, true);
door.Act1(Door.Action.Open);
door.Act1(Door.Action.Unlock);
door.Act1(Door.Action.Unlock, true);
door.Act1(Door.Action.Open);
}
}";
var expectedOutput =
@"Opened Close -> Closed
Closed Lock -> Closed
Closed Lock withKey -> Locked
Locked Open -> Locked
Locked Unlock -> Locked
Locked Unlock withKey -> Closed
Closed Open -> Opened
Opened Close -> Closed
Closed Lock -> Closed
Closed Lock withKey -> Locked
Locked Open -> Locked
Locked Unlock -> Locked
Locked Unlock withKey -> Closed
Closed Open -> Opened
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.RegularWithRecursivePatterns);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("Door.ChangeState0",
@"{
// Code size 61 (0x3d)
.maxstack 2
.locals init (Door.DoorState V_0, //oldState
Door.Action V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldarg.1
IL_0003: stloc.1
IL_0004: ldloc.0
IL_0005: switch (
IL_0018,
IL_001e,
IL_0027)
IL_0016: br.s IL_003b
IL_0018: ldloc.1
IL_0019: ldc.i4.1
IL_001a: beq.s IL_002d
IL_001c: br.s IL_003b
IL_001e: ldloc.1
IL_001f: brfalse.s IL_002f
IL_0021: ldloc.1
IL_0022: ldc.i4.2
IL_0023: beq.s IL_0031
IL_0025: br.s IL_003b
IL_0027: ldloc.1
IL_0028: ldc.i4.3
IL_0029: beq.s IL_0036
IL_002b: br.s IL_003b
IL_002d: ldc.i4.1
IL_002e: ret
IL_002f: ldc.i4.0
IL_0030: ret
IL_0031: ldarg.2
IL_0032: brfalse.s IL_003b
IL_0034: ldc.i4.2
IL_0035: ret
IL_0036: ldarg.2
IL_0037: brfalse.s IL_003b
IL_0039: ldc.i4.1
IL_003a: ret
IL_003b: ldloc.0
IL_003c: ret
}");
compVerifier.VerifyIL("Door.ChangeState1",
@"{
// Code size 71 (0x47)
.maxstack 2
.locals init (Door.DoorState V_0,
Door.DoorState V_1,
Door.Action V_2)
IL_0000: ldarg.0
IL_0001: stloc.1
IL_0002: ldarg.1
IL_0003: stloc.2
IL_0004: ldloc.1
IL_0005: switch (
IL_0018,
IL_001e,
IL_0027)
IL_0016: br.s IL_0043
IL_0018: ldloc.2
IL_0019: ldc.i4.1
IL_001a: beq.s IL_002d
IL_001c: br.s IL_0043
IL_001e: ldloc.2
IL_001f: brfalse.s IL_0031
IL_0021: ldloc.2
IL_0022: ldc.i4.2
IL_0023: beq.s IL_0035
IL_0025: br.s IL_0043
IL_0027: ldloc.2
IL_0028: ldc.i4.3
IL_0029: beq.s IL_003c
IL_002b: br.s IL_0043
IL_002d: ldc.i4.1
IL_002e: stloc.0
IL_002f: br.s IL_0045
IL_0031: ldc.i4.0
IL_0032: stloc.0
IL_0033: br.s IL_0045
IL_0035: ldarg.2
IL_0036: brfalse.s IL_0043
IL_0038: ldc.i4.2
IL_0039: stloc.0
IL_003a: br.s IL_0045
IL_003c: ldarg.2
IL_003d: brfalse.s IL_0043
IL_003f: ldc.i4.1
IL_0040: stloc.0
IL_0041: br.s IL_0045
IL_0043: ldarg.0
IL_0044: stloc.0
IL_0045: ldloc.0
IL_0046: ret
}");
}
[Fact]
[WorkItem(20641, "https://github.com/dotnet/roslyn/issues/20641")]
[WorkItem(1395, "https://github.com/dotnet/csharplang/issues/1395")]
public void SharingTemps01()
{
var source =
@"class Program
{
static void Main(string[] args) { }
void M1(string x)
{
switch (x)
{
case ""a"":
case ""b"" when Mutate(ref x): // prevents sharing temps
case ""c"":
break;
}
}
void M2(string x)
{
switch (x)
{
case ""a"":
case ""b"" when Pure(x):
case ""c"":
break;
}
}
static bool Mutate(ref string x) { x = null; return false; }
static bool Pure(string x) { return false; }
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.RegularWithoutRecursivePatterns);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("Program.M1",
@"{
// Code size 50 (0x32)
.maxstack 2
.locals init (string V_0)
IL_0000: ldarg.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldstr ""a""
IL_0008: call ""bool string.op_Equality(string, string)""
IL_000d: brtrue.s IL_0031
IL_000f: ldloc.0
IL_0010: ldstr ""b""
IL_0015: call ""bool string.op_Equality(string, string)""
IL_001a: brtrue.s IL_0029
IL_001c: ldloc.0
IL_001d: ldstr ""c""
IL_0022: call ""bool string.op_Equality(string, string)""
IL_0027: pop
IL_0028: ret
IL_0029: ldarga.s V_1
IL_002b: call ""bool Program.Mutate(ref string)""
IL_0030: pop
IL_0031: ret
}");
compVerifier.VerifyIL("Program.M2",
@"{
// Code size 49 (0x31)
.maxstack 2
.locals init (string V_0)
IL_0000: ldarg.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldstr ""a""
IL_0008: call ""bool string.op_Equality(string, string)""
IL_000d: brtrue.s IL_0030
IL_000f: ldloc.0
IL_0010: ldstr ""b""
IL_0015: call ""bool string.op_Equality(string, string)""
IL_001a: brtrue.s IL_0029
IL_001c: ldloc.0
IL_001d: ldstr ""c""
IL_0022: call ""bool string.op_Equality(string, string)""
IL_0027: pop
IL_0028: ret
IL_0029: ldarg.1
IL_002a: call ""bool Program.Pure(string)""
IL_002f: pop
IL_0030: ret
}");
}
[Fact, WorkItem(17266, "https://github.com/dotnet/roslyn/issues/17266")]
public void IrrefutablePatternInIs01()
{
var source =
@"using System;
public class C
{
public static void Main()
{
if (Get() is int index) { }
Console.WriteLine(index);
}
public static int Get()
{
Console.WriteLine(""eval"");
return 1;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics();
var expectedOutput = @"eval
1";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact, WorkItem(17266, "https://github.com/dotnet/roslyn/issues/17266")]
public void IrrefutablePatternInIs02()
{
var source =
@"using System;
public class C
{
public static void Main()
{
if (Get() is Assignment(int left, var right)) { }
Console.WriteLine(left);
Console.WriteLine(right);
}
public static Assignment Get()
{
Console.WriteLine(""eval"");
return new Assignment(1, 2);
}
}
public struct Assignment
{
public int Left, Right;
public Assignment(int left, int right) => (Left, Right) = (left, right);
public void Deconstruct(out int left, out int right) => (left, right) = (Left, Right);
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithRecursivePatterns);
compilation.VerifyDiagnostics();
var expectedOutput = @"eval
1
2";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void MissingNullCheck01()
{
var source =
@"class Program
{
public static void Main()
{
string s = null;
System.Console.WriteLine(s is string { Length: 3 });
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithRecursivePatterns);
compilation.VerifyDiagnostics();
var expectedOutput = @"False";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
[WorkItem(24550, "https://github.com/dotnet/roslyn/issues/24550")]
[WorkItem(1284, "https://github.com/dotnet/csharplang/issues/1284")]
public void ConstantPatternVsUnconstrainedTypeParameter01()
{
var source =
@"using System;
class Program
{
static void Main()
{
Console.WriteLine(Test1<object>(null));
Console.WriteLine(Test1<int>(1));
Console.WriteLine(Test1<int?>(null));
Console.WriteLine(Test1<int?>(1));
Console.WriteLine(Test2<object>(0));
Console.WriteLine(Test2<int>(1));
Console.WriteLine(Test2<int?>(0));
Console.WriteLine(Test2<string>(""frog""));
Console.WriteLine(Test3<object>(""frog""));
Console.WriteLine(Test3<int>(1));
Console.WriteLine(Test3<string>(""frog""));
Console.WriteLine(Test3<int?>(1));
}
public static bool Test1<T>(T t)
{
return t is null;
}
public static bool Test2<T>(T t)
{
return t is 0;
}
public static bool Test3<T>(T t)
{
return t is ""frog"";
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
var expectedOutput =
@"True
False
True
False
True
False
True
False
True
False
True
False
";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("Program.Test1<T>(T)",
@"{
// Code size 10 (0xa)
.maxstack 2
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: ldnull
IL_0007: ceq
IL_0009: ret
}");
compVerifier.VerifyIL("Program.Test2<T>(T)",
@"{
// Code size 35 (0x23)
.maxstack 2
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: isinst ""int""
IL_000b: brfalse.s IL_0021
IL_000d: ldarg.0
IL_000e: box ""T""
IL_0013: isinst ""int""
IL_0018: unbox.any ""int""
IL_001d: ldc.i4.0
IL_001e: ceq
IL_0020: ret
IL_0021: ldc.i4.0
IL_0022: ret
}
");
compVerifier.VerifyIL("Program.Test3<T>(T)",
@"{
// Code size 29 (0x1d)
.maxstack 2
.locals init (string V_0)
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: isinst ""string""
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: brfalse.s IL_001b
IL_000f: ldloc.0
IL_0010: ldstr ""frog""
IL_0015: call ""bool string.op_Equality(string, string)""
IL_001a: ret
IL_001b: ldc.i4.0
IL_001c: ret
}");
}
[Fact]
[WorkItem(24550, "https://github.com/dotnet/roslyn/issues/24550")]
[WorkItem(1284, "https://github.com/dotnet/csharplang/issues/1284")]
public void ConstantPatternVsUnconstrainedTypeParameter02()
{
var source =
@"class C<T>
{
internal struct S { }
static bool Test(S s)
{
return s is 1;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C<T>.Test(C<T>.S)",
@"{
// Code size 35 (0x23)
.maxstack 2
IL_0000: ldarg.0
IL_0001: box ""C<T>.S""
IL_0006: isinst ""int""
IL_000b: brfalse.s IL_0021
IL_000d: ldarg.0
IL_000e: box ""C<T>.S""
IL_0013: isinst ""int""
IL_0018: unbox.any ""int""
IL_001d: ldc.i4.1
IL_001e: ceq
IL_0020: ret
IL_0021: ldc.i4.0
IL_0022: ret
}
");
}
[Fact]
[WorkItem(26274, "https://github.com/dotnet/roslyn/issues/26274")]
public void VariablesInSwitchExpressionArms()
{
var source =
@"class C
{
public override bool Equals(object obj) =>
obj switch
{
C x1 when x1 is var x2 => x2 is var x3 && x3 is {},
_ => false
};
public override int GetHashCode() => 1;
public static void Main()
{
C c = new C();
System.Console.Write(c.Equals(new C()));
System.Console.Write(c.Equals(new object()));
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation, expectedOutput: "TrueFalse");
compVerifier.VerifyIL("C.Equals(object)",
@"{
// Code size 25 (0x19)
.maxstack 2
.locals init (C V_0, //x1
C V_1, //x2
C V_2, //x3
bool V_3)
IL_0000: ldarg.1
IL_0001: isinst ""C""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0015
IL_000a: ldloc.0
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: stloc.2
IL_000e: ldloc.2
IL_000f: ldnull
IL_0010: cgt.un
IL_0012: stloc.3
IL_0013: br.s IL_0017
IL_0015: ldc.i4.0
IL_0016: stloc.3
IL_0017: ldloc.3
IL_0018: ret
}");
}
[Fact, WorkItem(26387, "https://github.com/dotnet/roslyn/issues/26387")]
public void ValueTypeArgument01()
{
var source =
@"using System;
class TestHelper
{
static void Main()
{
Console.WriteLine(IsValueTypeT0(new S()));
Console.WriteLine(IsValueTypeT1(new S()));
Console.WriteLine(IsValueTypeT2(new S()));
}
static bool IsValueTypeT0<T>(T result)
{
return result is T;
}
static bool IsValueTypeT1<T>(T result)
{
return result is T v;
}
static bool IsValueTypeT2<T>(T result)
{
return result is T _;
}
}
struct S { }
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics();
var expectedOutput =
@"True
True
True";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("TestHelper.IsValueTypeT0<T>(T)",
@"{
// Code size 15 (0xf)
.maxstack 2
.locals init (bool V_0)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: box ""T""
IL_0007: ldnull
IL_0008: cgt.un
IL_000a: stloc.0
IL_000b: br.s IL_000d
IL_000d: ldloc.0
IL_000e: ret
}");
compVerifier.VerifyIL("TestHelper.IsValueTypeT1<T>(T)",
@"{
// Code size 20 (0x14)
.maxstack 1
.locals init (T V_0, //v
bool V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: box ""T""
IL_0007: brfalse.s IL_000e
IL_0009: ldarg.0
IL_000a: stloc.0
IL_000b: ldc.i4.1
IL_000c: br.s IL_000f
IL_000e: ldc.i4.0
IL_000f: stloc.1
IL_0010: br.s IL_0012
IL_0012: ldloc.1
IL_0013: ret
}");
compVerifier.VerifyIL("TestHelper.IsValueTypeT2<T>(T)",
@"{
// Code size 15 (0xf)
.maxstack 2
.locals init (bool V_0)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: box ""T""
IL_0007: ldnull
IL_0008: cgt.un
IL_000a: stloc.0
IL_000b: br.s IL_000d
IL_000d: ldloc.0
IL_000e: ret
}");
}
[Fact, WorkItem(26387, "https://github.com/dotnet/roslyn/issues/26387")]
public void ValueTypeArgument02()
{
var source =
@"namespace ConsoleApp1
{
public class TestHelper
{
public static void Main()
{
IsValueTypeT(new Result<(Cls, IInt)>((new Cls(), new Int())));
System.Console.WriteLine(""done"");
}
public static void IsValueTypeT<T>(Result<T> result)
{
if (!(result.Value is T v))
throw new NotPossibleException();
}
}
public class Result<T>
{
public T Value { get; }
public Result(T value)
{
Value = value;
}
}
public class Cls { }
public interface IInt { }
public class Int : IInt { }
public class NotPossibleException : System.Exception { }
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics();
var expectedOutput =
@"done";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("ConsoleApp1.TestHelper.IsValueTypeT<T>(ConsoleApp1.Result<T>)",
@"{
// Code size 31 (0x1f)
.maxstack 2
.locals init (T V_0, //v
bool V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: callvirt ""T ConsoleApp1.Result<T>.Value.get""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: box ""T""
IL_000e: ldnull
IL_000f: cgt.un
IL_0011: ldc.i4.0
IL_0012: ceq
IL_0014: stloc.1
IL_0015: ldloc.1
IL_0016: brfalse.s IL_001e
IL_0018: newobj ""ConsoleApp1.NotPossibleException..ctor()""
IL_001d: throw
IL_001e: ret
}");
}
[Fact]
public void DeconstructNullableTuple_01()
{
var source =
@"
class C {
static int i = 3;
static (int,int)? GetNullableTuple() => (i++, i++);
static void Main() {
if (GetNullableTuple() is (int x1, int y1) tupl1)
{
System.Console.WriteLine($""x = {x1}, y = {y1}"");
}
if (GetNullableTuple() is (int x2, int y2) _)
{
System.Console.WriteLine($""x = {x2}, y = {y2}"");
}
switch (GetNullableTuple())
{
case (int x3, int y3) s:
System.Console.WriteLine($""x = {x3}, y = {y3}"");
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics();
var expectedOutput = @"x = 3, y = 4
x = 5, y = 6
x = 7, y = 8";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void DeconstructNullable_01()
{
var source =
@"
class C {
static int i = 3;
static S? GetNullableTuple() => new S(i++, i++);
static void Main() {
if (GetNullableTuple() is (int x1, int y1) tupl1)
{
System.Console.WriteLine($""x = {x1}, y = {y1}"");
}
if (GetNullableTuple() is (int x2, int y2) _)
{
System.Console.WriteLine($""x = {x2}, y = {y2}"");
}
switch (GetNullableTuple())
{
case (int x3, int y3) s:
System.Console.WriteLine($""x = {x3}, y = {y3}"");
break;
}
}
}
struct S
{
int x, y;
public S(int X, int Y) => (this.x, this.y) = (X, Y);
public void Deconstruct(out int X, out int Y) => (X, Y) = (x, y);
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics();
var expectedOutput = @"x = 3, y = 4
x = 5, y = 6
x = 7, y = 8";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact, WorkItem(28632, "https://github.com/dotnet/roslyn/issues/28632")]
public void UnboxNullableInRecursivePattern01()
{
var source =
@"
static class Program
{
public static int M1(int? x)
{
return x is int y ? y : 1;
}
public static int M2(int? x)
{
return x is { } y ? y : 2;
}
public static void Main()
{
System.Console.WriteLine(M1(null));
System.Console.WriteLine(M2(null));
System.Console.WriteLine(M1(3));
System.Console.WriteLine(M2(4));
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
var expectedOutput =
@"1
2
3
4";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("Program.M1",
@"{
// Code size 23 (0x17)
.maxstack 1
.locals init (int V_0) //y
IL_0000: ldarga.s V_0
IL_0002: call ""bool int?.HasValue.get""
IL_0007: brfalse.s IL_0013
IL_0009: ldarga.s V_0
IL_000b: call ""int int?.GetValueOrDefault()""
IL_0010: stloc.0
IL_0011: br.s IL_0015
IL_0013: ldc.i4.1
IL_0014: ret
IL_0015: ldloc.0
IL_0016: ret
}");
compVerifier.VerifyIL("Program.M2",
@"{
// Code size 23 (0x17)
.maxstack 1
.locals init (int V_0) //y
IL_0000: ldarga.s V_0
IL_0002: call ""bool int?.HasValue.get""
IL_0007: brfalse.s IL_0013
IL_0009: ldarga.s V_0
IL_000b: call ""int int?.GetValueOrDefault()""
IL_0010: stloc.0
IL_0011: br.s IL_0015
IL_0013: ldc.i4.2
IL_0014: ret
IL_0015: ldloc.0
IL_0016: ret
}");
}
[Fact]
public void DoNotShareInputForMutatingWhenClause()
{
var source =
@"using System;
class Program
{
static void Main()
{
Console.Write(M1(1));
Console.Write(M2(1));
Console.Write(M3(1));
Console.Write(M4(1));
Console.Write(M5(1));
Console.Write(M6(1));
Console.Write(M7(1));
Console.Write(M8(1));
Console.Write(M9(1));
}
public static int M1(int x)
{
return x switch { _ when (++x) == 5 => 1, 1 => 2, _ => 3 };
}
public static int M2(int x)
{
return x switch { _ when (x+=1) == 5 => 1, 1 => 2, _ => 3 };
}
public static int M3(int x)
{
return x switch { _ when ((x, _) = (5, 6)) == (0, 0) => 1, 1 => 2, _ => 3 };
}
public static int M4(int x)
{
dynamic d = new Program();
return x switch { _ when d.M(ref x) => 1, 1 => 2, _ => 3 };
}
bool M(ref int x) { x = 100; return false; }
public static int M5(int x)
{
return x switch { _ when new Program(ref x).P => 1, 1 => 2, _ => 3 };
}
public static int M6(int x)
{
dynamic d = x;
return x switch { _ when new Program(d, ref x).P => 1, 1 => 2, _ => 3 };
}
public static int M7(int x)
{
return x switch { _ when new Program(ref x).P && new Program().P => 1, 1 => 2, _ => 3 };
}
public static int M8(int x)
{
dynamic d = x;
return x switch { _ when new Program(d, ref x).P && new Program().P => 1, 1 => 2, _ => 3 };
}
public static int M9(int x)
{
return x switch { _ when (x=100) == 1 => 1, 1 => 2, _ => 3 };
}
Program() { }
Program(ref int x) { x = 100; }
Program(int a, ref int x) { x = 100; }
bool P => false;
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, references: new[] { CSharpRef });
compilation.VerifyDiagnostics();
var expectedOutput = @"222222222";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void GenerateStringHashOnlyOnce()
{
var source =
@"using System;
class Program
{
static void Main()
{
Console.Write(M1(string.Empty));
Console.Write(M2(string.Empty));
}
public static int M1(string s)
{
return s switch { ""a""=>1, ""b""=>2, ""c""=>3, ""d""=>4, ""e""=>5, ""f""=>6, ""g""=>7, ""h""=>8, _ => 9 };
}
public static int M2(string s)
{
return s switch { ""a""=>1, ""b""=>2, ""c""=>3, ""d""=>4, ""e""=>5, ""f""=>6, ""g""=>7, ""h""=>8, _ => 9 };
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
var expectedOutput = @"99";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void BindVariablesInWhenClause()
{
var source =
@"using System;
class Program
{
static void Main()
{
var t = (1, 2);
switch (t)
{
case var (x, y) when x+1 == y:
Console.Write(1);
break;
}
Console.Write(t switch
{
var (x, y) when x+1 == y => 1,
_ => 2
});
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
var expectedOutput = @"11";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void MissingExceptions_01()
{
var source = @"namespace System {
public class Object { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
}
static class C {
public static bool M(int i) => i switch { 1 => true };
}
";
var compilation = CreateEmptyCompilation(source, options: TestOptions.ReleaseDll);
compilation.GetDiagnostics().Verify(
// (9,38): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '0' is not covered.
// public static bool M(int i) => i switch { 1 => true };
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("0").WithLocation(9, 38)
);
compilation.GetEmitDiagnostics().Verify(
// warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options.
Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1),
// (9,36): error CS0656: Missing compiler required member 'System.InvalidOperationException..ctor'
// public static bool M(int i) => i switch { 1 => true };
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "i switch { 1 => true }").WithArguments("System.InvalidOperationException", ".ctor").WithLocation(9, 36),
// (9,38): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '0' is not covered.
// public static bool M(int i) => i switch { 1 => true };
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("0").WithLocation(9, 38)
);
}
[Fact, WorkItem(32774, "https://github.com/dotnet/roslyn/issues/32774")]
public void BadCode_32774()
{
var source = @"
public class Class1
{
static void Main()
{
System.Console.WriteLine(SwitchCaseThatFails(12.123));
}
public static bool SwitchCaseThatFails(object someObject)
{
switch (someObject)
{
case IObject x when x.SubObject != null:
return false;
case IOtherObject x:
return false;
case double x:
return true;
default:
return false;
}
}
public interface IObject
{
IObject SubObject { get; }
}
public interface IOtherObject { }
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics();
var expectedOutput = @"True";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("Class1.SwitchCaseThatFails",
@"{
// Code size 97 (0x61)
.maxstack 1
.locals init (Class1.IObject V_0, //x
Class1.IOtherObject V_1, //x
double V_2, //x
object V_3,
object V_4,
bool V_5)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.s V_4
IL_0004: ldloc.s V_4
IL_0006: stloc.3
IL_0007: ldloc.3
IL_0008: isinst ""Class1.IObject""
IL_000d: stloc.0
IL_000e: ldloc.0
IL_000f: brtrue.s IL_003c
IL_0011: br.s IL_001f
IL_0013: ldloc.3
IL_0014: isinst ""Class1.IOtherObject""
IL_0019: stloc.1
IL_001a: ldloc.1
IL_001b: brtrue.s IL_004b
IL_001d: br.s IL_0059
IL_001f: ldloc.3
IL_0020: isinst ""Class1.IOtherObject""
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: brtrue.s IL_004b
IL_0029: br.s IL_002b
IL_002b: ldloc.3
IL_002c: isinst ""double""
IL_0031: brfalse.s IL_0059
IL_0033: ldloc.3
IL_0034: unbox.any ""double""
IL_0039: stloc.2
IL_003a: br.s IL_0052
IL_003c: ldloc.0
IL_003d: callvirt ""Class1.IObject Class1.IObject.SubObject.get""
IL_0042: brtrue.s IL_0046
IL_0044: br.s IL_0013
IL_0046: ldc.i4.0
IL_0047: stloc.s V_5
IL_0049: br.s IL_005e
IL_004b: br.s IL_004d
IL_004d: ldc.i4.0
IL_004e: stloc.s V_5
IL_0050: br.s IL_005e
IL_0052: br.s IL_0054
IL_0054: ldc.i4.1
IL_0055: stloc.s V_5
IL_0057: br.s IL_005e
IL_0059: ldc.i4.0
IL_005a: stloc.s V_5
IL_005c: br.s IL_005e
IL_005e: ldloc.s V_5
IL_0060: ret
}");
}
// Possible test helper bug on Linux; see https://github.com/dotnet/roslyn/issues/33356
[ConditionalFact(typeof(WindowsOnly))]
public void SwitchExpressionSequencePoints()
{
string source = @"
public class Program
{
public static void Main()
{
int i = 0;
var y = (i switch
{
0 => new Program(),
1 => new Program(),
_ => new Program(),
}).Chain();
y.Chain2();
}
public Program Chain() => this;
public Program Chain2() => this;
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugExe);
v.VerifyIL(qualifiedMethodName: "Program.Main", @"
{
// Code size 61 (0x3d)
.maxstack 2
.locals init (int V_0, //i
Program V_1, //y
Program V_2)
// sequence point: {
IL_0000: nop
// sequence point: int i = 0;
IL_0001: ldc.i4.0
IL_0002: stloc.0
// sequence point: var y = (i s ... }).Chain()
IL_0003: ldc.i4.1
IL_0004: brtrue.s IL_0007
// sequence point: switch ... }
IL_0006: nop
// sequence point: <hidden>
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0012
IL_000a: br.s IL_000c
IL_000c: ldloc.0
IL_000d: ldc.i4.1
IL_000e: beq.s IL_001a
IL_0010: br.s IL_0022
// sequence point: new Program()
IL_0012: newobj ""Program..ctor()""
IL_0017: stloc.2
IL_0018: br.s IL_002a
// sequence point: new Program()
IL_001a: newobj ""Program..ctor()""
IL_001f: stloc.2
IL_0020: br.s IL_002a
// sequence point: new Program()
IL_0022: newobj ""Program..ctor()""
IL_0027: stloc.2
IL_0028: br.s IL_002a
// sequence point: <hidden>
IL_002a: ldc.i4.1
IL_002b: brtrue.s IL_002e
// sequence point: var y = (i s ... }).Chain()
IL_002d: nop
// sequence point: <hidden>
IL_002e: ldloc.2
IL_002f: callvirt ""Program Program.Chain()""
IL_0034: stloc.1
// sequence point: y.Chain2();
IL_0035: ldloc.1
IL_0036: callvirt ""Program Program.Chain2()""
IL_003b: pop
// sequence point: }
IL_003c: ret
}
", sequencePoints: "Program.Main", source: source);
}
[Fact, WorkItem(33675, "https://github.com/dotnet/roslyn/issues/33675")]
public void ParsingParenthesizedExpressionAsPatternOfExpressionSwitch()
{
var source = @"
public class Class1
{
static void Main()
{
System.Console.Write(M(42));
System.Console.Write(M(41));
}
static bool M(object o)
{
const int X = 42;
return o switch { (X) => true, _ => false };
}
}";
foreach (var options in new[] { TestOptions.DebugExe, TestOptions.ReleaseExe })
{
var compilation = CreateCompilation(source, options: options);
compilation.VerifyDiagnostics();
var expectedOutput = @"TrueFalse";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
if (options.OptimizationLevel == OptimizationLevel.Debug)
{
compVerifier.VerifyIL("Class1.M", @"
{
// Code size 45 (0x2d)
.maxstack 2
.locals init (bool V_0,
int V_1,
bool V_2)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: brtrue.s IL_0005
IL_0004: nop
IL_0005: ldarg.0
IL_0006: isinst ""int""
IL_000b: brfalse.s IL_001f
IL_000d: ldarg.0
IL_000e: unbox.any ""int""
IL_0013: stloc.1
IL_0014: ldloc.1
IL_0015: ldc.i4.s 42
IL_0017: beq.s IL_001b
IL_0019: br.s IL_001f
IL_001b: ldc.i4.1
IL_001c: stloc.0
IL_001d: br.s IL_0023
IL_001f: ldc.i4.0
IL_0020: stloc.0
IL_0021: br.s IL_0023
IL_0023: ldc.i4.1
IL_0024: brtrue.s IL_0027
IL_0026: nop
IL_0027: ldloc.0
IL_0028: stloc.2
IL_0029: br.s IL_002b
IL_002b: ldloc.2
IL_002c: ret
}
");
}
else
{
compVerifier.VerifyIL("Class1.M",
@"{
// Code size 26 (0x1a)
.maxstack 2
.locals init (bool V_0)
IL_0000: ldarg.0
IL_0001: isinst ""int""
IL_0006: brfalse.s IL_0016
IL_0008: ldarg.0
IL_0009: unbox.any ""int""
IL_000e: ldc.i4.s 42
IL_0010: bne.un.s IL_0016
IL_0012: ldc.i4.1
IL_0013: stloc.0
IL_0014: br.s IL_0018
IL_0016: ldc.i4.0
IL_0017: stloc.0
IL_0018: ldloc.0
IL_0019: ret
}");
}
}
}
[Fact, WorkItem(35584, "https://github.com/dotnet/roslyn/issues/35584")]
public void MatchToTypeParameterUnbox_01()
{
var source = @"
class Program
{
public static void Main() => System.Console.WriteLine(P<int>(0));
public static string P<T>(T t) => (t is object o) ? o.ToString() : string.Empty;
}
";
var expectedOutput = @"0";
foreach (var options in new[] { TestOptions.DebugExe, TestOptions.ReleaseExe })
{
var compilation = CreateCompilation(source, options: options);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
if (options.OptimizationLevel == OptimizationLevel.Debug)
{
compVerifier.VerifyIL("Program.P<T>",
@"{
// Code size 24 (0x18)
.maxstack 1
.locals init (object V_0) //o
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brtrue.s IL_0011
IL_000a: ldsfld ""string string.Empty""
IL_000f: br.s IL_0017
IL_0011: ldloc.0
IL_0012: callvirt ""string object.ToString()""
IL_0017: ret
}
");
}
else
{
compVerifier.VerifyIL("Program.P<T>",
@"{
// Code size 23 (0x17)
.maxstack 1
.locals init (object V_0) //o
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brtrue.s IL_0010
IL_000a: ldsfld ""string string.Empty""
IL_000f: ret
IL_0010: ldloc.0
IL_0011: callvirt ""string object.ToString()""
IL_0016: ret
}
");
}
}
}
[Fact, WorkItem(35584, "https://github.com/dotnet/roslyn/issues/35584")]
public void MatchToTypeParameterUnbox_02()
{
var source =
@"using System;
class Program
{
public static void Main()
{
var generic = new Generic<int>(0);
}
}
public class Generic<T>
{
public Generic(T value)
{
if (value is object obj && obj == null)
{
throw new Exception(""Kaboom!"");
}
}
}
";
var expectedOutput = @"";
foreach (var options in new[] { TestOptions.DebugExe, TestOptions.ReleaseExe })
{
var compilation = CreateCompilation(source, options: options);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
if (options.OptimizationLevel == OptimizationLevel.Debug)
{
compVerifier.VerifyIL("Generic<T>..ctor(T)",
@"{
// Code size 42 (0x2a)
.maxstack 2
.locals init (object V_0, //obj
bool V_1)
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: nop
IL_0007: nop
IL_0008: ldarg.1
IL_0009: box ""T""
IL_000e: stloc.0
IL_000f: ldloc.0
IL_0010: brfalse.s IL_0018
IL_0012: ldloc.0
IL_0013: ldnull
IL_0014: ceq
IL_0016: br.s IL_0019
IL_0018: ldc.i4.0
IL_0019: stloc.1
IL_001a: ldloc.1
IL_001b: brfalse.s IL_0029
IL_001d: nop
IL_001e: ldstr ""Kaboom!""
IL_0023: newobj ""System.Exception..ctor(string)""
IL_0028: throw
IL_0029: ret
}
");
}
else
{
compVerifier.VerifyIL("Generic<T>..ctor(T)",
@"{
// Code size 31 (0x1f)
.maxstack 1
.locals init (object V_0) //obj
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ldarg.1
IL_0007: box ""T""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: brfalse.s IL_001e
IL_0010: ldloc.0
IL_0011: brtrue.s IL_001e
IL_0013: ldstr ""Kaboom!""
IL_0018: newobj ""System.Exception..ctor(string)""
IL_001d: throw
IL_001e: ret
}
");
}
}
}
[Fact, WorkItem(35584, "https://github.com/dotnet/roslyn/issues/35584")]
public void MatchToTypeParameterUnbox_03()
{
var source =
@"using System;
class Program
{
public static void Main() => System.Console.WriteLine(P<Enum>(null));
public static string P<T>(T t) where T: Enum => (t is ValueType o) ? o.ToString() : ""1"";
}
";
var expectedOutput = @"1";
foreach (var options in new[] { TestOptions.DebugExe, TestOptions.ReleaseExe })
{
var compilation = CreateCompilation(source, options: options);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
if (options.OptimizationLevel == OptimizationLevel.Debug)
{
compVerifier.VerifyIL("Program.P<T>",
@"{
// Code size 24 (0x18)
.maxstack 1
.locals init (System.ValueType V_0) //o
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brtrue.s IL_0011
IL_000a: ldstr ""1""
IL_000f: br.s IL_0017
IL_0011: ldloc.0
IL_0012: callvirt ""string object.ToString()""
IL_0017: ret
}
");
}
else
{
compVerifier.VerifyIL("Program.P<T>",
@"{
// Code size 23 (0x17)
.maxstack 1
.locals init (System.ValueType V_0) //o
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brtrue.s IL_0010
IL_000a: ldstr ""1""
IL_000f: ret
IL_0010: ldloc.0
IL_0011: callvirt ""string object.ToString()""
IL_0016: ret
}
");
}
}
}
[Fact]
public void CompileTimeRuntimeInstanceofMismatch_01()
{
var source =
@"using System;
class Program
{
static void Main()
{
M(new byte[1]);
M(new sbyte[1]);
M(new Ebyte[1]);
M(new Esbyte[1]);
M(new short[1]);
M(new ushort[1]);
M(new Eshort[1]);
M(new Eushort[1]);
M(new int[1]);
M(new uint[1]);
M(new Eint[1]);
M(new Euint[1]);
M(new int[1][]);
M(new uint[1][]);
M(new Eint[1][]);
M(new Euint[1][]);
M(new long[1]);
M(new ulong[1]);
M(new Elong[1]);
M(new Eulong[1]);
M(new IntPtr[1]);
M(new UIntPtr[1]);
M(new IntPtr[1][]);
M(new UIntPtr[1][]);
}
static void M(object o)
{
switch (o)
{
case byte[] _ when o.GetType() == typeof(byte[]):
Console.WriteLine(""byte[]"");
break;
case sbyte[] _ when o.GetType() == typeof(sbyte[]):
Console.WriteLine(""sbyte[]"");
break;
case Ebyte[] _ when o.GetType() == typeof(Ebyte[]):
Console.WriteLine(""Ebyte[]"");
break;
case Esbyte[] _ when o.GetType() == typeof(Esbyte[]):
Console.WriteLine(""Esbyte[]"");
break;
case short[] _ when o.GetType() == typeof(short[]):
Console.WriteLine(""short[]"");
break;
case ushort[] _ when o.GetType() == typeof(ushort[]):
Console.WriteLine(""ushort[]"");
break;
case Eshort[] _ when o.GetType() == typeof(Eshort[]):
Console.WriteLine(""Eshort[]"");
break;
case Eushort[] _ when o.GetType() == typeof(Eushort[]):
Console.WriteLine(""Eushort[]"");
break;
case int[] _ when o.GetType() == typeof(int[]):
Console.WriteLine(""int[]"");
break;
case uint[] _ when o.GetType() == typeof(uint[]):
Console.WriteLine(""uint[]"");
break;
case Eint[] _ when o.GetType() == typeof(Eint[]):
Console.WriteLine(""Eint[]"");
break;
case Euint[] _ when o.GetType() == typeof(Euint[]):
Console.WriteLine(""Euint[]"");
break;
case int[][] _ when o.GetType() == typeof(int[][]):
Console.WriteLine(""int[][]"");
break;
case uint[][] _ when o.GetType() == typeof(uint[][]):
Console.WriteLine(""uint[][]"");
break;
case Eint[][] _ when o.GetType() == typeof(Eint[][]):
Console.WriteLine(""Eint[][]"");
break;
case Euint[][] _ when o.GetType() == typeof(Euint[][]):
Console.WriteLine(""Euint[][]"");
break;
case long[] _ when o.GetType() == typeof(long[]):
Console.WriteLine(""long[]"");
break;
case ulong[] _ when o.GetType() == typeof(ulong[]):
Console.WriteLine(""ulong[]"");
break;
case Elong[] _ when o.GetType() == typeof(Elong[]):
Console.WriteLine(""Elong[]"");
break;
case Eulong[] _ when o.GetType() == typeof(Eulong[]):
Console.WriteLine(""Eulong[]"");
break;
case IntPtr[] _ when o.GetType() == typeof(IntPtr[]):
Console.WriteLine(""IntPtr[]"");
break;
case UIntPtr[] _ when o.GetType() == typeof(UIntPtr[]):
Console.WriteLine(""UIntPtr[]"");
break;
case IntPtr[][] _ when o.GetType() == typeof(IntPtr[][]):
Console.WriteLine(""IntPtr[][]"");
break;
case UIntPtr[][] _ when o.GetType() == typeof(UIntPtr[][]):
Console.WriteLine(""UIntPtr[][]"");
break;
default:
Console.WriteLine(""oops: "" + o.GetType());
break;
}
}
}
enum Ebyte : byte {}
enum Esbyte : sbyte {}
enum Eshort : short {}
enum Eushort : ushort {}
enum Eint : int {}
enum Euint : uint {}
enum Elong : long {}
enum Eulong : ulong {}
";
var expectedOutput =
@"byte[]
sbyte[]
Ebyte[]
Esbyte[]
short[]
ushort[]
Eshort[]
Eushort[]
int[]
uint[]
Eint[]
Euint[]
int[][]
uint[][]
Eint[][]
Euint[][]
long[]
ulong[]
Elong[]
Eulong[]
IntPtr[]
UIntPtr[]
IntPtr[][]
UIntPtr[][]
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: expectedOutput);
compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void CompileTimeRuntimeInstanceofMismatch_02()
{
var source =
@"using System;
class Program
{
static void Main()
{
M(new byte[1]);
M(new sbyte[1]);
}
static void M(object o)
{
switch (o)
{
case byte[] _:
Console.WriteLine(""byte[]"");
break;
case sbyte[] _: // not subsumed, even though it will never occur due to CLR behavior
Console.WriteLine(""sbyte[]"");
break;
}
}
}
";
var expectedOutput =
@"byte[]
byte[]
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: expectedOutput);
compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
[WorkItem(36496, "https://github.com/dotnet/roslyn/issues/36496")]
public void EmptyVarPatternVsDeconstruct()
{
var source =
@"using System;
public class C
{
public static void Main()
{
Console.Write(M(new C()));
Console.Write(M(null));
}
public static bool M(C c)
{
return c is var ();
}
public void Deconstruct() { }
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation, expectedOutput: "TrueFalse");
compVerifier.VerifyIL("C.M(C)",
@"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldnull
IL_0002: cgt.un
IL_0004: ret
}
");
}
[Fact]
[WorkItem(36496, "https://github.com/dotnet/roslyn/issues/36496")]
public void EmptyPositionalPatternVsDeconstruct()
{
var source =
@"using System;
public class C
{
public static void Main()
{
Console.Write(M(new C()));
Console.Write(M(null));
}
public static bool M(C c)
{
return c is ();
}
public void Deconstruct() { }
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation, expectedOutput: "TrueFalse");
compVerifier.VerifyIL("C.M(C)",
@"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldnull
IL_0002: cgt.un
IL_0004: ret
}
");
}
[Fact, WorkItem(31494, "https://github.com/dotnet/roslyn/issues/31494")]
public void NoRedundantNullCheckForStringConstantPattern_01()
{
var source =
@"public class C
{
public static bool M1(string s) => s is ""Frog"";
public static bool M2(string s) => s == ""Frog"";
public static bool M3(string s) => s switch { ""Frog"" => true, _ => false };
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M1(string)", @"
{
// Code size 12 (0xc)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldstr ""Frog""
IL_0006: call ""bool string.op_Equality(string, string)""
IL_000b: ret
}
");
compVerifier.VerifyIL("C.M2(string)", @"
{
// Code size 12 (0xc)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldstr ""Frog""
IL_0006: call ""bool string.op_Equality(string, string)""
IL_000b: ret
}
");
compVerifier.VerifyIL("C.M3(string)", @"
{
// Code size 21 (0x15)
.maxstack 2
.locals init (bool V_0)
IL_0000: ldarg.0
IL_0001: ldstr ""Frog""
IL_0006: call ""bool string.op_Equality(string, string)""
IL_000b: brfalse.s IL_0011
IL_000d: ldc.i4.1
IL_000e: stloc.0
IL_000f: br.s IL_0013
IL_0011: ldc.i4.0
IL_0012: stloc.0
IL_0013: ldloc.0
IL_0014: ret
}
");
}
[Fact, WorkItem(31494, "https://github.com/dotnet/roslyn/issues/31494")]
public void NoRedundantNullCheckForStringConstantPattern_02()
{
var source =
@"public class C
{
public static bool M1(string s) => s switch { ""Frog"" => true, ""Newt"" => true, _ => false };
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M1(string)", @"
{
// Code size 40 (0x28)
.maxstack 2
.locals init (bool V_0)
IL_0000: ldarg.0
IL_0001: ldstr ""Frog""
IL_0006: call ""bool string.op_Equality(string, string)""
IL_000b: brtrue.s IL_001c
IL_000d: ldarg.0
IL_000e: ldstr ""Newt""
IL_0013: call ""bool string.op_Equality(string, string)""
IL_0018: brtrue.s IL_0020
IL_001a: br.s IL_0024
IL_001c: ldc.i4.1
IL_001d: stloc.0
IL_001e: br.s IL_0026
IL_0020: ldc.i4.1
IL_0021: stloc.0
IL_0022: br.s IL_0026
IL_0024: ldc.i4.0
IL_0025: stloc.0
IL_0026: ldloc.0
IL_0027: ret
}
");
}
[Fact, WorkItem(31494, "https://github.com/dotnet/roslyn/issues/31494")]
public void NoRedundantNullCheckForStringConstantPattern_03()
{
var source =
@"public class C
{
public static bool M1(System.Type x) => x is { Name: ""Program"" };
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M1(System.Type)", @"
{
// Code size 22 (0x16)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brfalse.s IL_0014
IL_0003: ldarg.0
IL_0004: callvirt ""string System.Reflection.MemberInfo.Name.get""
IL_0009: ldstr ""Program""
IL_000e: call ""bool string.op_Equality(string, string)""
IL_0013: ret
IL_0014: ldc.i4.0
IL_0015: ret
}
");
}
[Fact]
[WorkItem(42912, "https://github.com/dotnet/roslyn/issues/42912")]
[WorkItem(31494, "https://github.com/dotnet/roslyn/issues/31494")]
public void NoRedundantNullCheckForNullableConstantPattern_04()
{
// Note that we do not produce the same code for `x is 1` and `x == 1`.
// The latter has been optimized to avoid branches.
var source =
@"public class C
{
public static bool M1(int? x) => x is 1;
public static bool M2(int? x) => x == 1;
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M1(int?)", @"
{
// Code size 22 (0x16)
.maxstack 2
IL_0000: ldarga.s V_0
IL_0002: call ""bool int?.HasValue.get""
IL_0007: brfalse.s IL_0014
IL_0009: ldarga.s V_0
IL_000b: call ""int int?.GetValueOrDefault()""
IL_0010: ldc.i4.1
IL_0011: ceq
IL_0013: ret
IL_0014: ldc.i4.0
IL_0015: ret
}
");
compVerifier.VerifyIL("C.M2(int?)", @"
{
// Code size 23 (0x17)
.maxstack 2
.locals init (int? V_0,
int V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldc.i4.1
IL_0003: stloc.1
IL_0004: ldloca.s V_0
IL_0006: call ""int int?.GetValueOrDefault()""
IL_000b: ldloc.1
IL_000c: ceq
IL_000e: ldloca.s V_0
IL_0010: call ""bool int?.HasValue.get""
IL_0015: and
IL_0016: ret
}
");
}
[Fact]
public void SwitchExpressionAsExceptionFilter_01()
{
var source = @"
using System;
class C
{
const string K1 = ""frog"";
const string K2 = ""toad"";
public static void M(string msg)
{
try
{
T(msg);
}
catch (Exception e) when (e.Message switch
{
K1 => true,
K2 => true,
_ => false,
})
{
throw new Exception(e.Message);
}
catch
{
}
}
static void T(string msg)
{
throw new Exception(msg);
}
static void Main()
{
Try(K1);
Try(K2);
Try(""fox"");
}
static void Try(string s)
{
try { M(s); } catch (Exception ex) { Console.WriteLine(ex.Message); }
}
}
";
var expectedOutput =
@"frog
toad";
foreach (var compilationOptions in new[] { TestOptions.ReleaseExe, TestOptions.DebugExe })
{
var compilation = CreateCompilation(source, options: compilationOptions);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
if (compilationOptions.OptimizationLevel == OptimizationLevel.Debug)
{
compVerifier.VerifyIL("C.M(string)", @"
{
// Code size 108 (0x6c)
.maxstack 2
.locals init (System.Exception V_0, //e
bool V_1,
string V_2,
bool V_3)
IL_0000: nop
.try
{
IL_0001: nop
IL_0002: ldarg.0
IL_0003: call ""void C.T(string)""
IL_0008: nop
IL_0009: nop
IL_000a: leave.s IL_006b
}
filter
{
IL_000c: isinst ""System.Exception""
IL_0011: dup
IL_0012: brtrue.s IL_0018
IL_0014: pop
IL_0015: ldc.i4.0
IL_0016: br.s IL_0056
IL_0018: stloc.0
IL_0019: ldloc.0
IL_001a: callvirt ""string System.Exception.Message.get""
IL_001f: stloc.2
IL_0020: ldc.i4.1
IL_0021: brtrue.s IL_0024
IL_0023: nop
IL_0024: ldloc.2
IL_0025: ldstr ""frog""
IL_002a: call ""bool string.op_Equality(string, string)""
IL_002f: brtrue.s IL_0040
IL_0031: ldloc.2
IL_0032: ldstr ""toad""
IL_0037: call ""bool string.op_Equality(string, string)""
IL_003c: brtrue.s IL_0044
IL_003e: br.s IL_0048
IL_0040: ldc.i4.1
IL_0041: stloc.1
IL_0042: br.s IL_004c
IL_0044: ldc.i4.1
IL_0045: stloc.1
IL_0046: br.s IL_004c
IL_0048: ldc.i4.0
IL_0049: stloc.1
IL_004a: br.s IL_004c
IL_004c: ldc.i4.1
IL_004d: brtrue.s IL_0050
IL_004f: nop
IL_0050: ldloc.1
IL_0051: stloc.3
IL_0052: ldloc.3
IL_0053: ldc.i4.0
IL_0054: cgt.un
IL_0056: endfilter
} // end filter
{ // handler
IL_0058: pop
IL_0059: nop
IL_005a: ldloc.0
IL_005b: callvirt ""string System.Exception.Message.get""
IL_0060: newobj ""System.Exception..ctor(string)""
IL_0065: throw
}
catch object
{
IL_0066: pop
IL_0067: nop
IL_0068: nop
IL_0069: leave.s IL_006b
}
IL_006b: ret
}
");
}
else
{
compVerifier.VerifyIL("C.M(string)", @"
{
// Code size 89 (0x59)
.maxstack 2
.locals init (System.Exception V_0, //e
bool V_1,
string V_2)
.try
{
IL_0000: ldarg.0
IL_0001: call ""void C.T(string)""
IL_0006: leave.s IL_0058
}
filter
{
IL_0008: isinst ""System.Exception""
IL_000d: dup
IL_000e: brtrue.s IL_0014
IL_0010: pop
IL_0011: ldc.i4.0
IL_0012: br.s IL_0046
IL_0014: stloc.0
IL_0015: ldloc.0
IL_0016: callvirt ""string System.Exception.Message.get""
IL_001b: stloc.2
IL_001c: ldloc.2
IL_001d: ldstr ""frog""
IL_0022: call ""bool string.op_Equality(string, string)""
IL_0027: brtrue.s IL_0038
IL_0029: ldloc.2
IL_002a: ldstr ""toad""
IL_002f: call ""bool string.op_Equality(string, string)""
IL_0034: brtrue.s IL_003c
IL_0036: br.s IL_0040
IL_0038: ldc.i4.1
IL_0039: stloc.1
IL_003a: br.s IL_0042
IL_003c: ldc.i4.1
IL_003d: stloc.1
IL_003e: br.s IL_0042
IL_0040: ldc.i4.0
IL_0041: stloc.1
IL_0042: ldloc.1
IL_0043: ldc.i4.0
IL_0044: cgt.un
IL_0046: endfilter
} // end filter
{ // handler
IL_0048: pop
IL_0049: ldloc.0
IL_004a: callvirt ""string System.Exception.Message.get""
IL_004f: newobj ""System.Exception..ctor(string)""
IL_0054: throw
}
catch object
{
IL_0055: pop
IL_0056: leave.s IL_0058
}
IL_0058: ret
}
");
}
}
}
[Fact]
public void SwitchExpressionAsExceptionFilter_02()
{
var source = @"
using System;
class C
{
public static void Main()
{
try
{
throw new Exception();
}
catch when ((3 is int i) switch { true when M(() => i) => true, _ => false })
{
Console.WriteLine(""correct"");
}
}
static bool M(Func<int> func)
{
func();
return true;
}
}
";
var expectedOutput = @"correct";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
[WorkItem(48259, "https://github.com/dotnet/roslyn/issues/48259")]
public void SwitchExpressionAsExceptionFilter_03()
{
var source = @"
using System;
using System.Threading.Tasks;
public static class Program
{
static async Task Main()
{
Exception ex = new ArgumentException();
try
{
throw ex;
}
catch (Exception e) when (e switch { InvalidOperationException => true, _ => false })
{
return;
}
catch (Exception)
{
Console.WriteLine(""correct"");
}
}
}
";
var expectedOutput = "correct";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics(
// (7,23): 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.
// static async Task Main()
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Main").WithLocation(7, 23));
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
[WorkItem(48259, "https://github.com/dotnet/roslyn/issues/48259")]
public void SwitchExpressionAsExceptionFilter_04()
{
var source = @"
using System;
using System.Threading.Tasks;
public static class Program
{
static async Task Main()
{
Exception ex = new ArgumentException();
try
{
throw ex;
}
catch (Exception e) when (e switch { ArgumentException => true, _ => false })
{
Console.WriteLine(""correct"");
return;
}
}
}
";
var expectedOutput = "correct";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics(
// (7,23): 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.
// static async Task Main()
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Main").WithLocation(7, 23));
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[WorkItem(48563, "https://github.com/dotnet/roslyn/issues/48563")]
[Theory]
[InlineData("void*")]
[InlineData("char*")]
[InlineData("delegate*<void>")]
public void IsNull_01(string pointerType)
{
var source =
$@"using static System.Console;
unsafe class Program
{{
static void Main()
{{
Check(0);
Check(-1);
}}
static void Check(nint i)
{{
{pointerType} p = ({pointerType})i;
WriteLine(EqualNull(p));
WriteLine(IsNull(p));
WriteLine(NotEqualNull(p));
WriteLine(IsNotNull(p));
}}
static bool EqualNull({pointerType} p) => p == null;
static bool NotEqualNull({pointerType} p) => p != null;
static bool IsNull({pointerType} p) => p is null;
static bool IsNotNull({pointerType} p) => p is not null;
}}";
var verifier = CompileAndVerify(source, options: TestOptions.UnsafeReleaseExe, verify: Verification.Skipped, expectedOutput:
@"True
True
False
False
False
False
True
True");
string expectedEqualNull =
@"{
// Code size 6 (0x6)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: conv.u
IL_0003: ceq
IL_0005: ret
}";
string expectedNotEqualNull =
@"{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: conv.u
IL_0003: ceq
IL_0005: ldc.i4.0
IL_0006: ceq
IL_0008: ret
}";
verifier.VerifyIL("Program.EqualNull", expectedEqualNull);
verifier.VerifyIL("Program.NotEqualNull", expectedNotEqualNull);
verifier.VerifyIL("Program.IsNull", expectedEqualNull);
verifier.VerifyIL("Program.IsNotNull", expectedNotEqualNull);
}
[WorkItem(48563, "https://github.com/dotnet/roslyn/issues/48563")]
[Fact]
public void IsNull_02()
{
var source =
@"using static System.Console;
unsafe class Program
{
static void Main()
{
Check(0);
Check(-1);
}
static void Check(nint i)
{
char* p = (char*)i;
WriteLine(EqualNull(p));
}
static bool EqualNull(char* p) => p switch { null => true, _ => false };
}";
var verifier = CompileAndVerify(source, options: TestOptions.UnsafeReleaseExe, verify: Verification.Skipped, expectedOutput:
@"True
False");
verifier.VerifyIL("Program.EqualNull",
@"{
// Code size 13 (0xd)
.maxstack 2
.locals init (bool V_0)
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: conv.u
IL_0003: bne.un.s IL_0009
IL_0005: ldc.i4.1
IL_0006: stloc.0
IL_0007: br.s IL_000b
IL_0009: ldc.i4.0
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: ret
}");
}
[WorkItem(48563, "https://github.com/dotnet/roslyn/issues/48563")]
[Fact]
public void IsNull_03()
{
var source =
@"using static System.Console;
unsafe class C
{
public char* P;
}
unsafe class Program
{
static void Main()
{
Check(0);
Check(-1);
}
static void Check(nint i)
{
char* p = (char*)i;
WriteLine(EqualNull(new C() { P = p }));
}
static bool EqualNull(C c) => c switch { { P: null } => true, _ => false };
}";
var verifier = CompileAndVerify(source, options: TestOptions.UnsafeReleaseExe, verify: Verification.Skipped, expectedOutput:
@"True
False");
verifier.VerifyIL("Program.EqualNull",
@"{
// Code size 21 (0x15)
.maxstack 2
.locals init (bool V_0)
IL_0000: ldarg.0
IL_0001: brfalse.s IL_0011
IL_0003: ldarg.0
IL_0004: ldfld ""char* C.P""
IL_0009: ldc.i4.0
IL_000a: conv.u
IL_000b: bne.un.s IL_0011
IL_000d: ldc.i4.1
IL_000e: stloc.0
IL_000f: br.s IL_0013
IL_0011: ldc.i4.0
IL_0012: stloc.0
IL_0013: ldloc.0
IL_0014: ret
}");
}
#endregion Miscellaneous
#region Target Typed Switch
[Fact]
public void TargetTypedSwitch_Assignment()
{
var source = @"
using System;
class Program
{
public static void Main()
{
Console.Write(M(false));
Console.Write(M(true));
}
static object M(bool b)
{
int result = b switch { false => new A(), true => new B() };
return result;
}
}
class A
{
public static implicit operator int(A a) => throw null;
public static implicit operator B(A a) => new B();
}
class B
{
public static implicit operator int(B b) => (b == null) ? throw null : 2;
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
var expectedOutput = @"22";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void TargetTypedSwitch_Return()
{
var source = @"
using System;
class Program
{
public static void Main()
{
Console.Write(M(false));
Console.Write(M(true));
}
static long M(bool b)
{
return b switch { false => new A(), true => new B() };
}
}
class A
{
public static implicit operator int(A a) => throw null;
public static implicit operator B(A a) => new B();
}
class B
{
public static implicit operator int(B b) => (b == null) ? throw null : 2;
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
var expectedOutput = @"22";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void TargetTypedSwitch_Argument_01()
{
var source = @"
using System;
class Program
{
public static void Main()
{
Console.Write(M1(false));
Console.Write(M1(true));
}
static object M1(bool b)
{
return M2(b switch { false => new A(), true => new B() });
}
static Exception M2(Exception ex) => ex;
static int M2(int i) => i;
static int M2(string s) => s.Length;
}
class A : Exception
{
public static implicit operator int(A a) => throw null;
public static implicit operator B(A a) => throw null;
}
class B : Exception
{
public static implicit operator int(B b) => throw null;
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics(
// (12,16): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M2(Exception)' and 'Program.M2(int)'
// return M2(b switch { false => new A(), true => new B() });
Diagnostic(ErrorCode.ERR_AmbigCall, "M2").WithArguments("Program.M2(System.Exception)", "Program.M2(int)").WithLocation(12, 16)
);
}
[Fact]
public void TargetTypedSwitch_Argument_02()
{
var source = @"
using System;
class Program
{
public static void Main()
{
Console.Write(M1(false));
Console.Write(M1(true));
}
static object M1(bool b)
{
return M2(b switch { false => new A(), true => new B() });
}
// static Exception M2(Exception ex) => ex;
static int M2(int i) => i;
static int M2(string s) => s.Length;
}
class A : Exception
{
public static implicit operator int(A a) => throw null;
public static implicit operator B(A a) => new B();
}
class B : Exception
{
public static implicit operator int(B b) => (b == null) ? throw null : 2;
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
var expectedOutput = @"22";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)]
public void TargetTypedSwitch_Arglist()
{
var source = @"
using System;
class Program
{
public static void Main()
{
Console.WriteLine(M1(false));
Console.WriteLine(M1(true));
}
static object M1(bool b)
{
return M2(__arglist(b switch { false => new A(), true => new B() }));
}
static int M2(__arglist) => 1;
}
class A
{
public A() { Console.Write(""new A; ""); }
public static implicit operator B(A a) { Console.Write(""A->""); return new B(); }
}
class B
{
public B() { Console.Write(""new B; ""); }
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
var expectedOutput =
@"new A; A->new B; 1
new B; 1";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void TargetTypedSwitch_StackallocSize()
{
var source = @"
using System;
class Program
{
public static void Main()
{
M1(false);
M1(true);
}
static void M1(bool b)
{
Span<int> s = stackalloc int[b switch { false => new A(), true => new B() }];
Console.WriteLine(s.Length);
}
}
class A
{
public A() { Console.Write(""new A; ""); }
public static implicit operator int(A a) { Console.Write(""A->int; ""); return 4; }
}
class B
{
public B() { Console.Write(""new B; ""); }
public static implicit operator int(B b) { Console.Write(""B->int; ""); return 2; }
}
";
var compilation = CreateCompilationWithMscorlibAndSpan(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
var expectedOutput =
@"new A; A->int; 4
new B; B->int; 2";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput, verify: Verification.Skipped);
}
[Fact]
public void TargetTypedSwitch_Attribute()
{
var source = @"
using System;
class Program
{
[My(1 switch { 1 => 1, _ => 2 })]
public static void M1() { }
[My(1 switch { 1 => new A(), _ => new B() })]
public static void M2() { }
[My(1 switch { 1 => 1, _ => string.Empty })]
public static void M3() { }
}
public class MyAttribute : Attribute
{
public MyAttribute(int Value) { }
}
public class A
{
public static implicit operator int(A a) => 4;
}
public class B
{
public static implicit operator int(B b) => 2;
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (5,9): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [My(1 switch { 1 => 1, _ => 2 })]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "1 switch { 1 => 1, _ => 2 }").WithLocation(5, 9),
// (8,9): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [My(1 switch { 1 => new A(), _ => new B() })]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "1 switch { 1 => new A(), _ => new B() }").WithLocation(8, 9),
// (11,9): error CS1503: Argument 1: cannot convert from '<switch expression>' to 'int'
// [My(1 switch { 1 => 1, _ => string.Empty })]
Diagnostic(ErrorCode.ERR_BadArgType, "1 switch { 1 => 1, _ => string.Empty }").WithArguments("1", "<switch expression>", "int").WithLocation(11, 9)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var switchExpressions = tree.GetRoot().DescendantNodes().OfType<SwitchExpressionSyntax>().ToArray();
VerifyOperationTreeForNode(compilation, model, switchExpressions[0], @"
ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: '1 switch { ... 1, _ => 2 }')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Arms(2):
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '1 => 1')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '_ => 2')
Pattern:
IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null, IsInvalid) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2')
");
VerifyOperationTreeForNode(compilation, model, switchExpressions[1], @"
ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: '1 switch { ... > new B() }')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Arms(2):
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '1 => new A()')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Int32 A.op_Implicit(A a)) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'new A()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 A.op_Implicit(A a))
Operand:
IObjectCreationOperation (Constructor: A..ctor()) (OperationKind.ObjectCreation, Type: A, IsInvalid) (Syntax: 'new A()')
Arguments(0)
Initializer:
null
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '_ => new B()')
Pattern:
IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null, IsInvalid) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Int32 B.op_Implicit(B b)) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'new B()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 B.op_Implicit(B b))
Operand:
IObjectCreationOperation (Constructor: B..ctor()) (OperationKind.ObjectCreation, Type: B, IsInvalid) (Syntax: 'new B()')
Arguments(0)
Initializer:
null
");
VerifyOperationTreeForNode(compilation, model, switchExpressions[2], @"
ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: ?, IsInvalid) (Syntax: '1 switch { ... ing.Empty }')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Arms(2):
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '1 => 1')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsInvalid, IsImplicit) (Syntax: '1')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '_ => string.Empty')
Pattern:
IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null, IsInvalid) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsInvalid, IsImplicit) (Syntax: 'string.Empty')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String, IsInvalid) (Syntax: 'string.Empty')
Instance Receiver:
null
");
}
[Fact]
public void TargetTypedSwitch_Attribute_NamedArgument()
{
var source = @"
using System;
class Program
{
[My(Value = 1 switch { 1 => 1, _ => 2 })]
public static void M1() { }
[My(Value = 1 switch { 1 => new A(), _ => new B() })]
public static void M2() { }
[My(Value = 1 switch { 1 => 1, _ => string.Empty })]
public static void M3() { }
}
public class MyAttribute : Attribute
{
public MyAttribute() { }
public int Value { get; set; }
}
public class A
{
public static implicit operator int(A a) => 4;
}
public class B
{
public static implicit operator int(B b) => 2;
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (5,17): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [My(Value = 1 switch { 1 => 1, _ => 2 })]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "1 switch { 1 => 1, _ => 2 }").WithLocation(5, 17),
// (8,17): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [My(Value = 1 switch { 1 => new A(), _ => new B() })]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "1 switch { 1 => new A(), _ => new B() }").WithLocation(8, 17),
// (11,41): error CS0029: Cannot implicitly convert type 'string' to 'int'
// [My(Value = 1 switch { 1 => 1, _ => string.Empty })]
Diagnostic(ErrorCode.ERR_NoImplicitConv, "string.Empty").WithArguments("string", "int").WithLocation(11, 41)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var attributeArguments = tree.GetRoot().DescendantNodes().OfType<AttributeArgumentSyntax>().ToArray();
VerifyOperationTreeForNode(compilation, model, attributeArguments[0], @"
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'Value = 1 s ... 1, _ => 2 }')
Left:
IPropertyReferenceOperation: System.Int32 MyAttribute.Value { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Value')
Instance Receiver:
null
Right:
ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: '1 switch { ... 1, _ => 2 }')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Arms(2):
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '1 => 1')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '_ => 2')
Pattern:
IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null, IsInvalid) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2')
");
VerifyOperationTreeForNode(compilation, model, attributeArguments[1], @"
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'Value = 1 s ... > new B() }')
Left:
IPropertyReferenceOperation: System.Int32 MyAttribute.Value { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Value')
Instance Receiver:
null
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '1 switch { ... > new B() }')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: '1 switch { ... > new B() }')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Arms(2):
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '1 => new A()')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Int32 A.op_Implicit(A a)) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'new A()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 A.op_Implicit(A a))
Operand:
IObjectCreationOperation (Constructor: A..ctor()) (OperationKind.ObjectCreation, Type: A, IsInvalid) (Syntax: 'new A()')
Arguments(0)
Initializer:
null
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '_ => new B()')
Pattern:
IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null, IsInvalid) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Int32 B.op_Implicit(B b)) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'new B()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 B.op_Implicit(B b))
Operand:
IObjectCreationOperation (Constructor: B..ctor()) (OperationKind.ObjectCreation, Type: B, IsInvalid) (Syntax: 'new B()')
Arguments(0)
Initializer:
null
");
VerifyOperationTreeForNode(compilation, model, attributeArguments[2], @"
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'Value = 1 s ... ing.Empty }')
Left:
IPropertyReferenceOperation: System.Int32 MyAttribute.Value { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Value')
Instance Receiver:
null
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '1 switch { ... ing.Empty }')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: ?, IsInvalid) (Syntax: '1 switch { ... ing.Empty }')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Arms(2):
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '1 => 1')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: '1')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '_ => string.Empty')
Pattern:
IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsInvalid, IsImplicit) (Syntax: 'string.Empty')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String, IsInvalid) (Syntax: 'string.Empty')
Instance Receiver:
null
");
}
[Fact]
public void TargetTypedSwitch_Attribute_MissingNamedArgument()
{
var source = @"
using System;
class Program
{
[My(Value = 1 switch { 1 => 1, _ => 2 })]
public static void M1() { }
[My(Value = 1 switch { 1 => new A(), _ => new B() })]
public static void M2() { }
[My(Value = 1 switch { 1 => 1, _ => string.Empty })]
public static void M3() { }
}
public class MyAttribute : Attribute
{
public MyAttribute() { }
}
public class A
{
public static implicit operator int(A a) => 4;
}
public class B
{
public static implicit operator int(B b) => 2;
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (5,9): error CS0246: The type or namespace name 'Value' could not be found (are you missing a using directive or an assembly reference?)
// [My(Value = 1 switch { 1 => 1, _ => 2 })]
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Value").WithArguments("Value").WithLocation(5, 9),
// (8,9): error CS0246: The type or namespace name 'Value' could not be found (are you missing a using directive or an assembly reference?)
// [My(Value = 1 switch { 1 => new A(), _ => new B() })]
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Value").WithArguments("Value").WithLocation(8, 9),
// (11,9): error CS0246: The type or namespace name 'Value' could not be found (are you missing a using directive or an assembly reference?)
// [My(Value = 1 switch { 1 => 1, _ => string.Empty })]
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Value").WithArguments("Value").WithLocation(11, 9)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var attributeArguments = tree.GetRoot().DescendantNodes().OfType<AttributeArgumentSyntax>().ToArray();
VerifyOperationTreeForNode(compilation, model, attributeArguments[0], @"
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'Value = 1 s ... 1, _ => 2 }')
Left:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Value')
Children(0)
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: '1 switch { ... 1, _ => 2 }')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32) (Syntax: '1 switch { ... 1, _ => 2 }')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Arms(2):
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '1 => 1')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '_ => 2')
Pattern:
IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
");
VerifyOperationTreeForNode(compilation, model, attributeArguments[1], @"
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'Value = 1 s ... > new B() }')
Left:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Value')
Children(0)
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: '1 switch { ... > new B() }')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: ?) (Syntax: '1 switch { ... > new B() }')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Arms(2):
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '1 => new A()')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: 'new A()')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IObjectCreationOperation (Constructor: A..ctor()) (OperationKind.ObjectCreation, Type: A) (Syntax: 'new A()')
Arguments(0)
Initializer:
null
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '_ => new B()')
Pattern:
IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: 'new B()')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IObjectCreationOperation (Constructor: B..ctor()) (OperationKind.ObjectCreation, Type: B) (Syntax: 'new B()')
Arguments(0)
Initializer:
null
");
VerifyOperationTreeForNode(compilation, model, attributeArguments[2], @"
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'Value = 1 s ... ing.Empty }')
Left:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Value')
Children(0)
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: '1 switch { ... ing.Empty }')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: ?) (Syntax: '1 switch { ... ing.Empty }')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Arms(2):
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '1 => 1')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: '1')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '_ => string.Empty')
Pattern:
IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: 'string.Empty')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String) (Syntax: 'string.Empty')
Instance Receiver:
null
");
}
[Fact]
public void TargetTypedSwitch_As()
{
var source = @"
class Program
{
public static void M(int i, string s)
{
// we do not target-type the left-hand-side of an as expression
_ = i switch { 1 => i, _ => s } as object;
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (7,15): error CS8506: No best type was found for the switch expression.
// _ = i switch { 1 => i, _ => s } as object;
Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(7, 15)
);
}
[Fact]
public void TargetTypedSwitch_DoubleConversion()
{
var source = @"using System;
class Program
{
public static void Main(string[] args)
{
M(false);
M(true);
}
public static void M(bool b)
{
C c = b switch { false => new A(), true => new B() };
Console.WriteLine(""."");
}
}
class A
{
public A()
{
Console.Write(""new A; "");
}
public static implicit operator B(A a)
{
Console.Write(""A->"");
return new B();
}
}
class B
{
public B()
{
Console.Write(""new B; "");
}
public static implicit operator C(B a)
{
Console.Write(""B->"");
return new C();
}
}
class C
{
public C()
{
Console.Write(""new C; "");
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics();
var expectedOutput =
@"new A; A->new B; B->new C; .
new B; B->new C; .";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void TargetTypedSwitch_StringInsert()
{
var source = @"
using System;
class Program
{
public static void Main()
{
Console.Write($""{false switch { false => new A(), true => new B() }}"");
Console.Write($""{true switch { false => new A(), true => new B() }}"");
}
}
class A
{
}
class B
{
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: "AB");
}
#endregion Target Typed Switch
#region Pattern Combinators
[Fact]
public void IsPatternDisjunct_01()
{
var source = @"
using System;
class C
{
static bool M1(object o) => o is int or long;
static bool M2(object o) => o is int || o is long;
public static void Main()
{
Console.Write(M1(1));
Console.Write(M1(string.Empty));
Console.Write(M1(1L));
Console.Write(M1(1UL));
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithPatternCombinators);
compilation.VerifyDiagnostics();
var expectedOutput = @"TrueFalseTrueFalse";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
var code = @"
{
// Code size 21 (0x15)
.maxstack 2
IL_0000: ldarg.0
IL_0001: isinst ""int""
IL_0006: brtrue.s IL_0013
IL_0008: ldarg.0
IL_0009: isinst ""long""
IL_000e: ldnull
IL_000f: cgt.un
IL_0011: br.s IL_0014
IL_0013: ldc.i4.1
IL_0014: ret
}
";
compVerifier.VerifyIL("C.M1", code);
compVerifier.VerifyIL("C.M2", code);
compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.RegularWithPatternCombinators);
compilation.VerifyDiagnostics();
compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
code = @"
{
// Code size 20 (0x14)
.maxstack 2
IL_0000: ldarg.0
IL_0001: isinst ""int""
IL_0006: brtrue.s IL_0012
IL_0008: ldarg.0
IL_0009: isinst ""long""
IL_000e: ldnull
IL_000f: cgt.un
IL_0011: ret
IL_0012: ldc.i4.1
IL_0013: ret
}
";
compVerifier.VerifyIL("C.M1", code);
compVerifier.VerifyIL("C.M2", code);
}
[Fact]
public void IsPatternDisjunct_02()
{
var source = @"
using System;
class C
{
static string M1(object o) => (o is int or long) ? ""True"" : ""False"";
static string M2(object o) => (o is int || o is long) ? ""True"" : ""False"";
public static void Main()
{
Console.Write(M1(1));
Console.Write(M1(string.Empty));
Console.Write(M1(1L));
Console.Write(M1(1UL));
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithPatternCombinators);
compilation.VerifyDiagnostics();
var expectedOutput = @"TrueFalseTrueFalse";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
var code = @"
{
// Code size 29 (0x1d)
.maxstack 1
IL_0000: ldarg.0
IL_0001: isinst ""int""
IL_0006: brtrue.s IL_0017
IL_0008: ldarg.0
IL_0009: isinst ""long""
IL_000e: brtrue.s IL_0017
IL_0010: ldstr ""False""
IL_0015: br.s IL_001c
IL_0017: ldstr ""True""
IL_001c: ret
}
";
compVerifier.VerifyIL("C.M1", code);
compVerifier.VerifyIL("C.M2", code);
compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.RegularWithPatternCombinators);
compilation.VerifyDiagnostics();
compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
code = @"
{
// Code size 28 (0x1c)
.maxstack 1
IL_0000: ldarg.0
IL_0001: isinst ""int""
IL_0006: brtrue.s IL_0016
IL_0008: ldarg.0
IL_0009: isinst ""long""
IL_000e: brtrue.s IL_0016
IL_0010: ldstr ""False""
IL_0015: ret
IL_0016: ldstr ""True""
IL_001b: ret
}
";
compVerifier.VerifyIL("C.M1", code);
compVerifier.VerifyIL("C.M2", code);
}
[Fact]
public void IsPatternDisjunct_03()
{
var source = @"
using System;
class C
{
static bool M1(object o) => o is >= 'A' and <= 'Z' or >= 'a' and <= 'z';
static bool M2(object o) => o is char c && (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z');
public static void Main()
{
Console.Write(M1('A'));
Console.Write(M1('0'));
Console.Write(M1('q'));
Console.Write(M1(2));
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithPatternCombinators);
compilation.VerifyDiagnostics();
var expectedOutput = @"TrueFalseTrueFalse";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("C.M1", @"
{
// Code size 47 (0x2f)
.maxstack 2
.locals init (char V_0,
bool V_1)
IL_0000: ldarg.0
IL_0001: isinst ""char""
IL_0006: brfalse.s IL_002b
IL_0008: ldarg.0
IL_0009: unbox.any ""char""
IL_000e: stloc.0
IL_000f: ldloc.0
IL_0010: ldc.i4.s 97
IL_0012: blt.s IL_001b
IL_0014: ldloc.0
IL_0015: ldc.i4.s 122
IL_0017: ble.s IL_0027
IL_0019: br.s IL_002b
IL_001b: ldloc.0
IL_001c: ldc.i4.s 65
IL_001e: blt.s IL_002b
IL_0020: ldloc.0
IL_0021: ldc.i4.s 90
IL_0023: ble.s IL_0027
IL_0025: br.s IL_002b
IL_0027: ldc.i4.1
IL_0028: stloc.1
IL_0029: br.s IL_002d
IL_002b: ldc.i4.0
IL_002c: stloc.1
IL_002d: ldloc.1
IL_002e: ret
}
");
compVerifier.VerifyIL("C.M2", @"
{
// Code size 48 (0x30)
.maxstack 2
.locals init (char V_0) //c
IL_0000: ldarg.0
IL_0001: isinst ""char""
IL_0006: brfalse.s IL_002e
IL_0008: ldarg.0
IL_0009: unbox.any ""char""
IL_000e: stloc.0
IL_000f: ldloc.0
IL_0010: ldc.i4.s 65
IL_0012: blt.s IL_0019
IL_0014: ldloc.0
IL_0015: ldc.i4.s 90
IL_0017: ble.s IL_002b
IL_0019: ldloc.0
IL_001a: ldc.i4.s 97
IL_001c: blt.s IL_0028
IL_001e: ldloc.0
IL_001f: ldc.i4.s 122
IL_0021: cgt
IL_0023: ldc.i4.0
IL_0024: ceq
IL_0026: br.s IL_0029
IL_0028: ldc.i4.0
IL_0029: br.s IL_002c
IL_002b: ldc.i4.1
IL_002c: br.s IL_002f
IL_002e: ldc.i4.0
IL_002f: ret
}
");
compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.RegularWithPatternCombinators);
compilation.VerifyDiagnostics();
compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("C.M1", @"
{
// Code size 45 (0x2d)
.maxstack 2
.locals init (char V_0,
bool V_1)
IL_0000: ldarg.0
IL_0001: isinst ""char""
IL_0006: brfalse.s IL_0029
IL_0008: ldarg.0
IL_0009: unbox.any ""char""
IL_000e: stloc.0
IL_000f: ldloc.0
IL_0010: ldc.i4.s 97
IL_0012: blt.s IL_001b
IL_0014: ldloc.0
IL_0015: ldc.i4.s 122
IL_0017: ble.s IL_0025
IL_0019: br.s IL_0029
IL_001b: ldloc.0
IL_001c: ldc.i4.s 65
IL_001e: blt.s IL_0029
IL_0020: ldloc.0
IL_0021: ldc.i4.s 90
IL_0023: bgt.s IL_0029
IL_0025: ldc.i4.1
IL_0026: stloc.1
IL_0027: br.s IL_002b
IL_0029: ldc.i4.0
IL_002a: stloc.1
IL_002b: ldloc.1
IL_002c: ret
}
");
compVerifier.VerifyIL("C.M2", @"
{
// Code size 45 (0x2d)
.maxstack 2
.locals init (char V_0) //c
IL_0000: ldarg.0
IL_0001: isinst ""char""
IL_0006: brfalse.s IL_002b
IL_0008: ldarg.0
IL_0009: unbox.any ""char""
IL_000e: stloc.0
IL_000f: ldloc.0
IL_0010: ldc.i4.s 65
IL_0012: blt.s IL_0019
IL_0014: ldloc.0
IL_0015: ldc.i4.s 90
IL_0017: ble.s IL_0029
IL_0019: ldloc.0
IL_001a: ldc.i4.s 97
IL_001c: blt.s IL_0027
IL_001e: ldloc.0
IL_001f: ldc.i4.s 122
IL_0021: cgt
IL_0023: ldc.i4.0
IL_0024: ceq
IL_0026: ret
IL_0027: ldc.i4.0
IL_0028: ret
IL_0029: ldc.i4.1
IL_002a: ret
IL_002b: ldc.i4.0
IL_002c: ret
}
");
}
[Fact]
public void IsPatternDisjunct_04()
{
var source = @"
using System;
class C
{
static int M1(char c) => (c is >= 'A' and <= 'Z' or >= 'a' and <= 'z') ? 1 : 0;
static int M2(char c) => (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') ? 1 : 0;
public static void Main()
{
Console.Write(M1('A'));
Console.Write(M1('0'));
Console.Write(M1('q'));
Console.Write(M1(' '));
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithPatternCombinators);
compilation.VerifyDiagnostics();
var expectedOutput = @"1010";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("C.M1", @"
{
// Code size 38 (0x26)
.maxstack 2
.locals init (bool V_0)
IL_0000: ldarg.0
IL_0001: ldc.i4.s 97
IL_0003: blt.s IL_000c
IL_0005: ldarg.0
IL_0006: ldc.i4.s 122
IL_0008: ble.s IL_0018
IL_000a: br.s IL_001c
IL_000c: ldarg.0
IL_000d: ldc.i4.s 65
IL_000f: blt.s IL_001c
IL_0011: ldarg.0
IL_0012: ldc.i4.s 90
IL_0014: ble.s IL_0018
IL_0016: br.s IL_001c
IL_0018: ldc.i4.1
IL_0019: stloc.0
IL_001a: br.s IL_001e
IL_001c: ldc.i4.0
IL_001d: stloc.0
IL_001e: ldloc.0
IL_001f: brtrue.s IL_0024
IL_0021: ldc.i4.0
IL_0022: br.s IL_0025
IL_0024: ldc.i4.1
IL_0025: ret
}
");
compVerifier.VerifyIL("C.M2", @"
{
// Code size 25 (0x19)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 65
IL_0003: blt.s IL_000a
IL_0005: ldarg.0
IL_0006: ldc.i4.s 90
IL_0008: ble.s IL_0017
IL_000a: ldarg.0
IL_000b: ldc.i4.s 97
IL_000d: blt.s IL_0014
IL_000f: ldarg.0
IL_0010: ldc.i4.s 122
IL_0012: ble.s IL_0017
IL_0014: ldc.i4.0
IL_0015: br.s IL_0018
IL_0017: ldc.i4.1
IL_0018: ret
}
");
compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.RegularWithPatternCombinators);
compilation.VerifyDiagnostics();
compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("C.M1", @"
{
// Code size 35 (0x23)
.maxstack 2
.locals init (bool V_0)
IL_0000: ldarg.0
IL_0001: ldc.i4.s 97
IL_0003: blt.s IL_000c
IL_0005: ldarg.0
IL_0006: ldc.i4.s 122
IL_0008: ble.s IL_0016
IL_000a: br.s IL_001a
IL_000c: ldarg.0
IL_000d: ldc.i4.s 65
IL_000f: blt.s IL_001a
IL_0011: ldarg.0
IL_0012: ldc.i4.s 90
IL_0014: bgt.s IL_001a
IL_0016: ldc.i4.1
IL_0017: stloc.0
IL_0018: br.s IL_001c
IL_001a: ldc.i4.0
IL_001b: stloc.0
IL_001c: ldloc.0
IL_001d: brtrue.s IL_0021
IL_001f: ldc.i4.0
IL_0020: ret
IL_0021: ldc.i4.1
IL_0022: ret
}
");
compVerifier.VerifyIL("C.M2", @"
{
// Code size 24 (0x18)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 65
IL_0003: blt.s IL_000a
IL_0005: ldarg.0
IL_0006: ldc.i4.s 90
IL_0008: ble.s IL_0016
IL_000a: ldarg.0
IL_000b: ldc.i4.s 97
IL_000d: blt.s IL_0014
IL_000f: ldarg.0
IL_0010: ldc.i4.s 122
IL_0012: ble.s IL_0016
IL_0014: ldc.i4.0
IL_0015: ret
IL_0016: ldc.i4.1
IL_0017: ret
}
");
}
[Fact]
public void IsPatternDisjunct_05()
{
var source = @"
using System;
class C
{
static int M1(char c)
{
if (c is >= 'A' and <= 'Z' or >= 'a' and <= 'z')
return 1;
else
return 0;
}
static int M2(char c)
{
if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z')
return 1;
else
return 0;
}
public static void Main()
{
Console.Write(M1('A'));
Console.Write(M1('0'));
Console.Write(M1('q'));
Console.Write(M1(' '));
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithPatternCombinators);
compilation.VerifyDiagnostics();
var expectedOutput = @"1010";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("C.M1", @"
{
// Code size 46 (0x2e)
.maxstack 2
.locals init (bool V_0,
bool V_1,
int V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldc.i4.s 97
IL_0004: blt.s IL_000d
IL_0006: ldarg.0
IL_0007: ldc.i4.s 122
IL_0009: ble.s IL_0019
IL_000b: br.s IL_001d
IL_000d: ldarg.0
IL_000e: ldc.i4.s 65
IL_0010: blt.s IL_001d
IL_0012: ldarg.0
IL_0013: ldc.i4.s 90
IL_0015: ble.s IL_0019
IL_0017: br.s IL_001d
IL_0019: ldc.i4.1
IL_001a: stloc.0
IL_001b: br.s IL_001f
IL_001d: ldc.i4.0
IL_001e: stloc.0
IL_001f: ldloc.0
IL_0020: stloc.1
IL_0021: ldloc.1
IL_0022: brfalse.s IL_0028
IL_0024: ldc.i4.1
IL_0025: stloc.2
IL_0026: br.s IL_002c
IL_0028: ldc.i4.0
IL_0029: stloc.2
IL_002a: br.s IL_002c
IL_002c: ldloc.2
IL_002d: ret
}
");
compVerifier.VerifyIL("C.M2", @"
{
// Code size 44 (0x2c)
.maxstack 2
.locals init (bool V_0,
int V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldc.i4.s 65
IL_0004: blt.s IL_000b
IL_0006: ldarg.0
IL_0007: ldc.i4.s 90
IL_0009: ble.s IL_001d
IL_000b: ldarg.0
IL_000c: ldc.i4.s 97
IL_000e: blt.s IL_001a
IL_0010: ldarg.0
IL_0011: ldc.i4.s 122
IL_0013: cgt
IL_0015: ldc.i4.0
IL_0016: ceq
IL_0018: br.s IL_001b
IL_001a: ldc.i4.0
IL_001b: br.s IL_001e
IL_001d: ldc.i4.1
IL_001e: stloc.0
IL_001f: ldloc.0
IL_0020: brfalse.s IL_0026
IL_0022: ldc.i4.1
IL_0023: stloc.1
IL_0024: br.s IL_002a
IL_0026: ldc.i4.0
IL_0027: stloc.1
IL_0028: br.s IL_002a
IL_002a: ldloc.1
IL_002b: ret
}
");
compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.RegularWithPatternCombinators);
compilation.VerifyDiagnostics();
compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("C.M1", @"
{
// Code size 35 (0x23)
.maxstack 2
.locals init (bool V_0)
IL_0000: ldarg.0
IL_0001: ldc.i4.s 97
IL_0003: blt.s IL_000c
IL_0005: ldarg.0
IL_0006: ldc.i4.s 122
IL_0008: ble.s IL_0016
IL_000a: br.s IL_001a
IL_000c: ldarg.0
IL_000d: ldc.i4.s 65
IL_000f: blt.s IL_001a
IL_0011: ldarg.0
IL_0012: ldc.i4.s 90
IL_0014: bgt.s IL_001a
IL_0016: ldc.i4.1
IL_0017: stloc.0
IL_0018: br.s IL_001c
IL_001a: ldc.i4.0
IL_001b: stloc.0
IL_001c: ldloc.0
IL_001d: brfalse.s IL_0021
IL_001f: ldc.i4.1
IL_0020: ret
IL_0021: ldc.i4.0
IL_0022: ret
}
");
compVerifier.VerifyIL("C.M2", @"
{
// Code size 24 (0x18)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 65
IL_0003: blt.s IL_000a
IL_0005: ldarg.0
IL_0006: ldc.i4.s 90
IL_0008: ble.s IL_0014
IL_000a: ldarg.0
IL_000b: ldc.i4.s 97
IL_000d: blt.s IL_0016
IL_000f: ldarg.0
IL_0010: ldc.i4.s 122
IL_0012: bgt.s IL_0016
IL_0014: ldc.i4.1
IL_0015: ret
IL_0016: ldc.i4.0
IL_0017: ret
}
");
}
[Fact, WorkItem(46536, "https://github.com/dotnet/roslyn/issues/46536")]
public void MultiplePathsToNode_SwitchDispatch_01()
{
var source = @"
using System;
class Program
{
static void Main()
{
Console.Write(M("""", 0)); // 0
Console.Write(M("""", 1)); // 1
Console.Write(M("""", 2)); // 2
Console.Write(M("""", 3)); // 3
Console.Write(M(""a"", 2)); // 2
Console.Write(M(""a"", 10)); // 3
}
static int M(string x, int y)
{
return (x, y) switch
{
("""", 0) => 0,
("""", 1) => 1,
(_, 2) => 2,
_ => 3
};
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "012323", options: TestOptions.DebugExe);
verifier.VerifyDiagnostics();
verifier.VerifyIL("Program.M", @"{
// Code size 70 (0x46)
.maxstack 2
.locals init (int V_0,
int V_1)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: brtrue.s IL_0005
IL_0004: nop
IL_0005: ldarg.0
IL_0006: ldstr """"
IL_000b: call ""bool string.op_Equality(string, string)""
IL_0010: brfalse.s IL_0026
IL_0012: ldarg.1
IL_0013: switch (
IL_002c,
IL_0030,
IL_0034)
IL_0024: br.s IL_0038
IL_0026: ldarg.1
IL_0027: ldc.i4.2
IL_0028: beq.s IL_0034
IL_002a: br.s IL_0038
IL_002c: ldc.i4.0
IL_002d: stloc.0
IL_002e: br.s IL_003c
IL_0030: ldc.i4.1
IL_0031: stloc.0
IL_0032: br.s IL_003c
IL_0034: ldc.i4.2
IL_0035: stloc.0
IL_0036: br.s IL_003c
IL_0038: ldc.i4.3
IL_0039: stloc.0
IL_003a: br.s IL_003c
IL_003c: ldc.i4.1
IL_003d: brtrue.s IL_0040
IL_003f: nop
IL_0040: ldloc.0
IL_0041: stloc.1
IL_0042: br.s IL_0044
IL_0044: ldloc.1
IL_0045: ret
}");
}
[Fact, WorkItem(46536, "https://github.com/dotnet/roslyn/issues/46536")]
public void MultiplePathsToNode_SwitchDispatch_02()
{
var source = @"
using System;
class Program
{
static void Main()
{
Console.Write(M0("""", 0)); // 0
Console.Write(M0("""", 1)); // 1
Console.Write(M0("""", 2)); // 2
Console.Write(M0("""", 3)); // 3
Console.Write(M0(""a"", 2)); // 2
Console.Write(M0(""a"", 10)); // 3
}
static int M0(string x, int y)
{
return (x, y) switch
{
("""", 0) => M1(0),
("""", 1) => M1(1),
(_, 2) => M1(2),
_ => M1(3)
};
}
static int M1(int z)
{
Console.Write(' ');
return z;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: " 0 1 2 3 2 3", options: TestOptions.DebugExe);
verifier.VerifyDiagnostics();
verifier.VerifyIL("Program.M0", @"{
// Code size 90 (0x5a)
.maxstack 2
.locals init (int V_0,
int V_1)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: brtrue.s IL_0005
IL_0004: nop
IL_0005: ldarg.0
IL_0006: ldstr """"
IL_000b: call ""bool string.op_Equality(string, string)""
IL_0010: brfalse.s IL_0026
IL_0012: ldarg.1
IL_0013: switch (
IL_002c,
IL_0035,
IL_003e)
IL_0024: br.s IL_0047
IL_0026: ldarg.1
IL_0027: ldc.i4.2
IL_0028: beq.s IL_003e
IL_002a: br.s IL_0047
IL_002c: ldc.i4.0
IL_002d: call ""int Program.M1(int)""
IL_0032: stloc.0
IL_0033: br.s IL_0050
IL_0035: ldc.i4.1
IL_0036: call ""int Program.M1(int)""
IL_003b: stloc.0
IL_003c: br.s IL_0050
IL_003e: ldc.i4.2
IL_003f: call ""int Program.M1(int)""
IL_0044: stloc.0
IL_0045: br.s IL_0050
IL_0047: ldc.i4.3
IL_0048: call ""int Program.M1(int)""
IL_004d: stloc.0
IL_004e: br.s IL_0050
IL_0050: ldc.i4.1
IL_0051: brtrue.s IL_0054
IL_0053: nop
IL_0054: ldloc.0
IL_0055: stloc.1
IL_0056: br.s IL_0058
IL_0058: ldloc.1
IL_0059: ret
}");
}
[Fact, WorkItem(46536, "https://github.com/dotnet/roslyn/issues/46536")]
public void MultiplePathsToNode_SwitchDispatch_03()
{
var source = @"
using System;
class Program
{
static void Main()
{
Console.Write(M("""", 0)); // 0
Console.Write(M("""", 1)); // 1
Console.Write(M("""", 2)); // 2
Console.Write(M("""", 3)); // 3
Console.Write(M("""", 4)); // 4
Console.Write(M("""", 5)); // 5
Console.Write(M(""a"", 2)); // 2
Console.Write(M(""a"", 3)); // 3
Console.Write(M(""a"", 4)); // 4
Console.Write(M(""a"", 10)); // 5
}
static int M(string x, int y)
{
return (x, y) switch
{
("""", 0) => 0,
("""", 1) => 1,
(_, 2) => 2,
(_, 3) => 3,
(_, 4) => 4,
_ => 5
};
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "0123452345", options: TestOptions.DebugExe);
verifier.VerifyDiagnostics();
verifier.VerifyIL("Program.M", @"{
// Code size 98 (0x62)
.maxstack 2
.locals init (int V_0,
int V_1)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: brtrue.s IL_0005
IL_0004: nop
IL_0005: ldarg.0
IL_0006: ldstr """"
IL_000b: call ""bool string.op_Equality(string, string)""
IL_0010: brfalse.s IL_002e
IL_0012: ldarg.1
IL_0013: switch (
IL_0040,
IL_0044,
IL_0048,
IL_004c,
IL_0050)
IL_002c: br.s IL_0054
IL_002e: ldarg.1
IL_002f: ldc.i4.2
IL_0030: beq.s IL_0048
IL_0032: br.s IL_0034
IL_0034: ldarg.1
IL_0035: ldc.i4.3
IL_0036: beq.s IL_004c
IL_0038: br.s IL_003a
IL_003a: ldarg.1
IL_003b: ldc.i4.4
IL_003c: beq.s IL_0050
IL_003e: br.s IL_0054
IL_0040: ldc.i4.0
IL_0041: stloc.0
IL_0042: br.s IL_0058
IL_0044: ldc.i4.1
IL_0045: stloc.0
IL_0046: br.s IL_0058
IL_0048: ldc.i4.2
IL_0049: stloc.0
IL_004a: br.s IL_0058
IL_004c: ldc.i4.3
IL_004d: stloc.0
IL_004e: br.s IL_0058
IL_0050: ldc.i4.4
IL_0051: stloc.0
IL_0052: br.s IL_0058
IL_0054: ldc.i4.5
IL_0055: stloc.0
IL_0056: br.s IL_0058
IL_0058: ldc.i4.1
IL_0059: brtrue.s IL_005c
IL_005b: nop
IL_005c: ldloc.0
IL_005d: stloc.1
IL_005e: br.s IL_0060
IL_0060: ldloc.1
IL_0061: ret
}");
}
[Fact, WorkItem(46536, "https://github.com/dotnet/roslyn/issues/46536")]
public void MultiplePathsToNode_SwitchDispatch_04()
{
var source = @"
using System;
class Program
{
static void Main()
{
Console.Write(M(""a"", ""x"")); // 0
Console.Write(M(""a"", ""y"")); // 1
Console.Write(M(""a"", ""z"")); // 2
Console.Write(M(""a"", ""w"")); // 3
Console.Write(M(""b"", ""z"")); // 2
Console.Write(M(""c"", ""z"")); // 3
Console.Write(M(""c"", ""w"")); // 3
}
static int M(string x, string y)
{
return (x, y) switch
{
(""a"", ""x"") => 0,
(""a"", ""y"") => 1,
(""a"" or ""b"", ""z"") => 2,
_ => 3
};
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "0123233", options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview);
verifier.VerifyDiagnostics();
verifier.VerifyIL("Program.M", @"{
// Code size 115 (0x73)
.maxstack 2
.locals init (int V_0,
int V_1)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: brtrue.s IL_0005
IL_0004: nop
IL_0005: ldarg.0
IL_0006: ldstr ""a""
IL_000b: call ""bool string.op_Equality(string, string)""
IL_0010: brtrue.s IL_0021
IL_0012: ldarg.0
IL_0013: ldstr ""b""
IL_0018: call ""bool string.op_Equality(string, string)""
IL_001d: brtrue.s IL_004a
IL_001f: br.s IL_0065
IL_0021: ldarg.1
IL_0022: ldstr ""z""
IL_0027: call ""bool string.op_Equality(string, string)""
IL_002c: brtrue.s IL_0061
IL_002e: ldarg.1
IL_002f: ldstr ""x""
IL_0034: call ""bool string.op_Equality(string, string)""
IL_0039: brtrue.s IL_0059
IL_003b: ldarg.1
IL_003c: ldstr ""y""
IL_0041: call ""bool string.op_Equality(string, string)""
IL_0046: brtrue.s IL_005d
IL_0048: br.s IL_0065
IL_004a: ldarg.1
IL_004b: ldstr ""z""
IL_0050: call ""bool string.op_Equality(string, string)""
IL_0055: brtrue.s IL_0061
IL_0057: br.s IL_0065
IL_0059: ldc.i4.0
IL_005a: stloc.0
IL_005b: br.s IL_0069
IL_005d: ldc.i4.1
IL_005e: stloc.0
IL_005f: br.s IL_0069
IL_0061: ldc.i4.2
IL_0062: stloc.0
IL_0063: br.s IL_0069
IL_0065: ldc.i4.3
IL_0066: stloc.0
IL_0067: br.s IL_0069
IL_0069: ldc.i4.1
IL_006a: brtrue.s IL_006d
IL_006c: nop
IL_006d: ldloc.0
IL_006e: stloc.1
IL_006f: br.s IL_0071
IL_0071: ldloc.1
IL_0072: ret
}");
}
[Fact, WorkItem(46536, "https://github.com/dotnet/roslyn/issues/46536")]
public void MultiplePathsToNode_SwitchDispatch_05()
{
var source = @"
using System;
public enum EnumA { A, B, C }
public enum EnumB { X, Y, Z }
public class Class1
{
public string Repro(EnumA a, EnumB b)
=> (a, b) switch
{
(EnumA.A, EnumB.X) => ""AX"",
(_, EnumB.Y) => ""_Y"",
(EnumA.B, EnumB.X) => ""BZ"",
(_, EnumB.Z) => ""_Z"",
(_, _) => throw new ArgumentException()
};
}
";
var verifier = CompileAndVerify(source, options: TestOptions.DebugDll);
verifier.VerifyDiagnostics();
verifier.VerifyIL("Class1.Repro", @"{
// Code size 90 (0x5a)
.maxstack 2
.locals init (string V_0)
IL_0000: ldc.i4.1
IL_0001: brtrue.s IL_0004
IL_0003: nop
IL_0004: ldarg.1
IL_0005: brtrue.s IL_001b
IL_0007: ldarg.2
IL_0008: switch (
IL_002e,
IL_0036,
IL_0046)
IL_0019: br.s IL_004e
IL_001b: ldarg.2
IL_001c: ldc.i4.1
IL_001d: beq.s IL_0036
IL_001f: ldarg.1
IL_0020: ldc.i4.1
IL_0021: bne.un.s IL_0028
IL_0023: ldarg.2
IL_0024: brfalse.s IL_003e
IL_0026: br.s IL_0028
IL_0028: ldarg.2
IL_0029: ldc.i4.2
IL_002a: beq.s IL_0046
IL_002c: br.s IL_004e
IL_002e: ldstr ""AX""
IL_0033: stloc.0
IL_0034: br.s IL_0054
IL_0036: ldstr ""_Y""
IL_003b: stloc.0
IL_003c: br.s IL_0054
IL_003e: ldstr ""BZ""
IL_0043: stloc.0
IL_0044: br.s IL_0054
IL_0046: ldstr ""_Z""
IL_004b: stloc.0
IL_004c: br.s IL_0054
IL_004e: newobj ""System.ArgumentException..ctor()""
IL_0053: throw
IL_0054: ldc.i4.1
IL_0055: brtrue.s IL_0058
IL_0057: nop
IL_0058: ldloc.0
IL_0059: ret
}");
}
#endregion Pattern Combinators
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public class PatternTests : EmitMetadataTestBase
{
#region Miscellaneous
[Fact, WorkItem(18811, "https://github.com/dotnet/roslyn/issues/18811")]
public void MissingNullable_01()
{
var source = @"namespace System {
public class Object { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
}
static class C {
public static bool M() => ((object)123) is int i;
}
";
var compilation = CreateEmptyCompilation(source, options: TestOptions.ReleaseDll);
compilation.GetDiagnostics().Verify();
compilation.GetEmitDiagnostics().Verify(
// warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options.
Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1)
);
}
[Fact, WorkItem(18811, "https://github.com/dotnet/roslyn/issues/18811")]
public void MissingNullable_02()
{
var source = @"namespace System {
public class Object { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public struct Nullable<T> where T : struct { }
}
static class C {
public static bool M() => ((object)123) is int i;
}
";
var compilation = CreateEmptyCompilation(source, options: TestOptions.UnsafeReleaseDll);
compilation.GetDiagnostics().Verify();
compilation.GetEmitDiagnostics().Verify(
// warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options.
Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion)
);
}
[Fact]
public void MissingNullable_03()
{
var source = @"namespace System {
public class Object { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public struct Nullable<T> where T : struct { }
}
static class C {
static void M1(int? x)
{
switch (x)
{
case int i: break;
}
}
static bool M2(int? x) => x is int i;
}
";
var compilation = CreateEmptyCompilation(source, options: TestOptions.UnsafeReleaseDll);
compilation.GetDiagnostics().Verify();
compilation.GetEmitDiagnostics().Verify(
// warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options.
Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1),
// (14,18): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue'
// case int i: break;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(14, 18),
// (14,18): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault'
// case int i: break;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(14, 18),
// (14,18): error CS0656: Missing compiler required member 'System.Nullable`1.get_Value'
// case int i: break;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "get_Value").WithLocation(14, 18),
// (17,36): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue'
// static bool M2(int? x) => x is int i;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(17, 36),
// (17,36): error CS0656: Missing compiler required member 'System.Nullable`1.GetValueOrDefault'
// static bool M2(int? x) => x is int i;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "GetValueOrDefault").WithLocation(17, 36),
// (17,36): error CS0656: Missing compiler required member 'System.Nullable`1.get_Value'
// static bool M2(int? x) => x is int i;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "get_Value").WithLocation(17, 36)
);
}
[Fact]
public void MissingNullable_04()
{
var source = @"namespace System {
public class Object { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
public struct Nullable<T> where T : struct { public T GetValueOrDefault() => default(T); }
}
static class C {
static void M1(int? x)
{
switch (x)
{
case int i: break;
}
}
static bool M2(int? x) => x is int i;
}
";
var compilation = CreateEmptyCompilation(source, options: TestOptions.UnsafeReleaseDll);
compilation.GetDiagnostics().Verify();
compilation.GetEmitDiagnostics().Verify(
// warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options.
Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1),
// (14,18): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue'
// case int i: break;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(14, 18),
// (17,36): error CS0656: Missing compiler required member 'System.Nullable`1.get_HasValue'
// static bool M2(int? x) => x is int i;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "int i").WithArguments("System.Nullable`1", "get_HasValue").WithLocation(17, 36)
);
}
[Fact, WorkItem(17266, "https://github.com/dotnet/roslyn/issues/17266")]
public void DoubleEvaluation01()
{
var source =
@"using System;
public class C
{
public static void Main()
{
if (TryGet() is int index)
{
Console.WriteLine(index);
}
}
public static int? TryGet()
{
Console.WriteLine(""eval"");
return null;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics();
var expectedOutput = @"eval";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("C.Main",
@"{
// Code size 42 (0x2a)
.maxstack 1
.locals init (int V_0, //index
bool V_1,
int? V_2)
IL_0000: nop
IL_0001: call ""int? C.TryGet()""
IL_0006: stloc.2
IL_0007: ldloca.s V_2
IL_0009: call ""bool int?.HasValue.get""
IL_000e: brfalse.s IL_001b
IL_0010: ldloca.s V_2
IL_0012: call ""int int?.GetValueOrDefault()""
IL_0017: stloc.0
IL_0018: ldc.i4.1
IL_0019: br.s IL_001c
IL_001b: ldc.i4.0
IL_001c: stloc.1
IL_001d: ldloc.1
IL_001e: brfalse.s IL_0029
IL_0020: nop
IL_0021: ldloc.0
IL_0022: call ""void System.Console.WriteLine(int)""
IL_0027: nop
IL_0028: nop
IL_0029: ret
}");
compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("C.Main",
@"{
// Code size 30 (0x1e)
.maxstack 1
.locals init (int V_0, //index
int? V_1)
IL_0000: call ""int? C.TryGet()""
IL_0005: stloc.1
IL_0006: ldloca.s V_1
IL_0008: call ""bool int?.HasValue.get""
IL_000d: brfalse.s IL_001d
IL_000f: ldloca.s V_1
IL_0011: call ""int int?.GetValueOrDefault()""
IL_0016: stloc.0
IL_0017: ldloc.0
IL_0018: call ""void System.Console.WriteLine(int)""
IL_001d: ret
}");
}
[Fact, WorkItem(19122, "https://github.com/dotnet/roslyn/issues/19122")]
public void PatternCrash_01()
{
var source = @"using System;
using System.Collections.Generic;
using System.Linq;
public class Class2 : IDisposable
{
public Class2(bool parameter = false)
{
}
public void Dispose()
{
}
}
class X<T>
{
IdentityAccessor<T> idAccessor = new IdentityAccessor<T>();
void Y<U>() where U : T
{
// BUG: The following line is the problem
if (GetT().FirstOrDefault(p => idAccessor.GetId(p) == Guid.Empty) is U u)
{
}
}
IEnumerable<T> GetT()
{
yield return default(T);
}
}
class IdentityAccessor<T>
{
public Guid GetId(T t)
{
return Guid.Empty;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("X<T>.Y<U>",
@"{
// Code size 61 (0x3d)
.maxstack 3
.locals init (U V_0, //u
bool V_1,
T V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call ""System.Collections.Generic.IEnumerable<T> X<T>.GetT()""
IL_0007: ldarg.0
IL_0008: ldftn ""bool X<T>.<Y>b__1_0<U>(T)""
IL_000e: newobj ""System.Func<T, bool>..ctor(object, System.IntPtr)""
IL_0013: call ""T System.Linq.Enumerable.FirstOrDefault<T>(System.Collections.Generic.IEnumerable<T>, System.Func<T, bool>)""
IL_0018: stloc.2
IL_0019: ldloc.2
IL_001a: box ""T""
IL_001f: isinst ""U""
IL_0024: brfalse.s IL_0035
IL_0026: ldloc.2
IL_0027: box ""T""
IL_002c: unbox.any ""U""
IL_0031: stloc.0
IL_0032: ldc.i4.1
IL_0033: br.s IL_0036
IL_0035: ldc.i4.0
IL_0036: stloc.1
IL_0037: ldloc.1
IL_0038: brfalse.s IL_003c
IL_003a: nop
IL_003b: nop
IL_003c: ret
}");
}
[Fact, WorkItem(24522, "https://github.com/dotnet/roslyn/issues/24522")]
public void IgnoreDeclaredConversion_01()
{
var source =
@"class Base<T>
{
public static implicit operator Derived(Base<T> obj)
{
return new Derived();
}
}
class Derived : Base<object>
{
}
class Program
{
static void Main(string[] args)
{
Base<object> x = new Derived();
System.Console.WriteLine(x is Derived);
System.Console.WriteLine(x is Derived y);
switch (x)
{
case Derived z: System.Console.WriteLine(true); break;
}
System.Console.WriteLine(null != (x as Derived));
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics();
var expectedOutput =
@"True
True
True
True";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("Program.Main",
@"{
// Code size 84 (0x54)
.maxstack 2
.locals init (Base<object> V_0, //x
Derived V_1, //y
Derived V_2, //z
Base<object> V_3,
Base<object> V_4)
IL_0000: nop
IL_0001: newobj ""Derived..ctor()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: isinst ""Derived""
IL_000d: ldnull
IL_000e: cgt.un
IL_0010: call ""void System.Console.WriteLine(bool)""
IL_0015: nop
IL_0016: ldloc.0
IL_0017: isinst ""Derived""
IL_001c: stloc.1
IL_001d: ldloc.1
IL_001e: ldnull
IL_001f: cgt.un
IL_0021: call ""void System.Console.WriteLine(bool)""
IL_0026: nop
IL_0027: ldloc.0
IL_0028: stloc.s V_4
IL_002a: ldloc.s V_4
IL_002c: stloc.3
IL_002d: ldloc.3
IL_002e: isinst ""Derived""
IL_0033: stloc.2
IL_0034: ldloc.2
IL_0035: brtrue.s IL_0039
IL_0037: br.s IL_0044
IL_0039: br.s IL_003b
IL_003b: ldc.i4.1
IL_003c: call ""void System.Console.WriteLine(bool)""
IL_0041: nop
IL_0042: br.s IL_0044
IL_0044: ldloc.0
IL_0045: isinst ""Derived""
IL_004a: ldnull
IL_004b: cgt.un
IL_004d: call ""void System.Console.WriteLine(bool)""
IL_0052: nop
IL_0053: ret
}");
}
[Fact]
public void DoublePattern01()
{
var source =
@"using System;
class Program
{
static bool P1(double d) => d is double.NaN;
static bool P2(float f) => f is float.NaN;
static bool P3(double d) => d is 3.14d;
static bool P4(float f) => f is 3.14f;
static bool P5(object o)
{
switch (o)
{
case double.NaN: return true;
case float.NaN: return true;
case 3.14d: return true;
case 3.14f: return true;
default: return false;
}
}
public static void Main(string[] args)
{
Console.Write(P1(double.NaN));
Console.Write(P1(1.0));
Console.Write(P2(float.NaN));
Console.Write(P2(1.0f));
Console.Write(P3(3.14));
Console.Write(P3(double.NaN));
Console.Write(P4(3.14f));
Console.Write(P4(float.NaN));
Console.Write(P5(double.NaN));
Console.Write(P5(0.0d));
Console.Write(P5(float.NaN));
Console.Write(P5(0.0f));
Console.Write(P5(3.14d));
Console.Write(P5(125));
Console.Write(P5(3.14f));
Console.Write(P5(1.0f));
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics();
var expectedOutput = @"TrueFalseTrueFalseTrueFalseTrueFalseTrueFalseTrueFalseTrueFalseTrueFalse";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("Program.P1",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""bool double.IsNaN(double)""
IL_0006: ret
}");
compVerifier.VerifyIL("Program.P2",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call ""bool float.IsNaN(float)""
IL_0006: ret
}");
compVerifier.VerifyIL("Program.P3",
@"{
// Code size 13 (0xd)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.r8 3.14
IL_000a: ceq
IL_000c: ret
}");
compVerifier.VerifyIL("Program.P4",
@"{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.r4 3.14
IL_0006: ceq
IL_0008: ret
}");
compVerifier.VerifyIL("Program.P5",
@"{
// Code size 103 (0x67)
.maxstack 2
.locals init (object V_0,
double V_1,
float V_2,
object V_3,
bool V_4)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.3
IL_0003: ldloc.3
IL_0004: stloc.0
IL_0005: ldloc.0
IL_0006: isinst ""double""
IL_000b: brfalse.s IL_002a
IL_000d: ldloc.0
IL_000e: unbox.any ""double""
IL_0013: stloc.1
IL_0014: ldloc.1
IL_0015: ldc.r8 3.14
IL_001e: beq.s IL_0055
IL_0020: ldloc.1
IL_0021: call ""bool double.IsNaN(double)""
IL_0026: brtrue.s IL_004b
IL_0028: br.s IL_005f
IL_002a: ldloc.0
IL_002b: isinst ""float""
IL_0030: brfalse.s IL_005f
IL_0032: ldloc.0
IL_0033: unbox.any ""float""
IL_0038: stloc.2
IL_0039: ldloc.2
IL_003a: ldc.r4 3.14
IL_003f: beq.s IL_005a
IL_0041: ldloc.2
IL_0042: call ""bool float.IsNaN(float)""
IL_0047: brtrue.s IL_0050
IL_0049: br.s IL_005f
IL_004b: ldc.i4.1
IL_004c: stloc.s V_4
IL_004e: br.s IL_0064
IL_0050: ldc.i4.1
IL_0051: stloc.s V_4
IL_0053: br.s IL_0064
IL_0055: ldc.i4.1
IL_0056: stloc.s V_4
IL_0058: br.s IL_0064
IL_005a: ldc.i4.1
IL_005b: stloc.s V_4
IL_005d: br.s IL_0064
IL_005f: ldc.i4.0
IL_0060: stloc.s V_4
IL_0062: br.s IL_0064
IL_0064: ldloc.s V_4
IL_0066: ret
}");
}
[Fact]
public void DecimalEquality()
{
// demonstrate that pattern-matching against a decimal constant is
// at least as efficient as simply using ==
var source =
@"using System;
public class C
{
public static void Main()
{
Console.Write(M1(1.0m));
Console.Write(M2(1.0m));
Console.Write(M1(2.0m));
Console.Write(M2(2.0m));
}
static int M1(decimal d)
{
if (M(d) is 1.0m) return 1;
return 0;
}
static int M2(decimal d)
{
if (M(d) == 1.0m) return 1;
return 0;
}
public static decimal M(decimal d)
{
return d;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics();
var expectedOutput = @"1100";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("C.M1",
@"{
// Code size 37 (0x25)
.maxstack 6
.locals init (bool V_0,
int V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call ""decimal C.M(decimal)""
IL_0007: ldc.i4.s 10
IL_0009: ldc.i4.0
IL_000a: ldc.i4.0
IL_000b: ldc.i4.0
IL_000c: ldc.i4.1
IL_000d: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0012: call ""bool decimal.op_Equality(decimal, decimal)""
IL_0017: stloc.0
IL_0018: ldloc.0
IL_0019: brfalse.s IL_001f
IL_001b: ldc.i4.1
IL_001c: stloc.1
IL_001d: br.s IL_0023
IL_001f: ldc.i4.0
IL_0020: stloc.1
IL_0021: br.s IL_0023
IL_0023: ldloc.1
IL_0024: ret
}");
compVerifier.VerifyIL("C.M2",
@"{
// Code size 37 (0x25)
.maxstack 6
.locals init (bool V_0,
int V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call ""decimal C.M(decimal)""
IL_0007: ldc.i4.s 10
IL_0009: ldc.i4.0
IL_000a: ldc.i4.0
IL_000b: ldc.i4.0
IL_000c: ldc.i4.1
IL_000d: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0012: call ""bool decimal.op_Equality(decimal, decimal)""
IL_0017: stloc.0
IL_0018: ldloc.0
IL_0019: brfalse.s IL_001f
IL_001b: ldc.i4.1
IL_001c: stloc.1
IL_001d: br.s IL_0023
IL_001f: ldc.i4.0
IL_0020: stloc.1
IL_0021: br.s IL_0023
IL_0023: ldloc.1
IL_0024: ret
}");
compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("C.M1",
@"{
// Code size 28 (0x1c)
.maxstack 6
IL_0000: ldarg.0
IL_0001: call ""decimal C.M(decimal)""
IL_0006: ldc.i4.s 10
IL_0008: ldc.i4.0
IL_0009: ldc.i4.0
IL_000a: ldc.i4.0
IL_000b: ldc.i4.1
IL_000c: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0011: call ""bool decimal.op_Equality(decimal, decimal)""
IL_0016: brfalse.s IL_001a
IL_0018: ldc.i4.1
IL_0019: ret
IL_001a: ldc.i4.0
IL_001b: ret
}");
compVerifier.VerifyIL("C.M2",
@"{
// Code size 28 (0x1c)
.maxstack 6
IL_0000: ldarg.0
IL_0001: call ""decimal C.M(decimal)""
IL_0006: ldc.i4.s 10
IL_0008: ldc.i4.0
IL_0009: ldc.i4.0
IL_000a: ldc.i4.0
IL_000b: ldc.i4.1
IL_000c: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0011: call ""bool decimal.op_Equality(decimal, decimal)""
IL_0016: brfalse.s IL_001a
IL_0018: ldc.i4.1
IL_0019: ret
IL_001a: ldc.i4.0
IL_001b: ret
}");
}
[Fact, WorkItem(16878, "https://github.com/dotnet/roslyn/issues/16878")]
public void RedundantNullCheck()
{
var source =
@"public class C
{
static int M1(bool? b1, bool b2)
{
switch (b1)
{
case null:
return 1;
case var _ when b2:
return 2;
case true:
return 3;
case false:
return 4;
}
}
static int M2(object o, bool b)
{
switch (o)
{
case string a when b:
return 1;
case string a:
return 2;
}
return 3;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M1",
@"{
// Code size 35 (0x23)
.maxstack 1
.locals init (bool? V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: call ""bool bool?.HasValue.get""
IL_0009: brfalse.s IL_0018
IL_000b: br.s IL_001a
IL_000d: ldloca.s V_0
IL_000f: call ""bool bool?.GetValueOrDefault()""
IL_0014: brtrue.s IL_001f
IL_0016: br.s IL_0021
IL_0018: ldc.i4.1
IL_0019: ret
IL_001a: ldarg.1
IL_001b: brfalse.s IL_000d
IL_001d: ldc.i4.2
IL_001e: ret
IL_001f: ldc.i4.3
IL_0020: ret
IL_0021: ldc.i4.4
IL_0022: ret
}");
compVerifier.VerifyIL("C.M2",
@"{
// Code size 19 (0x13)
.maxstack 1
.locals init (string V_0) //a
IL_0000: ldarg.0
IL_0001: isinst ""string""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0011
IL_000a: ldarg.1
IL_000b: brfalse.s IL_000f
IL_000d: ldc.i4.1
IL_000e: ret
IL_000f: ldc.i4.2
IL_0010: ret
IL_0011: ldc.i4.3
IL_0012: ret
}");
}
[Fact, WorkItem(12813, "https://github.com/dotnet/roslyn/issues/12813")]
public void NoBoxingOnIntegerConstantPattern()
{
var source =
@"public class C
{
static bool M1(int x)
{
return x is 42;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M1",
@"{
// Code size 6 (0x6)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 42
IL_0003: ceq
IL_0005: ret
}");
}
[Fact, WorkItem(40403, "https://github.com/dotnet/roslyn/issues/40403")]
public void RefParameter_StoreToTemp()
{
var source =
@"public class C
{
static bool M1(ref object x)
{
return x is 42;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M1",
@"{
// Code size 24 (0x18)
.maxstack 2
.locals init (object V_0)
IL_0000: ldarg.0
IL_0001: ldind.ref
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: isinst ""int""
IL_0009: brfalse.s IL_0016
IL_000b: ldloc.0
IL_000c: unbox.any ""int""
IL_0011: ldc.i4.s 42
IL_0013: ceq
IL_0015: ret
IL_0016: ldc.i4.0
IL_0017: ret
}");
}
[Fact, WorkItem(40403, "https://github.com/dotnet/roslyn/issues/40403")]
public void RefLocal_StoreToTemp()
{
var source =
@"public class C
{
static bool M1(bool b, ref object x, ref object y)
{
ref object z = ref b ? ref x : ref y;
return z is 42;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M1",
@"{
// Code size 30 (0x1e)
.maxstack 2
.locals init (object V_0)
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0006
IL_0003: ldarg.2
IL_0004: br.s IL_0007
IL_0006: ldarg.1
IL_0007: ldind.ref
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: isinst ""int""
IL_000f: brfalse.s IL_001c
IL_0011: ldloc.0
IL_0012: unbox.any ""int""
IL_0017: ldc.i4.s 42
IL_0019: ceq
IL_001b: ret
IL_001c: ldc.i4.0
IL_001d: ret
}");
}
[Fact, WorkItem(40403, "https://github.com/dotnet/roslyn/issues/40403")]
public void InParameter_StoreToTemp()
{
var source =
@"public class C
{
static bool M1(in object x)
{
return x is 42;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M1",
@"{
// Code size 24 (0x18)
.maxstack 2
.locals init (object V_0)
IL_0000: ldarg.0
IL_0001: ldind.ref
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: isinst ""int""
IL_0009: brfalse.s IL_0016
IL_000b: ldloc.0
IL_000c: unbox.any ""int""
IL_0011: ldc.i4.s 42
IL_0013: ceq
IL_0015: ret
IL_0016: ldc.i4.0
IL_0017: ret
}");
}
[Fact, WorkItem(40403, "https://github.com/dotnet/roslyn/issues/40403")]
public void RefReadonlyLocal_StoreToTemp()
{
var source =
@"public class C
{
static bool M1(bool b, in object x, in object y)
{
ref readonly object z = ref b ? ref x : ref y;
return z is 42;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M1",
@"{
// Code size 30 (0x1e)
.maxstack 2
.locals init (object V_0)
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0006
IL_0003: ldarg.2
IL_0004: br.s IL_0007
IL_0006: ldarg.1
IL_0007: ldind.ref
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: isinst ""int""
IL_000f: brfalse.s IL_001c
IL_0011: ldloc.0
IL_0012: unbox.any ""int""
IL_0017: ldc.i4.s 42
IL_0019: ceq
IL_001b: ret
IL_001c: ldc.i4.0
IL_001d: ret
}");
}
[Fact, WorkItem(40403, "https://github.com/dotnet/roslyn/issues/40403")]
public void OutParameter_StoreToTemp()
{
var source =
@"public class C
{
static bool M1(out object x)
{
x = null;
return x is 42;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M1",
@"{
// Code size 27 (0x1b)
.maxstack 2
.locals init (object V_0)
IL_0000: ldarg.0
IL_0001: ldnull
IL_0002: stind.ref
IL_0003: ldarg.0
IL_0004: ldind.ref
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: isinst ""int""
IL_000c: brfalse.s IL_0019
IL_000e: ldloc.0
IL_000f: unbox.any ""int""
IL_0014: ldc.i4.s 42
IL_0016: ceq
IL_0018: ret
IL_0019: ldc.i4.0
IL_001a: ret
}");
}
[Fact, WorkItem(22654, "https://github.com/dotnet/roslyn/issues/22654")]
public void NoRedundantTypeCheck()
{
var source =
@"using System;
public class C
{
public void SwitchBasedPatternMatching(object o)
{
switch (o)
{
case int n when n == 1:
Console.WriteLine(""1""); break;
case string s:
Console.WriteLine(""s""); break;
case int n when n == 2:
Console.WriteLine(""2""); break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.SwitchBasedPatternMatching",
@"{
// Code size 69 (0x45)
.maxstack 2
.locals init (int V_0, //n
object V_1)
IL_0000: ldarg.1
IL_0001: stloc.1
IL_0002: ldloc.1
IL_0003: isinst ""int""
IL_0008: brfalse.s IL_0013
IL_000a: ldloc.1
IL_000b: unbox.any ""int""
IL_0010: stloc.0
IL_0011: br.s IL_001c
IL_0013: ldloc.1
IL_0014: isinst ""string""
IL_0019: brtrue.s IL_002b
IL_001b: ret
IL_001c: ldloc.0
IL_001d: ldc.i4.1
IL_001e: bne.un.s IL_0036
IL_0020: ldstr ""1""
IL_0025: call ""void System.Console.WriteLine(string)""
IL_002a: ret
IL_002b: ldstr ""s""
IL_0030: call ""void System.Console.WriteLine(string)""
IL_0035: ret
IL_0036: ldloc.0
IL_0037: ldc.i4.2
IL_0038: bne.un.s IL_0044
IL_003a: ldstr ""2""
IL_003f: call ""void System.Console.WriteLine(string)""
IL_0044: ret
}");
}
[Fact, WorkItem(15437, "https://github.com/dotnet/roslyn/issues/15437")]
public void IsTypeDiscard()
{
var source =
@"public class C
{
public bool IsString(object o)
{
return o is string _;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.IsString",
@"{
// Code size 10 (0xa)
.maxstack 2
IL_0000: ldarg.1
IL_0001: isinst ""string""
IL_0006: ldnull
IL_0007: cgt.un
IL_0009: ret
}");
}
[Fact, WorkItem(19150, "https://github.com/dotnet/roslyn/issues/19150")]
public void RedundantHasValue()
{
var source =
@"using System;
public class C
{
public static void M(int? x)
{
switch (x)
{
case int i:
Console.Write(i);
break;
case null:
Console.Write(""null"");
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M",
@"{
// Code size 33 (0x21)
.maxstack 1
IL_0000: ldarga.s V_0
IL_0002: call ""bool int?.HasValue.get""
IL_0007: brfalse.s IL_0016
IL_0009: ldarga.s V_0
IL_000b: call ""int int?.GetValueOrDefault()""
IL_0010: call ""void System.Console.Write(int)""
IL_0015: ret
IL_0016: ldstr ""null""
IL_001b: call ""void System.Console.Write(string)""
IL_0020: ret
}");
}
[Fact, WorkItem(19153, "https://github.com/dotnet/roslyn/issues/19153")]
public void RedundantBox()
{
var source = @"using System;
public class C
{
public static void M<T, U>(U x) where T : U
{
// when T is not known to be a reference type, there is an unboxing conversion from
// a type parameter U to T, provided T depends on U.
switch (x)
{
case T i:
Console.Write(i);
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M<T, U>(U)",
@"{
// Code size 35 (0x23)
.maxstack 1
IL_0000: ldarg.0
IL_0001: box ""U""
IL_0006: isinst ""T""
IL_000b: brfalse.s IL_0022
IL_000d: ldarg.0
IL_000e: box ""U""
IL_0013: unbox.any ""T""
IL_0018: box ""T""
IL_001d: call ""void System.Console.Write(object)""
IL_0022: ret
}");
}
[Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")]
public void NoRedundantPropertyRead01()
{
var source = @"using System;
public class Person {
public string Name { get; set; }
}
public class C {
public void M(Person p) {
switch (p) {
case { Name: ""Bill"" }:
Console.WriteLine(""Hey Bill!"");
break;
case { Name: ""Bob"" }:
Console.WriteLine(""Hey Bob!"");
break;
case { Name: var name }:
Console.WriteLine($""Hello {name}!"");
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M",
@"{
// Code size 82 (0x52)
.maxstack 3
.locals init (string V_0) //name
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0051
IL_0003: ldarg.1
IL_0004: callvirt ""string Person.Name.get""
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: ldstr ""Bill""
IL_0010: call ""bool string.op_Equality(string, string)""
IL_0015: brtrue.s IL_0026
IL_0017: ldloc.0
IL_0018: ldstr ""Bob""
IL_001d: call ""bool string.op_Equality(string, string)""
IL_0022: brtrue.s IL_0031
IL_0024: br.s IL_003c
IL_0026: ldstr ""Hey Bill!""
IL_002b: call ""void System.Console.WriteLine(string)""
IL_0030: ret
IL_0031: ldstr ""Hey Bob!""
IL_0036: call ""void System.Console.WriteLine(string)""
IL_003b: ret
IL_003c: ldstr ""Hello ""
IL_0041: ldloc.0
IL_0042: ldstr ""!""
IL_0047: call ""string string.Concat(string, string, string)""
IL_004c: call ""void System.Console.WriteLine(string)""
IL_0051: ret
}");
}
[Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")]
public void NoRedundantPropertyRead02()
{
var source = @"using System;
public class Person {
public string Name { get; set; }
public int Age;
}
public class C {
public void M(Person p) {
switch (p) {
case Person { Name: var name, Age: 0}:
Console.WriteLine($""Hello baby { name }!"");
break;
case Person { Name: var name }:
Console.WriteLine($""Hello { name }!"");
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M",
@"{
// Code size 64 (0x40)
.maxstack 3
.locals init (string V_0, //name
string V_1) //name
IL_0000: ldarg.1
IL_0001: brfalse.s IL_003f
IL_0003: ldarg.1
IL_0004: callvirt ""string Person.Name.get""
IL_0009: stloc.0
IL_000a: ldarg.1
IL_000b: ldfld ""int Person.Age""
IL_0010: brtrue.s IL_0028
IL_0012: ldstr ""Hello baby ""
IL_0017: ldloc.0
IL_0018: ldstr ""!""
IL_001d: call ""string string.Concat(string, string, string)""
IL_0022: call ""void System.Console.WriteLine(string)""
IL_0027: ret
IL_0028: ldloc.0
IL_0029: stloc.1
IL_002a: ldstr ""Hello ""
IL_002f: ldloc.1
IL_0030: ldstr ""!""
IL_0035: call ""string string.Concat(string, string, string)""
IL_003a: call ""void System.Console.WriteLine(string)""
IL_003f: ret
}");
}
[Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")]
public void NoRedundantPropertyRead03()
{
var source = @"using System;
public class Person {
public string Name { get; set; }
}
public class Student : Person { }
public class C {
public void M(Person p) {
switch (p) {
case { Name: ""Bill"" }:
Console.WriteLine(""Hey Bill!"");
break;
case Student { Name: var name }:
Console.WriteLine($""Hello student { name}!"");
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M",
@"{
// Code size 65 (0x41)
.maxstack 3
.locals init (string V_0) //name
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0040
IL_0003: ldarg.1
IL_0004: callvirt ""string Person.Name.get""
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: ldstr ""Bill""
IL_0010: call ""bool string.op_Equality(string, string)""
IL_0015: brtrue.s IL_0020
IL_0017: ldarg.1
IL_0018: isinst ""Student""
IL_001d: brtrue.s IL_002b
IL_001f: ret
IL_0020: ldstr ""Hey Bill!""
IL_0025: call ""void System.Console.WriteLine(string)""
IL_002a: ret
IL_002b: ldstr ""Hello student ""
IL_0030: ldloc.0
IL_0031: ldstr ""!""
IL_0036: call ""string string.Concat(string, string, string)""
IL_003b: call ""void System.Console.WriteLine(string)""
IL_0040: ret
}");
}
[Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")]
public void NoRedundantPropertyRead04()
{
// Cannot combine the evaluations of name here, since we first check if p is Teacher,
// and only if that fails check if p is null.
// Combining the evaluations would mean first checking if p is null, then evaluating name, then checking if p is Teacher.
// This would not necessarily be more performant.
var source = @"using System;
public class Person {
public string Name { get; set; }
}
public class Teacher : Person { }
public class C {
public void M(Person p) {
switch (p) {
case Teacher { Name: var name }:
Console.WriteLine($""Hello teacher { name}!"");
break;
case Person { Name: var name }:
Console.WriteLine($""Hello { name}!"");
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M",
@"{
// Code size 75 (0x4b)
.maxstack 3
.locals init (string V_0, //name
string V_1) //name
IL_0000: ldarg.1
IL_0001: isinst ""Teacher""
IL_0006: brfalse.s IL_0011
IL_0008: ldarg.1
IL_0009: callvirt ""string Person.Name.get""
IL_000e: stloc.0
IL_000f: br.s IL_001d
IL_0011: ldarg.1
IL_0012: brfalse.s IL_004a
IL_0014: ldarg.1
IL_0015: callvirt ""string Person.Name.get""
IL_001a: stloc.0
IL_001b: br.s IL_0033
IL_001d: ldstr ""Hello teacher ""
IL_0022: ldloc.0
IL_0023: ldstr ""!""
IL_0028: call ""string string.Concat(string, string, string)""
IL_002d: call ""void System.Console.WriteLine(string)""
IL_0032: ret
IL_0033: ldloc.0
IL_0034: stloc.1
IL_0035: ldstr ""Hello ""
IL_003a: ldloc.1
IL_003b: ldstr ""!""
IL_0040: call ""string string.Concat(string, string, string)""
IL_0045: call ""void System.Console.WriteLine(string)""
IL_004a: ret
}
");
}
[Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")]
public void NoRedundantPropertyRead05()
{
// Cannot combine the evaluations of name here, since we first check if p is Teacher,
// and only if that fails check if p is Student.
// Combining the evaluations would mean first checking if p is null,
// then evaluating name,
// then checking if p is Teacher,
// then checking if p is Student.
// This would not necessarily be more performant.
var source = @"using System;
public class Person {
public string Name { get; set; }
}
public class Student : Person { }
public class Teacher : Person { }
public class C {
public void M(Person p) {
switch (p) {
case Teacher { Name: var name }:
Console.WriteLine($""Hello teacher { name}!"");
break;
case Student { Name: var name }:
Console.WriteLine($""Hello student { name}!"");
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M",
@"{
// Code size 80 (0x50)
.maxstack 3
.locals init (string V_0, //name
string V_1) //name
IL_0000: ldarg.1
IL_0001: isinst ""Teacher""
IL_0006: brfalse.s IL_0011
IL_0008: ldarg.1
IL_0009: callvirt ""string Person.Name.get""
IL_000e: stloc.0
IL_000f: br.s IL_0022
IL_0011: ldarg.1
IL_0012: isinst ""Student""
IL_0017: brfalse.s IL_004f
IL_0019: ldarg.1
IL_001a: callvirt ""string Person.Name.get""
IL_001f: stloc.0
IL_0020: br.s IL_0038
IL_0022: ldstr ""Hello teacher ""
IL_0027: ldloc.0
IL_0028: ldstr ""!""
IL_002d: call ""string string.Concat(string, string, string)""
IL_0032: call ""void System.Console.WriteLine(string)""
IL_0037: ret
IL_0038: ldloc.0
IL_0039: stloc.1
IL_003a: ldstr ""Hello student ""
IL_003f: ldloc.1
IL_0040: ldstr ""!""
IL_0045: call ""string string.Concat(string, string, string)""
IL_004a: call ""void System.Console.WriteLine(string)""
IL_004f: ret
}
");
}
[Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")]
public void NoRedundantPropertyRead06()
{
var source = @"using System;
public class Person {
public string Name { get; set; }
}
public class Student : Person { }
public class C {
public void M(Person p) {
switch (p) {
case { Name: { Length: 0 } }:
Console.WriteLine(""Hello!"");
break;
case Student { Name: { Length : 1 } }:
Console.WriteLine($""Hello student!"");
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M",
@"{
// Code size 58 (0x3a)
.maxstack 2
.locals init (string V_0,
int V_1)
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0039
IL_0003: ldarg.1
IL_0004: callvirt ""string Person.Name.get""
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_0039
IL_000d: ldloc.0
IL_000e: callvirt ""int string.Length.get""
IL_0013: stloc.1
IL_0014: ldloc.1
IL_0015: brfalse.s IL_0024
IL_0017: ldarg.1
IL_0018: isinst ""Student""
IL_001d: brfalse.s IL_0039
IL_001f: ldloc.1
IL_0020: ldc.i4.1
IL_0021: beq.s IL_002f
IL_0023: ret
IL_0024: ldstr ""Hello!""
IL_0029: call ""void System.Console.WriteLine(string)""
IL_002e: ret
IL_002f: ldstr ""Hello student!""
IL_0034: call ""void System.Console.WriteLine(string)""
IL_0039: ret
}");
}
[Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")]
public void NoRedundantPropertyRead07()
{
// Cannot combine the evaluations of name here, since we first check if name is MemoryStream,
// and only if that fails check if name is null.
// Combining the evaluations would mean first checking if name is null, then evaluating name, then checking if p is Teacher.
// This would not necessarily be more performant.
var source = @"using System;
using System.IO;
public class Person {
public Stream Name { get; set; }
}
public class C {
public void M(Person p) {
switch (p) {
case Person { Name: MemoryStream { Length: 1 } }:
Console.WriteLine(""Your Names A MemoryStream!"");
break;
case Person { Name: { Length : var x } }:
Console.WriteLine(""Your Names A Stream!"");
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M",
@"{
// Code size 66 (0x42)
.maxstack 2
.locals init (System.IO.Stream V_0,
System.IO.MemoryStream V_1)
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0041
IL_0003: ldarg.1
IL_0004: callvirt ""System.IO.Stream Person.Name.get""
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: isinst ""System.IO.MemoryStream""
IL_0010: stloc.1
IL_0011: ldloc.1
IL_0012: brfalse.s IL_0020
IL_0014: ldloc.1
IL_0015: callvirt ""long System.IO.Stream.Length.get""
IL_001a: ldc.i4.1
IL_001b: conv.i8
IL_001c: beq.s IL_002c
IL_001e: br.s IL_0023
IL_0020: ldloc.0
IL_0021: brfalse.s IL_0041
IL_0023: ldloc.0
IL_0024: callvirt ""long System.IO.Stream.Length.get""
IL_0029: pop
IL_002a: br.s IL_0037
IL_002c: ldstr ""Your Names A MemoryStream!""
IL_0031: call ""void System.Console.WriteLine(string)""
IL_0036: ret
IL_0037: ldstr ""Your Names A Stream!""
IL_003c: call ""void System.Console.WriteLine(string)""
IL_0041: ret
}");
}
[Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")]
public void NoRedundantPropertyRead08()
{
var source = @"
public class Person {
public string Name { get; set; }
}
public class Student : Person { }
public class C {
public string M(Person p) {
return p switch {
{ Name: ""Bill"" } => ""Hey Bill!"",
Student { Name: var name } => ""Hello student { name}!"",
_ => null,
};
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M",
@"{
// Code size 51 (0x33)
.maxstack 2
.locals init (string V_0)
IL_0000: ldarg.1
IL_0001: brfalse.s IL_002f
IL_0003: ldarg.1
IL_0004: callvirt ""string Person.Name.get""
IL_0009: ldstr ""Bill""
IL_000e: call ""bool string.op_Equality(string, string)""
IL_0013: brtrue.s IL_001f
IL_0015: ldarg.1
IL_0016: isinst ""Student""
IL_001b: brtrue.s IL_0027
IL_001d: br.s IL_002f
IL_001f: ldstr ""Hey Bill!""
IL_0024: stloc.0
IL_0025: br.s IL_0031
IL_0027: ldstr ""Hello student { name}!""
IL_002c: stloc.0
IL_002d: br.s IL_0031
IL_002f: ldnull
IL_0030: stloc.0
IL_0031: ldloc.0
IL_0032: ret
}");
}
[Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")]
public void NoRedundantPropertyRead09()
{
var source = @"using System;
public class Person {
public virtual string Name { get; set; }
}
public class Student : Person { }
public class C {
public void M(Person p) {
switch (p) {
case { Name: ""Bill"" }:
Console.WriteLine(""Hey Bill!"");
break;
case Student { Name: var name }:
Console.WriteLine($""Hello student { name}!"");
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M",
@"{
// Code size 65 (0x41)
.maxstack 3
.locals init (string V_0) //name
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0040
IL_0003: ldarg.1
IL_0004: callvirt ""string Person.Name.get""
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: ldstr ""Bill""
IL_0010: call ""bool string.op_Equality(string, string)""
IL_0015: brtrue.s IL_0020
IL_0017: ldarg.1
IL_0018: isinst ""Student""
IL_001d: brtrue.s IL_002b
IL_001f: ret
IL_0020: ldstr ""Hey Bill!""
IL_0025: call ""void System.Console.WriteLine(string)""
IL_002a: ret
IL_002b: ldstr ""Hello student ""
IL_0030: ldloc.0
IL_0031: ldstr ""!""
IL_0036: call ""string string.Concat(string, string, string)""
IL_003b: call ""void System.Console.WriteLine(string)""
IL_0040: ret
}");
}
[Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")]
public void NoRedundantPropertyRead10()
{
// Currently we don't combine these redundant property reads.
// However we could do so in the future.
var source = @"using System;
public abstract class Person {
public abstract string Name { get; set; }
}
public class Student : Person {
public override string Name { get; set; }
}
public class C {
public void M(Person p) {
switch (p) {
case { Name: ""Bill"" }:
Console.WriteLine(""Hey Bill!"");
break;
case Student { Name: var name }:
Console.WriteLine($""Hello student { name}!"");
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M",
@"{
// Code size 73 (0x49)
.maxstack 3
.locals init (string V_0, //name
Student V_1)
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0048
IL_0003: ldarg.1
IL_0004: callvirt ""string Person.Name.get""
IL_0009: ldstr ""Bill""
IL_000e: call ""bool string.op_Equality(string, string)""
IL_0013: brtrue.s IL_0028
IL_0015: ldarg.1
IL_0016: isinst ""Student""
IL_001b: stloc.1
IL_001c: ldloc.1
IL_001d: brfalse.s IL_0048
IL_001f: ldloc.1
IL_0020: callvirt ""string Person.Name.get""
IL_0025: stloc.0
IL_0026: br.s IL_0033
IL_0028: ldstr ""Hey Bill!""
IL_002d: call ""void System.Console.WriteLine(string)""
IL_0032: ret
IL_0033: ldstr ""Hello student ""
IL_0038: ldloc.0
IL_0039: ldstr ""!""
IL_003e: call ""string string.Concat(string, string, string)""
IL_0043: call ""void System.Console.WriteLine(string)""
IL_0048: ret
}");
}
[Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")]
public void CombiningRedundantPropertyReadsDoesNotChangeNullabilityAnalysis01()
{
// Currently we don't combine the redundant property reads at all.
// However this could be improved in the future so this test is important
var source = @"using System;
#nullable enable
public class Person {
public virtual string? Name { get; }
}
public class Student : Person {
public override string Name { get => base.Name ?? """"; }
}
public class C {
public void M(Person p) {
switch (p) {
case { Name: ""Bill""}:
Console.WriteLine(""Hey Bill!"");
break;
case Student { Name: var name }:
Console.WriteLine($""Student has name of length { name.Length }!"");
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M",
@"{
// Code size 78 (0x4e)
.maxstack 2
.locals init (string V_0, //name
Student V_1)
IL_0000: ldarg.1
IL_0001: brfalse.s IL_004d
IL_0003: ldarg.1
IL_0004: callvirt ""string Person.Name.get""
IL_0009: ldstr ""Bill""
IL_000e: call ""bool string.op_Equality(string, string)""
IL_0013: brtrue.s IL_0028
IL_0015: ldarg.1
IL_0016: isinst ""Student""
IL_001b: stloc.1
IL_001c: ldloc.1
IL_001d: brfalse.s IL_004d
IL_001f: ldloc.1
IL_0020: callvirt ""string Person.Name.get""
IL_0025: stloc.0
IL_0026: br.s IL_0033
IL_0028: ldstr ""Hey Bill!""
IL_002d: call ""void System.Console.WriteLine(string)""
IL_0032: ret
IL_0033: ldstr ""Student has name of length {0}!""
IL_0038: ldloc.0
IL_0039: callvirt ""int string.Length.get""
IL_003e: box ""int""
IL_0043: call ""string string.Format(string, object)""
IL_0048: call ""void System.Console.WriteLine(string)""
IL_004d: ret
}");
}
[Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")]
public void CombiningRedundantPropertyReadsDoesNotChangeNullabilityAnalysis02()
{
var source = @"using System;
#nullable enable
public class Person {
public string? Name { get;}
}
public class Student : Person {
}
public class C {
public void M(Person p) {
switch (p) {
case { Name: var name } when name is null:
Console.WriteLine($""Hey { name }"");
break;
case Student { Name: var name } when name != null:
Console.WriteLine($""Student has name of length { name.Length }!"");
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M",
@"{
// Code size 75 (0x4b)
.maxstack 2
.locals init (string V_0, //name
string V_1, //name
Person V_2)
IL_0000: ldarg.1
IL_0001: stloc.2
IL_0002: ldloc.2
IL_0003: brfalse.s IL_004a
IL_0005: ldloc.2
IL_0006: callvirt ""string Person.Name.get""
IL_000b: stloc.0
IL_000c: br.s IL_0017
IL_000e: ldloc.2
IL_000f: isinst ""Student""
IL_0014: brtrue.s IL_002b
IL_0016: ret
IL_0017: ldloc.0
IL_0018: brtrue.s IL_000e
IL_001a: ldstr ""Hey ""
IL_001f: ldloc.0
IL_0020: call ""string string.Concat(string, string)""
IL_0025: call ""void System.Console.WriteLine(string)""
IL_002a: ret
IL_002b: ldloc.0
IL_002c: stloc.1
IL_002d: ldloc.1
IL_002e: brfalse.s IL_004a
IL_0030: ldstr ""Student has name of length {0}!""
IL_0035: ldloc.1
IL_0036: callvirt ""int string.Length.get""
IL_003b: box ""int""
IL_0040: call ""string string.Format(string, object)""
IL_0045: call ""void System.Console.WriteLine(string)""
IL_004a: ret
}");
}
[Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")]
public void CombiningRedundantPropertyReadsDoesNotChangeNullabilityAnalysis03()
{
var source = @"using System;
#nullable enable
public class Person {
public string? Name { get; }
}
public class Student : Person {
}
public class C {
public void M(Person p) {
switch (p) {
case { Name: string name }:
Console.WriteLine($""Hey {name}"");
break;
case Student { Name: var name }:
Console.WriteLine($""Student has name of length { name.Length }!"");
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics(
// (19,66): warning CS8602: Dereference of a possibly null reference.
// Console.WriteLine($"Student has name of length { name.Length }!");
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "name").WithLocation(19, 66));
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M",
@"{
// Code size 68 (0x44)
.maxstack 2
.locals init (string V_0, //name
string V_1) //name
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0043
IL_0003: ldarg.1
IL_0004: callvirt ""string Person.Name.get""
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brtrue.s IL_0016
IL_000d: ldarg.1
IL_000e: isinst ""Student""
IL_0013: brtrue.s IL_0027
IL_0015: ret
IL_0016: ldstr ""Hey ""
IL_001b: ldloc.0
IL_001c: call ""string string.Concat(string, string)""
IL_0021: call ""void System.Console.WriteLine(string)""
IL_0026: ret
IL_0027: ldloc.0
IL_0028: stloc.1
IL_0029: ldstr ""Student has name of length {0}!""
IL_002e: ldloc.1
IL_002f: callvirt ""int string.Length.get""
IL_0034: box ""int""
IL_0039: call ""string string.Format(string, object)""
IL_003e: call ""void System.Console.WriteLine(string)""
IL_0043: ret
}");
}
[Fact, WorkItem(34933, "https://github.com/dotnet/roslyn/issues/34933")]
public void DoNotCombineDifferentPropertyReadsWithSameName()
{
var source = @"using System;
public class Person {
public string Name { get; set; }
}
public class Student : Person {
public new string Name { get; set; }
}
public class C {
public void M(Person p) {
switch (p) {
case { Name: ""Bill"" }:
Console.WriteLine(""Hey Bill!"");
break;
case Student { Name: var name }:
Console.WriteLine($""Hello student { name}!"");
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M",
@"{
// Code size 73 (0x49)
.maxstack 3
.locals init (string V_0, //name
Student V_1)
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0048
IL_0003: ldarg.1
IL_0004: callvirt ""string Person.Name.get""
IL_0009: ldstr ""Bill""
IL_000e: call ""bool string.op_Equality(string, string)""
IL_0013: brtrue.s IL_0028
IL_0015: ldarg.1
IL_0016: isinst ""Student""
IL_001b: stloc.1
IL_001c: ldloc.1
IL_001d: brfalse.s IL_0048
IL_001f: ldloc.1
IL_0020: callvirt ""string Student.Name.get""
IL_0025: stloc.0
IL_0026: br.s IL_0033
IL_0028: ldstr ""Hey Bill!""
IL_002d: call ""void System.Console.WriteLine(string)""
IL_0032: ret
IL_0033: ldstr ""Hello student ""
IL_0038: ldloc.0
IL_0039: ldstr ""!""
IL_003e: call ""string string.Concat(string, string, string)""
IL_0043: call ""void System.Console.WriteLine(string)""
IL_0048: ret
}");
}
[Fact, WorkItem(20641, "https://github.com/dotnet/roslyn/issues/20641")]
public void PatternsVsAs01()
{
var source = @"using System.Collections;
using System.Collections.Generic;
class Program
{
static void Main() { }
internal static bool TryGetCount1<T>(IEnumerable<T> source, out int count)
{
ICollection nonGeneric = source as ICollection;
if (nonGeneric != null)
{
count = nonGeneric.Count;
return true;
}
ICollection<T> generic = source as ICollection<T>;
if (generic != null)
{
count = generic.Count;
return true;
}
count = -1;
return false;
}
internal static bool TryGetCount2<T>(IEnumerable<T> source, out int count)
{
switch (source)
{
case ICollection nonGeneric:
count = nonGeneric.Count;
return true;
case ICollection<T> generic:
count = generic.Count;
return true;
default:
count = -1;
return false;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("Program.TryGetCount1<T>",
@"{
// Code size 45 (0x2d)
.maxstack 2
.locals init (System.Collections.ICollection V_0, //nonGeneric
System.Collections.Generic.ICollection<T> V_1) //generic
IL_0000: ldarg.0
IL_0001: isinst ""System.Collections.ICollection""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0014
IL_000a: ldarg.1
IL_000b: ldloc.0
IL_000c: callvirt ""int System.Collections.ICollection.Count.get""
IL_0011: stind.i4
IL_0012: ldc.i4.1
IL_0013: ret
IL_0014: ldarg.0
IL_0015: isinst ""System.Collections.Generic.ICollection<T>""
IL_001a: stloc.1
IL_001b: ldloc.1
IL_001c: brfalse.s IL_0028
IL_001e: ldarg.1
IL_001f: ldloc.1
IL_0020: callvirt ""int System.Collections.Generic.ICollection<T>.Count.get""
IL_0025: stind.i4
IL_0026: ldc.i4.1
IL_0027: ret
IL_0028: ldarg.1
IL_0029: ldc.i4.m1
IL_002a: stind.i4
IL_002b: ldc.i4.0
IL_002c: ret
}");
compVerifier.VerifyIL("Program.TryGetCount2<T>",
@"{
// Code size 47 (0x2f)
.maxstack 2
.locals init (System.Collections.ICollection V_0, //nonGeneric
System.Collections.Generic.ICollection<T> V_1) //generic
IL_0000: ldarg.0
IL_0001: isinst ""System.Collections.ICollection""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brtrue.s IL_0016
IL_000a: ldarg.0
IL_000b: isinst ""System.Collections.Generic.ICollection<T>""
IL_0010: stloc.1
IL_0011: ldloc.1
IL_0012: brtrue.s IL_0020
IL_0014: br.s IL_002a
IL_0016: ldarg.1
IL_0017: ldloc.0
IL_0018: callvirt ""int System.Collections.ICollection.Count.get""
IL_001d: stind.i4
IL_001e: ldc.i4.1
IL_001f: ret
IL_0020: ldarg.1
IL_0021: ldloc.1
IL_0022: callvirt ""int System.Collections.Generic.ICollection<T>.Count.get""
IL_0027: stind.i4
IL_0028: ldc.i4.1
IL_0029: ret
IL_002a: ldarg.1
IL_002b: ldc.i4.m1
IL_002c: stind.i4
IL_002d: ldc.i4.0
IL_002e: ret
}");
}
[Fact, WorkItem(20641, "https://github.com/dotnet/roslyn/issues/20641")]
public void PatternsVsAs02()
{
var source = @"using System.Collections;
class Program
{
static void Main() { }
internal static bool IsEmpty1(IEnumerable source)
{
var c = source as ICollection;
return c != null && c.Count > 0;
}
internal static bool IsEmpty2(IEnumerable source)
{
return source is ICollection c && c.Count > 0;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("Program.IsEmpty1",
@"{
// Code size 22 (0x16)
.maxstack 2
.locals init (System.Collections.ICollection V_0) //c
IL_0000: ldarg.0
IL_0001: isinst ""System.Collections.ICollection""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0014
IL_000a: ldloc.0
IL_000b: callvirt ""int System.Collections.ICollection.Count.get""
IL_0010: ldc.i4.0
IL_0011: cgt
IL_0013: ret
IL_0014: ldc.i4.0
IL_0015: ret
}");
compVerifier.VerifyIL("Program.IsEmpty2",
@"{
// Code size 22 (0x16)
.maxstack 2
.locals init (System.Collections.ICollection V_0) //c
IL_0000: ldarg.0
IL_0001: isinst ""System.Collections.ICollection""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0014
IL_000a: ldloc.0
IL_000b: callvirt ""int System.Collections.ICollection.Count.get""
IL_0010: ldc.i4.0
IL_0011: cgt
IL_0013: ret
IL_0014: ldc.i4.0
IL_0015: ret
}");
}
[Fact]
[WorkItem(20641, "https://github.com/dotnet/roslyn/issues/20641")]
[WorkItem(1395, "https://github.com/dotnet/csharplang/issues/1395")]
public void TupleSwitch01()
{
var source = @"using System;
public class Door
{
public DoorState State;
public enum DoorState { Opened, Closed, Locked }
public enum Action { Open, Close, Lock, Unlock }
public void Act0(Action action, bool haveKey = false)
{
Console.Write($""{State} {action}{(haveKey ? "" withKey"" : null)}"");
State = ChangeState0(State, action, haveKey);
Console.WriteLine($"" -> {State}"");
}
public void Act1(Action action, bool haveKey = false)
{
Console.Write($""{State} {action}{(haveKey ? "" withKey"" : null)}"");
State = ChangeState1(State, action, haveKey);
Console.WriteLine($"" -> {State}"");
}
public static DoorState ChangeState0(DoorState state, Action action, bool haveKey = false)
{
switch (state, action)
{
case (DoorState.Opened, Action.Close):
return DoorState.Closed;
case (DoorState.Closed, Action.Open):
return DoorState.Opened;
case (DoorState.Closed, Action.Lock) when haveKey:
return DoorState.Locked;
case (DoorState.Locked, Action.Unlock) when haveKey:
return DoorState.Closed;
case var (oldState, _):
return oldState;
}
}
public static DoorState ChangeState1(DoorState state, Action action, bool haveKey = false) =>
(state, action) switch {
(DoorState.Opened, Action.Close) => DoorState.Closed,
(DoorState.Closed, Action.Open) => DoorState.Opened,
(DoorState.Closed, Action.Lock) when haveKey => DoorState.Locked,
(DoorState.Locked, Action.Unlock) when haveKey => DoorState.Closed,
_ => state };
}
class Program
{
static void Main(string[] args)
{
var door = new Door();
door.Act0(Door.Action.Close);
door.Act0(Door.Action.Lock);
door.Act0(Door.Action.Lock, true);
door.Act0(Door.Action.Open);
door.Act0(Door.Action.Unlock);
door.Act0(Door.Action.Unlock, true);
door.Act0(Door.Action.Open);
Console.WriteLine();
door = new Door();
door.Act1(Door.Action.Close);
door.Act1(Door.Action.Lock);
door.Act1(Door.Action.Lock, true);
door.Act1(Door.Action.Open);
door.Act1(Door.Action.Unlock);
door.Act1(Door.Action.Unlock, true);
door.Act1(Door.Action.Open);
}
}";
var expectedOutput =
@"Opened Close -> Closed
Closed Lock -> Closed
Closed Lock withKey -> Locked
Locked Open -> Locked
Locked Unlock -> Locked
Locked Unlock withKey -> Closed
Closed Open -> Opened
Opened Close -> Closed
Closed Lock -> Closed
Closed Lock withKey -> Locked
Locked Open -> Locked
Locked Unlock -> Locked
Locked Unlock withKey -> Closed
Closed Open -> Opened
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.RegularWithRecursivePatterns);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("Door.ChangeState0",
@"{
// Code size 61 (0x3d)
.maxstack 2
.locals init (Door.DoorState V_0, //oldState
Door.Action V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldarg.1
IL_0003: stloc.1
IL_0004: ldloc.0
IL_0005: switch (
IL_0018,
IL_001e,
IL_0027)
IL_0016: br.s IL_003b
IL_0018: ldloc.1
IL_0019: ldc.i4.1
IL_001a: beq.s IL_002d
IL_001c: br.s IL_003b
IL_001e: ldloc.1
IL_001f: brfalse.s IL_002f
IL_0021: ldloc.1
IL_0022: ldc.i4.2
IL_0023: beq.s IL_0031
IL_0025: br.s IL_003b
IL_0027: ldloc.1
IL_0028: ldc.i4.3
IL_0029: beq.s IL_0036
IL_002b: br.s IL_003b
IL_002d: ldc.i4.1
IL_002e: ret
IL_002f: ldc.i4.0
IL_0030: ret
IL_0031: ldarg.2
IL_0032: brfalse.s IL_003b
IL_0034: ldc.i4.2
IL_0035: ret
IL_0036: ldarg.2
IL_0037: brfalse.s IL_003b
IL_0039: ldc.i4.1
IL_003a: ret
IL_003b: ldloc.0
IL_003c: ret
}");
compVerifier.VerifyIL("Door.ChangeState1",
@"{
// Code size 71 (0x47)
.maxstack 2
.locals init (Door.DoorState V_0,
Door.DoorState V_1,
Door.Action V_2)
IL_0000: ldarg.0
IL_0001: stloc.1
IL_0002: ldarg.1
IL_0003: stloc.2
IL_0004: ldloc.1
IL_0005: switch (
IL_0018,
IL_001e,
IL_0027)
IL_0016: br.s IL_0043
IL_0018: ldloc.2
IL_0019: ldc.i4.1
IL_001a: beq.s IL_002d
IL_001c: br.s IL_0043
IL_001e: ldloc.2
IL_001f: brfalse.s IL_0031
IL_0021: ldloc.2
IL_0022: ldc.i4.2
IL_0023: beq.s IL_0035
IL_0025: br.s IL_0043
IL_0027: ldloc.2
IL_0028: ldc.i4.3
IL_0029: beq.s IL_003c
IL_002b: br.s IL_0043
IL_002d: ldc.i4.1
IL_002e: stloc.0
IL_002f: br.s IL_0045
IL_0031: ldc.i4.0
IL_0032: stloc.0
IL_0033: br.s IL_0045
IL_0035: ldarg.2
IL_0036: brfalse.s IL_0043
IL_0038: ldc.i4.2
IL_0039: stloc.0
IL_003a: br.s IL_0045
IL_003c: ldarg.2
IL_003d: brfalse.s IL_0043
IL_003f: ldc.i4.1
IL_0040: stloc.0
IL_0041: br.s IL_0045
IL_0043: ldarg.0
IL_0044: stloc.0
IL_0045: ldloc.0
IL_0046: ret
}");
}
[Fact]
[WorkItem(20641, "https://github.com/dotnet/roslyn/issues/20641")]
[WorkItem(1395, "https://github.com/dotnet/csharplang/issues/1395")]
public void SharingTemps01()
{
var source =
@"class Program
{
static void Main(string[] args) { }
void M1(string x)
{
switch (x)
{
case ""a"":
case ""b"" when Mutate(ref x): // prevents sharing temps
case ""c"":
break;
}
}
void M2(string x)
{
switch (x)
{
case ""a"":
case ""b"" when Pure(x):
case ""c"":
break;
}
}
static bool Mutate(ref string x) { x = null; return false; }
static bool Pure(string x) { return false; }
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.RegularWithoutRecursivePatterns);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("Program.M1",
@"{
// Code size 50 (0x32)
.maxstack 2
.locals init (string V_0)
IL_0000: ldarg.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldstr ""a""
IL_0008: call ""bool string.op_Equality(string, string)""
IL_000d: brtrue.s IL_0031
IL_000f: ldloc.0
IL_0010: ldstr ""b""
IL_0015: call ""bool string.op_Equality(string, string)""
IL_001a: brtrue.s IL_0029
IL_001c: ldloc.0
IL_001d: ldstr ""c""
IL_0022: call ""bool string.op_Equality(string, string)""
IL_0027: pop
IL_0028: ret
IL_0029: ldarga.s V_1
IL_002b: call ""bool Program.Mutate(ref string)""
IL_0030: pop
IL_0031: ret
}");
compVerifier.VerifyIL("Program.M2",
@"{
// Code size 49 (0x31)
.maxstack 2
.locals init (string V_0)
IL_0000: ldarg.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldstr ""a""
IL_0008: call ""bool string.op_Equality(string, string)""
IL_000d: brtrue.s IL_0030
IL_000f: ldloc.0
IL_0010: ldstr ""b""
IL_0015: call ""bool string.op_Equality(string, string)""
IL_001a: brtrue.s IL_0029
IL_001c: ldloc.0
IL_001d: ldstr ""c""
IL_0022: call ""bool string.op_Equality(string, string)""
IL_0027: pop
IL_0028: ret
IL_0029: ldarg.1
IL_002a: call ""bool Program.Pure(string)""
IL_002f: pop
IL_0030: ret
}");
}
[Fact, WorkItem(17266, "https://github.com/dotnet/roslyn/issues/17266")]
public void IrrefutablePatternInIs01()
{
var source =
@"using System;
public class C
{
public static void Main()
{
if (Get() is int index) { }
Console.WriteLine(index);
}
public static int Get()
{
Console.WriteLine(""eval"");
return 1;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics();
var expectedOutput = @"eval
1";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact, WorkItem(17266, "https://github.com/dotnet/roslyn/issues/17266")]
public void IrrefutablePatternInIs02()
{
var source =
@"using System;
public class C
{
public static void Main()
{
if (Get() is Assignment(int left, var right)) { }
Console.WriteLine(left);
Console.WriteLine(right);
}
public static Assignment Get()
{
Console.WriteLine(""eval"");
return new Assignment(1, 2);
}
}
public struct Assignment
{
public int Left, Right;
public Assignment(int left, int right) => (Left, Right) = (left, right);
public void Deconstruct(out int left, out int right) => (left, right) = (Left, Right);
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithRecursivePatterns);
compilation.VerifyDiagnostics();
var expectedOutput = @"eval
1
2";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void MissingNullCheck01()
{
var source =
@"class Program
{
public static void Main()
{
string s = null;
System.Console.WriteLine(s is string { Length: 3 });
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithRecursivePatterns);
compilation.VerifyDiagnostics();
var expectedOutput = @"False";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
[WorkItem(24550, "https://github.com/dotnet/roslyn/issues/24550")]
[WorkItem(1284, "https://github.com/dotnet/csharplang/issues/1284")]
public void ConstantPatternVsUnconstrainedTypeParameter01()
{
var source =
@"using System;
class Program
{
static void Main()
{
Console.WriteLine(Test1<object>(null));
Console.WriteLine(Test1<int>(1));
Console.WriteLine(Test1<int?>(null));
Console.WriteLine(Test1<int?>(1));
Console.WriteLine(Test2<object>(0));
Console.WriteLine(Test2<int>(1));
Console.WriteLine(Test2<int?>(0));
Console.WriteLine(Test2<string>(""frog""));
Console.WriteLine(Test3<object>(""frog""));
Console.WriteLine(Test3<int>(1));
Console.WriteLine(Test3<string>(""frog""));
Console.WriteLine(Test3<int?>(1));
}
public static bool Test1<T>(T t)
{
return t is null;
}
public static bool Test2<T>(T t)
{
return t is 0;
}
public static bool Test3<T>(T t)
{
return t is ""frog"";
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
var expectedOutput =
@"True
False
True
False
True
False
True
False
True
False
True
False
";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("Program.Test1<T>(T)",
@"{
// Code size 10 (0xa)
.maxstack 2
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: ldnull
IL_0007: ceq
IL_0009: ret
}");
compVerifier.VerifyIL("Program.Test2<T>(T)",
@"{
// Code size 35 (0x23)
.maxstack 2
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: isinst ""int""
IL_000b: brfalse.s IL_0021
IL_000d: ldarg.0
IL_000e: box ""T""
IL_0013: isinst ""int""
IL_0018: unbox.any ""int""
IL_001d: ldc.i4.0
IL_001e: ceq
IL_0020: ret
IL_0021: ldc.i4.0
IL_0022: ret
}
");
compVerifier.VerifyIL("Program.Test3<T>(T)",
@"{
// Code size 29 (0x1d)
.maxstack 2
.locals init (string V_0)
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: isinst ""string""
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: brfalse.s IL_001b
IL_000f: ldloc.0
IL_0010: ldstr ""frog""
IL_0015: call ""bool string.op_Equality(string, string)""
IL_001a: ret
IL_001b: ldc.i4.0
IL_001c: ret
}");
}
[Fact]
[WorkItem(24550, "https://github.com/dotnet/roslyn/issues/24550")]
[WorkItem(1284, "https://github.com/dotnet/csharplang/issues/1284")]
public void ConstantPatternVsUnconstrainedTypeParameter02()
{
var source =
@"class C<T>
{
internal struct S { }
static bool Test(S s)
{
return s is 1;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C<T>.Test(C<T>.S)",
@"{
// Code size 35 (0x23)
.maxstack 2
IL_0000: ldarg.0
IL_0001: box ""C<T>.S""
IL_0006: isinst ""int""
IL_000b: brfalse.s IL_0021
IL_000d: ldarg.0
IL_000e: box ""C<T>.S""
IL_0013: isinst ""int""
IL_0018: unbox.any ""int""
IL_001d: ldc.i4.1
IL_001e: ceq
IL_0020: ret
IL_0021: ldc.i4.0
IL_0022: ret
}
");
}
[Fact]
[WorkItem(26274, "https://github.com/dotnet/roslyn/issues/26274")]
public void VariablesInSwitchExpressionArms()
{
var source =
@"class C
{
public override bool Equals(object obj) =>
obj switch
{
C x1 when x1 is var x2 => x2 is var x3 && x3 is {},
_ => false
};
public override int GetHashCode() => 1;
public static void Main()
{
C c = new C();
System.Console.Write(c.Equals(new C()));
System.Console.Write(c.Equals(new object()));
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation, expectedOutput: "TrueFalse");
compVerifier.VerifyIL("C.Equals(object)",
@"{
// Code size 25 (0x19)
.maxstack 2
.locals init (C V_0, //x1
C V_1, //x2
C V_2, //x3
bool V_3)
IL_0000: ldarg.1
IL_0001: isinst ""C""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0015
IL_000a: ldloc.0
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: stloc.2
IL_000e: ldloc.2
IL_000f: ldnull
IL_0010: cgt.un
IL_0012: stloc.3
IL_0013: br.s IL_0017
IL_0015: ldc.i4.0
IL_0016: stloc.3
IL_0017: ldloc.3
IL_0018: ret
}");
}
[Fact, WorkItem(26387, "https://github.com/dotnet/roslyn/issues/26387")]
public void ValueTypeArgument01()
{
var source =
@"using System;
class TestHelper
{
static void Main()
{
Console.WriteLine(IsValueTypeT0(new S()));
Console.WriteLine(IsValueTypeT1(new S()));
Console.WriteLine(IsValueTypeT2(new S()));
}
static bool IsValueTypeT0<T>(T result)
{
return result is T;
}
static bool IsValueTypeT1<T>(T result)
{
return result is T v;
}
static bool IsValueTypeT2<T>(T result)
{
return result is T _;
}
}
struct S { }
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics();
var expectedOutput =
@"True
True
True";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("TestHelper.IsValueTypeT0<T>(T)",
@"{
// Code size 15 (0xf)
.maxstack 2
.locals init (bool V_0)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: box ""T""
IL_0007: ldnull
IL_0008: cgt.un
IL_000a: stloc.0
IL_000b: br.s IL_000d
IL_000d: ldloc.0
IL_000e: ret
}");
compVerifier.VerifyIL("TestHelper.IsValueTypeT1<T>(T)",
@"{
// Code size 20 (0x14)
.maxstack 1
.locals init (T V_0, //v
bool V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: box ""T""
IL_0007: brfalse.s IL_000e
IL_0009: ldarg.0
IL_000a: stloc.0
IL_000b: ldc.i4.1
IL_000c: br.s IL_000f
IL_000e: ldc.i4.0
IL_000f: stloc.1
IL_0010: br.s IL_0012
IL_0012: ldloc.1
IL_0013: ret
}");
compVerifier.VerifyIL("TestHelper.IsValueTypeT2<T>(T)",
@"{
// Code size 15 (0xf)
.maxstack 2
.locals init (bool V_0)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: box ""T""
IL_0007: ldnull
IL_0008: cgt.un
IL_000a: stloc.0
IL_000b: br.s IL_000d
IL_000d: ldloc.0
IL_000e: ret
}");
}
[Fact, WorkItem(26387, "https://github.com/dotnet/roslyn/issues/26387")]
public void ValueTypeArgument02()
{
var source =
@"namespace ConsoleApp1
{
public class TestHelper
{
public static void Main()
{
IsValueTypeT(new Result<(Cls, IInt)>((new Cls(), new Int())));
System.Console.WriteLine(""done"");
}
public static void IsValueTypeT<T>(Result<T> result)
{
if (!(result.Value is T v))
throw new NotPossibleException();
}
}
public class Result<T>
{
public T Value { get; }
public Result(T value)
{
Value = value;
}
}
public class Cls { }
public interface IInt { }
public class Int : IInt { }
public class NotPossibleException : System.Exception { }
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics();
var expectedOutput =
@"done";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("ConsoleApp1.TestHelper.IsValueTypeT<T>(ConsoleApp1.Result<T>)",
@"{
// Code size 31 (0x1f)
.maxstack 2
.locals init (T V_0, //v
bool V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: callvirt ""T ConsoleApp1.Result<T>.Value.get""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: box ""T""
IL_000e: ldnull
IL_000f: cgt.un
IL_0011: ldc.i4.0
IL_0012: ceq
IL_0014: stloc.1
IL_0015: ldloc.1
IL_0016: brfalse.s IL_001e
IL_0018: newobj ""ConsoleApp1.NotPossibleException..ctor()""
IL_001d: throw
IL_001e: ret
}");
}
[Fact]
public void DeconstructNullableTuple_01()
{
var source =
@"
class C {
static int i = 3;
static (int,int)? GetNullableTuple() => (i++, i++);
static void Main() {
if (GetNullableTuple() is (int x1, int y1) tupl1)
{
System.Console.WriteLine($""x = {x1}, y = {y1}"");
}
if (GetNullableTuple() is (int x2, int y2) _)
{
System.Console.WriteLine($""x = {x2}, y = {y2}"");
}
switch (GetNullableTuple())
{
case (int x3, int y3) s:
System.Console.WriteLine($""x = {x3}, y = {y3}"");
break;
}
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics();
var expectedOutput = @"x = 3, y = 4
x = 5, y = 6
x = 7, y = 8";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void DeconstructNullable_01()
{
var source =
@"
class C {
static int i = 3;
static S? GetNullableTuple() => new S(i++, i++);
static void Main() {
if (GetNullableTuple() is (int x1, int y1) tupl1)
{
System.Console.WriteLine($""x = {x1}, y = {y1}"");
}
if (GetNullableTuple() is (int x2, int y2) _)
{
System.Console.WriteLine($""x = {x2}, y = {y2}"");
}
switch (GetNullableTuple())
{
case (int x3, int y3) s:
System.Console.WriteLine($""x = {x3}, y = {y3}"");
break;
}
}
}
struct S
{
int x, y;
public S(int X, int Y) => (this.x, this.y) = (X, Y);
public void Deconstruct(out int X, out int Y) => (X, Y) = (x, y);
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics();
var expectedOutput = @"x = 3, y = 4
x = 5, y = 6
x = 7, y = 8";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact, WorkItem(28632, "https://github.com/dotnet/roslyn/issues/28632")]
public void UnboxNullableInRecursivePattern01()
{
var source =
@"
static class Program
{
public static int M1(int? x)
{
return x is int y ? y : 1;
}
public static int M2(int? x)
{
return x is { } y ? y : 2;
}
public static void Main()
{
System.Console.WriteLine(M1(null));
System.Console.WriteLine(M2(null));
System.Console.WriteLine(M1(3));
System.Console.WriteLine(M2(4));
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
var expectedOutput =
@"1
2
3
4";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("Program.M1",
@"{
// Code size 23 (0x17)
.maxstack 1
.locals init (int V_0) //y
IL_0000: ldarga.s V_0
IL_0002: call ""bool int?.HasValue.get""
IL_0007: brfalse.s IL_0013
IL_0009: ldarga.s V_0
IL_000b: call ""int int?.GetValueOrDefault()""
IL_0010: stloc.0
IL_0011: br.s IL_0015
IL_0013: ldc.i4.1
IL_0014: ret
IL_0015: ldloc.0
IL_0016: ret
}");
compVerifier.VerifyIL("Program.M2",
@"{
// Code size 23 (0x17)
.maxstack 1
.locals init (int V_0) //y
IL_0000: ldarga.s V_0
IL_0002: call ""bool int?.HasValue.get""
IL_0007: brfalse.s IL_0013
IL_0009: ldarga.s V_0
IL_000b: call ""int int?.GetValueOrDefault()""
IL_0010: stloc.0
IL_0011: br.s IL_0015
IL_0013: ldc.i4.2
IL_0014: ret
IL_0015: ldloc.0
IL_0016: ret
}");
}
[Fact]
public void DoNotShareInputForMutatingWhenClause()
{
var source =
@"using System;
class Program
{
static void Main()
{
Console.Write(M1(1));
Console.Write(M2(1));
Console.Write(M3(1));
Console.Write(M4(1));
Console.Write(M5(1));
Console.Write(M6(1));
Console.Write(M7(1));
Console.Write(M8(1));
Console.Write(M9(1));
}
public static int M1(int x)
{
return x switch { _ when (++x) == 5 => 1, 1 => 2, _ => 3 };
}
public static int M2(int x)
{
return x switch { _ when (x+=1) == 5 => 1, 1 => 2, _ => 3 };
}
public static int M3(int x)
{
return x switch { _ when ((x, _) = (5, 6)) == (0, 0) => 1, 1 => 2, _ => 3 };
}
public static int M4(int x)
{
dynamic d = new Program();
return x switch { _ when d.M(ref x) => 1, 1 => 2, _ => 3 };
}
bool M(ref int x) { x = 100; return false; }
public static int M5(int x)
{
return x switch { _ when new Program(ref x).P => 1, 1 => 2, _ => 3 };
}
public static int M6(int x)
{
dynamic d = x;
return x switch { _ when new Program(d, ref x).P => 1, 1 => 2, _ => 3 };
}
public static int M7(int x)
{
return x switch { _ when new Program(ref x).P && new Program().P => 1, 1 => 2, _ => 3 };
}
public static int M8(int x)
{
dynamic d = x;
return x switch { _ when new Program(d, ref x).P && new Program().P => 1, 1 => 2, _ => 3 };
}
public static int M9(int x)
{
return x switch { _ when (x=100) == 1 => 1, 1 => 2, _ => 3 };
}
Program() { }
Program(ref int x) { x = 100; }
Program(int a, ref int x) { x = 100; }
bool P => false;
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, references: new[] { CSharpRef });
compilation.VerifyDiagnostics();
var expectedOutput = @"222222222";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void GenerateStringHashOnlyOnce()
{
var source =
@"using System;
class Program
{
static void Main()
{
Console.Write(M1(string.Empty));
Console.Write(M2(string.Empty));
}
public static int M1(string s)
{
return s switch { ""a""=>1, ""b""=>2, ""c""=>3, ""d""=>4, ""e""=>5, ""f""=>6, ""g""=>7, ""h""=>8, _ => 9 };
}
public static int M2(string s)
{
return s switch { ""a""=>1, ""b""=>2, ""c""=>3, ""d""=>4, ""e""=>5, ""f""=>6, ""g""=>7, ""h""=>8, _ => 9 };
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
var expectedOutput = @"99";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void BindVariablesInWhenClause()
{
var source =
@"using System;
class Program
{
static void Main()
{
var t = (1, 2);
switch (t)
{
case var (x, y) when x+1 == y:
Console.Write(1);
break;
}
Console.Write(t switch
{
var (x, y) when x+1 == y => 1,
_ => 2
});
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
var expectedOutput = @"11";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void MissingExceptions_01()
{
var source = @"namespace System {
public class Object { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Int32 { }
}
static class C {
public static bool M(int i) => i switch { 1 => true };
}
";
var compilation = CreateEmptyCompilation(source, options: TestOptions.ReleaseDll);
compilation.GetDiagnostics().Verify(
// (9,38): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '0' is not covered.
// public static bool M(int i) => i switch { 1 => true };
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("0").WithLocation(9, 38)
);
compilation.GetEmitDiagnostics().Verify(
// warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options.
Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1),
// (9,36): error CS0656: Missing compiler required member 'System.InvalidOperationException..ctor'
// public static bool M(int i) => i switch { 1 => true };
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "i switch { 1 => true }").WithArguments("System.InvalidOperationException", ".ctor").WithLocation(9, 36),
// (9,38): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '0' is not covered.
// public static bool M(int i) => i switch { 1 => true };
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("0").WithLocation(9, 38)
);
}
[Fact, WorkItem(32774, "https://github.com/dotnet/roslyn/issues/32774")]
public void BadCode_32774()
{
var source = @"
public class Class1
{
static void Main()
{
System.Console.WriteLine(SwitchCaseThatFails(12.123));
}
public static bool SwitchCaseThatFails(object someObject)
{
switch (someObject)
{
case IObject x when x.SubObject != null:
return false;
case IOtherObject x:
return false;
case double x:
return true;
default:
return false;
}
}
public interface IObject
{
IObject SubObject { get; }
}
public interface IOtherObject { }
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics();
var expectedOutput = @"True";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("Class1.SwitchCaseThatFails",
@"{
// Code size 97 (0x61)
.maxstack 1
.locals init (Class1.IObject V_0, //x
Class1.IOtherObject V_1, //x
double V_2, //x
object V_3,
object V_4,
bool V_5)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.s V_4
IL_0004: ldloc.s V_4
IL_0006: stloc.3
IL_0007: ldloc.3
IL_0008: isinst ""Class1.IObject""
IL_000d: stloc.0
IL_000e: ldloc.0
IL_000f: brtrue.s IL_003c
IL_0011: br.s IL_001f
IL_0013: ldloc.3
IL_0014: isinst ""Class1.IOtherObject""
IL_0019: stloc.1
IL_001a: ldloc.1
IL_001b: brtrue.s IL_004b
IL_001d: br.s IL_0059
IL_001f: ldloc.3
IL_0020: isinst ""Class1.IOtherObject""
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: brtrue.s IL_004b
IL_0029: br.s IL_002b
IL_002b: ldloc.3
IL_002c: isinst ""double""
IL_0031: brfalse.s IL_0059
IL_0033: ldloc.3
IL_0034: unbox.any ""double""
IL_0039: stloc.2
IL_003a: br.s IL_0052
IL_003c: ldloc.0
IL_003d: callvirt ""Class1.IObject Class1.IObject.SubObject.get""
IL_0042: brtrue.s IL_0046
IL_0044: br.s IL_0013
IL_0046: ldc.i4.0
IL_0047: stloc.s V_5
IL_0049: br.s IL_005e
IL_004b: br.s IL_004d
IL_004d: ldc.i4.0
IL_004e: stloc.s V_5
IL_0050: br.s IL_005e
IL_0052: br.s IL_0054
IL_0054: ldc.i4.1
IL_0055: stloc.s V_5
IL_0057: br.s IL_005e
IL_0059: ldc.i4.0
IL_005a: stloc.s V_5
IL_005c: br.s IL_005e
IL_005e: ldloc.s V_5
IL_0060: ret
}");
}
// Possible test helper bug on Linux; see https://github.com/dotnet/roslyn/issues/33356
[ConditionalFact(typeof(WindowsOnly))]
public void SwitchExpressionSequencePoints()
{
string source = @"
public class Program
{
public static void Main()
{
int i = 0;
var y = (i switch
{
0 => new Program(),
1 => new Program(),
_ => new Program(),
}).Chain();
y.Chain2();
}
public Program Chain() => this;
public Program Chain2() => this;
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugExe);
v.VerifyIL(qualifiedMethodName: "Program.Main", @"
{
// Code size 61 (0x3d)
.maxstack 2
.locals init (int V_0, //i
Program V_1, //y
Program V_2)
// sequence point: {
IL_0000: nop
// sequence point: int i = 0;
IL_0001: ldc.i4.0
IL_0002: stloc.0
// sequence point: var y = (i s ... }).Chain()
IL_0003: ldc.i4.1
IL_0004: brtrue.s IL_0007
// sequence point: switch ... }
IL_0006: nop
// sequence point: <hidden>
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0012
IL_000a: br.s IL_000c
IL_000c: ldloc.0
IL_000d: ldc.i4.1
IL_000e: beq.s IL_001a
IL_0010: br.s IL_0022
// sequence point: new Program()
IL_0012: newobj ""Program..ctor()""
IL_0017: stloc.2
IL_0018: br.s IL_002a
// sequence point: new Program()
IL_001a: newobj ""Program..ctor()""
IL_001f: stloc.2
IL_0020: br.s IL_002a
// sequence point: new Program()
IL_0022: newobj ""Program..ctor()""
IL_0027: stloc.2
IL_0028: br.s IL_002a
// sequence point: <hidden>
IL_002a: ldc.i4.1
IL_002b: brtrue.s IL_002e
// sequence point: var y = (i s ... }).Chain()
IL_002d: nop
// sequence point: <hidden>
IL_002e: ldloc.2
IL_002f: callvirt ""Program Program.Chain()""
IL_0034: stloc.1
// sequence point: y.Chain2();
IL_0035: ldloc.1
IL_0036: callvirt ""Program Program.Chain2()""
IL_003b: pop
// sequence point: }
IL_003c: ret
}
", sequencePoints: "Program.Main", source: source);
}
[Fact, WorkItem(33675, "https://github.com/dotnet/roslyn/issues/33675")]
public void ParsingParenthesizedExpressionAsPatternOfExpressionSwitch()
{
var source = @"
public class Class1
{
static void Main()
{
System.Console.Write(M(42));
System.Console.Write(M(41));
}
static bool M(object o)
{
const int X = 42;
return o switch { (X) => true, _ => false };
}
}";
foreach (var options in new[] { TestOptions.DebugExe, TestOptions.ReleaseExe })
{
var compilation = CreateCompilation(source, options: options);
compilation.VerifyDiagnostics();
var expectedOutput = @"TrueFalse";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
if (options.OptimizationLevel == OptimizationLevel.Debug)
{
compVerifier.VerifyIL("Class1.M", @"
{
// Code size 45 (0x2d)
.maxstack 2
.locals init (bool V_0,
int V_1,
bool V_2)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: brtrue.s IL_0005
IL_0004: nop
IL_0005: ldarg.0
IL_0006: isinst ""int""
IL_000b: brfalse.s IL_001f
IL_000d: ldarg.0
IL_000e: unbox.any ""int""
IL_0013: stloc.1
IL_0014: ldloc.1
IL_0015: ldc.i4.s 42
IL_0017: beq.s IL_001b
IL_0019: br.s IL_001f
IL_001b: ldc.i4.1
IL_001c: stloc.0
IL_001d: br.s IL_0023
IL_001f: ldc.i4.0
IL_0020: stloc.0
IL_0021: br.s IL_0023
IL_0023: ldc.i4.1
IL_0024: brtrue.s IL_0027
IL_0026: nop
IL_0027: ldloc.0
IL_0028: stloc.2
IL_0029: br.s IL_002b
IL_002b: ldloc.2
IL_002c: ret
}
");
}
else
{
compVerifier.VerifyIL("Class1.M",
@"{
// Code size 26 (0x1a)
.maxstack 2
.locals init (bool V_0)
IL_0000: ldarg.0
IL_0001: isinst ""int""
IL_0006: brfalse.s IL_0016
IL_0008: ldarg.0
IL_0009: unbox.any ""int""
IL_000e: ldc.i4.s 42
IL_0010: bne.un.s IL_0016
IL_0012: ldc.i4.1
IL_0013: stloc.0
IL_0014: br.s IL_0018
IL_0016: ldc.i4.0
IL_0017: stloc.0
IL_0018: ldloc.0
IL_0019: ret
}");
}
}
}
[Fact, WorkItem(35584, "https://github.com/dotnet/roslyn/issues/35584")]
public void MatchToTypeParameterUnbox_01()
{
var source = @"
class Program
{
public static void Main() => System.Console.WriteLine(P<int>(0));
public static string P<T>(T t) => (t is object o) ? o.ToString() : string.Empty;
}
";
var expectedOutput = @"0";
foreach (var options in new[] { TestOptions.DebugExe, TestOptions.ReleaseExe })
{
var compilation = CreateCompilation(source, options: options);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
if (options.OptimizationLevel == OptimizationLevel.Debug)
{
compVerifier.VerifyIL("Program.P<T>",
@"{
// Code size 24 (0x18)
.maxstack 1
.locals init (object V_0) //o
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brtrue.s IL_0011
IL_000a: ldsfld ""string string.Empty""
IL_000f: br.s IL_0017
IL_0011: ldloc.0
IL_0012: callvirt ""string object.ToString()""
IL_0017: ret
}
");
}
else
{
compVerifier.VerifyIL("Program.P<T>",
@"{
// Code size 23 (0x17)
.maxstack 1
.locals init (object V_0) //o
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brtrue.s IL_0010
IL_000a: ldsfld ""string string.Empty""
IL_000f: ret
IL_0010: ldloc.0
IL_0011: callvirt ""string object.ToString()""
IL_0016: ret
}
");
}
}
}
[Fact, WorkItem(35584, "https://github.com/dotnet/roslyn/issues/35584")]
public void MatchToTypeParameterUnbox_02()
{
var source =
@"using System;
class Program
{
public static void Main()
{
var generic = new Generic<int>(0);
}
}
public class Generic<T>
{
public Generic(T value)
{
if (value is object obj && obj == null)
{
throw new Exception(""Kaboom!"");
}
}
}
";
var expectedOutput = @"";
foreach (var options in new[] { TestOptions.DebugExe, TestOptions.ReleaseExe })
{
var compilation = CreateCompilation(source, options: options);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
if (options.OptimizationLevel == OptimizationLevel.Debug)
{
compVerifier.VerifyIL("Generic<T>..ctor(T)",
@"{
// Code size 42 (0x2a)
.maxstack 2
.locals init (object V_0, //obj
bool V_1)
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: nop
IL_0007: nop
IL_0008: ldarg.1
IL_0009: box ""T""
IL_000e: stloc.0
IL_000f: ldloc.0
IL_0010: brfalse.s IL_0018
IL_0012: ldloc.0
IL_0013: ldnull
IL_0014: ceq
IL_0016: br.s IL_0019
IL_0018: ldc.i4.0
IL_0019: stloc.1
IL_001a: ldloc.1
IL_001b: brfalse.s IL_0029
IL_001d: nop
IL_001e: ldstr ""Kaboom!""
IL_0023: newobj ""System.Exception..ctor(string)""
IL_0028: throw
IL_0029: ret
}
");
}
else
{
compVerifier.VerifyIL("Generic<T>..ctor(T)",
@"{
// Code size 31 (0x1f)
.maxstack 1
.locals init (object V_0) //obj
IL_0000: ldarg.0
IL_0001: call ""object..ctor()""
IL_0006: ldarg.1
IL_0007: box ""T""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: brfalse.s IL_001e
IL_0010: ldloc.0
IL_0011: brtrue.s IL_001e
IL_0013: ldstr ""Kaboom!""
IL_0018: newobj ""System.Exception..ctor(string)""
IL_001d: throw
IL_001e: ret
}
");
}
}
}
[Fact, WorkItem(35584, "https://github.com/dotnet/roslyn/issues/35584")]
public void MatchToTypeParameterUnbox_03()
{
var source =
@"using System;
class Program
{
public static void Main() => System.Console.WriteLine(P<Enum>(null));
public static string P<T>(T t) where T: Enum => (t is ValueType o) ? o.ToString() : ""1"";
}
";
var expectedOutput = @"1";
foreach (var options in new[] { TestOptions.DebugExe, TestOptions.ReleaseExe })
{
var compilation = CreateCompilation(source, options: options);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
if (options.OptimizationLevel == OptimizationLevel.Debug)
{
compVerifier.VerifyIL("Program.P<T>",
@"{
// Code size 24 (0x18)
.maxstack 1
.locals init (System.ValueType V_0) //o
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brtrue.s IL_0011
IL_000a: ldstr ""1""
IL_000f: br.s IL_0017
IL_0011: ldloc.0
IL_0012: callvirt ""string object.ToString()""
IL_0017: ret
}
");
}
else
{
compVerifier.VerifyIL("Program.P<T>",
@"{
// Code size 23 (0x17)
.maxstack 1
.locals init (System.ValueType V_0) //o
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brtrue.s IL_0010
IL_000a: ldstr ""1""
IL_000f: ret
IL_0010: ldloc.0
IL_0011: callvirt ""string object.ToString()""
IL_0016: ret
}
");
}
}
}
[Fact]
public void CompileTimeRuntimeInstanceofMismatch_01()
{
var source =
@"using System;
class Program
{
static void Main()
{
M(new byte[1]);
M(new sbyte[1]);
M(new Ebyte[1]);
M(new Esbyte[1]);
M(new short[1]);
M(new ushort[1]);
M(new Eshort[1]);
M(new Eushort[1]);
M(new int[1]);
M(new uint[1]);
M(new Eint[1]);
M(new Euint[1]);
M(new int[1][]);
M(new uint[1][]);
M(new Eint[1][]);
M(new Euint[1][]);
M(new long[1]);
M(new ulong[1]);
M(new Elong[1]);
M(new Eulong[1]);
M(new IntPtr[1]);
M(new UIntPtr[1]);
M(new IntPtr[1][]);
M(new UIntPtr[1][]);
}
static void M(object o)
{
switch (o)
{
case byte[] _ when o.GetType() == typeof(byte[]):
Console.WriteLine(""byte[]"");
break;
case sbyte[] _ when o.GetType() == typeof(sbyte[]):
Console.WriteLine(""sbyte[]"");
break;
case Ebyte[] _ when o.GetType() == typeof(Ebyte[]):
Console.WriteLine(""Ebyte[]"");
break;
case Esbyte[] _ when o.GetType() == typeof(Esbyte[]):
Console.WriteLine(""Esbyte[]"");
break;
case short[] _ when o.GetType() == typeof(short[]):
Console.WriteLine(""short[]"");
break;
case ushort[] _ when o.GetType() == typeof(ushort[]):
Console.WriteLine(""ushort[]"");
break;
case Eshort[] _ when o.GetType() == typeof(Eshort[]):
Console.WriteLine(""Eshort[]"");
break;
case Eushort[] _ when o.GetType() == typeof(Eushort[]):
Console.WriteLine(""Eushort[]"");
break;
case int[] _ when o.GetType() == typeof(int[]):
Console.WriteLine(""int[]"");
break;
case uint[] _ when o.GetType() == typeof(uint[]):
Console.WriteLine(""uint[]"");
break;
case Eint[] _ when o.GetType() == typeof(Eint[]):
Console.WriteLine(""Eint[]"");
break;
case Euint[] _ when o.GetType() == typeof(Euint[]):
Console.WriteLine(""Euint[]"");
break;
case int[][] _ when o.GetType() == typeof(int[][]):
Console.WriteLine(""int[][]"");
break;
case uint[][] _ when o.GetType() == typeof(uint[][]):
Console.WriteLine(""uint[][]"");
break;
case Eint[][] _ when o.GetType() == typeof(Eint[][]):
Console.WriteLine(""Eint[][]"");
break;
case Euint[][] _ when o.GetType() == typeof(Euint[][]):
Console.WriteLine(""Euint[][]"");
break;
case long[] _ when o.GetType() == typeof(long[]):
Console.WriteLine(""long[]"");
break;
case ulong[] _ when o.GetType() == typeof(ulong[]):
Console.WriteLine(""ulong[]"");
break;
case Elong[] _ when o.GetType() == typeof(Elong[]):
Console.WriteLine(""Elong[]"");
break;
case Eulong[] _ when o.GetType() == typeof(Eulong[]):
Console.WriteLine(""Eulong[]"");
break;
case IntPtr[] _ when o.GetType() == typeof(IntPtr[]):
Console.WriteLine(""IntPtr[]"");
break;
case UIntPtr[] _ when o.GetType() == typeof(UIntPtr[]):
Console.WriteLine(""UIntPtr[]"");
break;
case IntPtr[][] _ when o.GetType() == typeof(IntPtr[][]):
Console.WriteLine(""IntPtr[][]"");
break;
case UIntPtr[][] _ when o.GetType() == typeof(UIntPtr[][]):
Console.WriteLine(""UIntPtr[][]"");
break;
default:
Console.WriteLine(""oops: "" + o.GetType());
break;
}
}
}
enum Ebyte : byte {}
enum Esbyte : sbyte {}
enum Eshort : short {}
enum Eushort : ushort {}
enum Eint : int {}
enum Euint : uint {}
enum Elong : long {}
enum Eulong : ulong {}
";
var expectedOutput =
@"byte[]
sbyte[]
Ebyte[]
Esbyte[]
short[]
ushort[]
Eshort[]
Eushort[]
int[]
uint[]
Eint[]
Euint[]
int[][]
uint[][]
Eint[][]
Euint[][]
long[]
ulong[]
Elong[]
Eulong[]
IntPtr[]
UIntPtr[]
IntPtr[][]
UIntPtr[][]
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: expectedOutput);
compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void CompileTimeRuntimeInstanceofMismatch_02()
{
var source =
@"using System;
class Program
{
static void Main()
{
M(new byte[1]);
M(new sbyte[1]);
}
static void M(object o)
{
switch (o)
{
case byte[] _:
Console.WriteLine(""byte[]"");
break;
case sbyte[] _: // not subsumed, even though it will never occur due to CLR behavior
Console.WriteLine(""sbyte[]"");
break;
}
}
}
";
var expectedOutput =
@"byte[]
byte[]
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: expectedOutput);
compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
[WorkItem(36496, "https://github.com/dotnet/roslyn/issues/36496")]
public void EmptyVarPatternVsDeconstruct()
{
var source =
@"using System;
public class C
{
public static void Main()
{
Console.Write(M(new C()));
Console.Write(M(null));
}
public static bool M(C c)
{
return c is var ();
}
public void Deconstruct() { }
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation, expectedOutput: "TrueFalse");
compVerifier.VerifyIL("C.M(C)",
@"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldnull
IL_0002: cgt.un
IL_0004: ret
}
");
}
[Fact]
[WorkItem(36496, "https://github.com/dotnet/roslyn/issues/36496")]
public void EmptyPositionalPatternVsDeconstruct()
{
var source =
@"using System;
public class C
{
public static void Main()
{
Console.Write(M(new C()));
Console.Write(M(null));
}
public static bool M(C c)
{
return c is ();
}
public void Deconstruct() { }
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation, expectedOutput: "TrueFalse");
compVerifier.VerifyIL("C.M(C)",
@"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldnull
IL_0002: cgt.un
IL_0004: ret
}
");
}
[Fact, WorkItem(31494, "https://github.com/dotnet/roslyn/issues/31494")]
public void NoRedundantNullCheckForStringConstantPattern_01()
{
var source =
@"public class C
{
public static bool M1(string s) => s is ""Frog"";
public static bool M2(string s) => s == ""Frog"";
public static bool M3(string s) => s switch { ""Frog"" => true, _ => false };
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M1(string)", @"
{
// Code size 12 (0xc)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldstr ""Frog""
IL_0006: call ""bool string.op_Equality(string, string)""
IL_000b: ret
}
");
compVerifier.VerifyIL("C.M2(string)", @"
{
// Code size 12 (0xc)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldstr ""Frog""
IL_0006: call ""bool string.op_Equality(string, string)""
IL_000b: ret
}
");
compVerifier.VerifyIL("C.M3(string)", @"
{
// Code size 21 (0x15)
.maxstack 2
.locals init (bool V_0)
IL_0000: ldarg.0
IL_0001: ldstr ""Frog""
IL_0006: call ""bool string.op_Equality(string, string)""
IL_000b: brfalse.s IL_0011
IL_000d: ldc.i4.1
IL_000e: stloc.0
IL_000f: br.s IL_0013
IL_0011: ldc.i4.0
IL_0012: stloc.0
IL_0013: ldloc.0
IL_0014: ret
}
");
}
[Fact, WorkItem(31494, "https://github.com/dotnet/roslyn/issues/31494")]
public void NoRedundantNullCheckForStringConstantPattern_02()
{
var source =
@"public class C
{
public static bool M1(string s) => s switch { ""Frog"" => true, ""Newt"" => true, _ => false };
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M1(string)", @"
{
// Code size 40 (0x28)
.maxstack 2
.locals init (bool V_0)
IL_0000: ldarg.0
IL_0001: ldstr ""Frog""
IL_0006: call ""bool string.op_Equality(string, string)""
IL_000b: brtrue.s IL_001c
IL_000d: ldarg.0
IL_000e: ldstr ""Newt""
IL_0013: call ""bool string.op_Equality(string, string)""
IL_0018: brtrue.s IL_0020
IL_001a: br.s IL_0024
IL_001c: ldc.i4.1
IL_001d: stloc.0
IL_001e: br.s IL_0026
IL_0020: ldc.i4.1
IL_0021: stloc.0
IL_0022: br.s IL_0026
IL_0024: ldc.i4.0
IL_0025: stloc.0
IL_0026: ldloc.0
IL_0027: ret
}
");
}
[Fact, WorkItem(31494, "https://github.com/dotnet/roslyn/issues/31494")]
public void NoRedundantNullCheckForStringConstantPattern_03()
{
var source =
@"public class C
{
public static bool M1(System.Type x) => x is { Name: ""Program"" };
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M1(System.Type)", @"
{
// Code size 22 (0x16)
.maxstack 2
IL_0000: ldarg.0
IL_0001: brfalse.s IL_0014
IL_0003: ldarg.0
IL_0004: callvirt ""string System.Reflection.MemberInfo.Name.get""
IL_0009: ldstr ""Program""
IL_000e: call ""bool string.op_Equality(string, string)""
IL_0013: ret
IL_0014: ldc.i4.0
IL_0015: ret
}
");
}
[Fact]
[WorkItem(42912, "https://github.com/dotnet/roslyn/issues/42912")]
[WorkItem(31494, "https://github.com/dotnet/roslyn/issues/31494")]
public void NoRedundantNullCheckForNullableConstantPattern_04()
{
// Note that we do not produce the same code for `x is 1` and `x == 1`.
// The latter has been optimized to avoid branches.
var source =
@"public class C
{
public static bool M1(int? x) => x is 1;
public static bool M2(int? x) => x == 1;
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation);
compVerifier.VerifyIL("C.M1(int?)", @"
{
// Code size 22 (0x16)
.maxstack 2
IL_0000: ldarga.s V_0
IL_0002: call ""bool int?.HasValue.get""
IL_0007: brfalse.s IL_0014
IL_0009: ldarga.s V_0
IL_000b: call ""int int?.GetValueOrDefault()""
IL_0010: ldc.i4.1
IL_0011: ceq
IL_0013: ret
IL_0014: ldc.i4.0
IL_0015: ret
}
");
compVerifier.VerifyIL("C.M2(int?)", @"
{
// Code size 23 (0x17)
.maxstack 2
.locals init (int? V_0,
int V_1)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldc.i4.1
IL_0003: stloc.1
IL_0004: ldloca.s V_0
IL_0006: call ""int int?.GetValueOrDefault()""
IL_000b: ldloc.1
IL_000c: ceq
IL_000e: ldloca.s V_0
IL_0010: call ""bool int?.HasValue.get""
IL_0015: and
IL_0016: ret
}
");
}
[Fact]
public void SwitchExpressionAsExceptionFilter_01()
{
var source = @"
using System;
class C
{
const string K1 = ""frog"";
const string K2 = ""toad"";
public static void M(string msg)
{
try
{
T(msg);
}
catch (Exception e) when (e.Message switch
{
K1 => true,
K2 => true,
_ => false,
})
{
throw new Exception(e.Message);
}
catch
{
}
}
static void T(string msg)
{
throw new Exception(msg);
}
static void Main()
{
Try(K1);
Try(K2);
Try(""fox"");
}
static void Try(string s)
{
try { M(s); } catch (Exception ex) { Console.WriteLine(ex.Message); }
}
}
";
var expectedOutput =
@"frog
toad";
foreach (var compilationOptions in new[] { TestOptions.ReleaseExe, TestOptions.DebugExe })
{
var compilation = CreateCompilation(source, options: compilationOptions);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
if (compilationOptions.OptimizationLevel == OptimizationLevel.Debug)
{
compVerifier.VerifyIL("C.M(string)", @"
{
// Code size 108 (0x6c)
.maxstack 2
.locals init (System.Exception V_0, //e
bool V_1,
string V_2,
bool V_3)
IL_0000: nop
.try
{
IL_0001: nop
IL_0002: ldarg.0
IL_0003: call ""void C.T(string)""
IL_0008: nop
IL_0009: nop
IL_000a: leave.s IL_006b
}
filter
{
IL_000c: isinst ""System.Exception""
IL_0011: dup
IL_0012: brtrue.s IL_0018
IL_0014: pop
IL_0015: ldc.i4.0
IL_0016: br.s IL_0056
IL_0018: stloc.0
IL_0019: ldloc.0
IL_001a: callvirt ""string System.Exception.Message.get""
IL_001f: stloc.2
IL_0020: ldc.i4.1
IL_0021: brtrue.s IL_0024
IL_0023: nop
IL_0024: ldloc.2
IL_0025: ldstr ""frog""
IL_002a: call ""bool string.op_Equality(string, string)""
IL_002f: brtrue.s IL_0040
IL_0031: ldloc.2
IL_0032: ldstr ""toad""
IL_0037: call ""bool string.op_Equality(string, string)""
IL_003c: brtrue.s IL_0044
IL_003e: br.s IL_0048
IL_0040: ldc.i4.1
IL_0041: stloc.1
IL_0042: br.s IL_004c
IL_0044: ldc.i4.1
IL_0045: stloc.1
IL_0046: br.s IL_004c
IL_0048: ldc.i4.0
IL_0049: stloc.1
IL_004a: br.s IL_004c
IL_004c: ldc.i4.1
IL_004d: brtrue.s IL_0050
IL_004f: nop
IL_0050: ldloc.1
IL_0051: stloc.3
IL_0052: ldloc.3
IL_0053: ldc.i4.0
IL_0054: cgt.un
IL_0056: endfilter
} // end filter
{ // handler
IL_0058: pop
IL_0059: nop
IL_005a: ldloc.0
IL_005b: callvirt ""string System.Exception.Message.get""
IL_0060: newobj ""System.Exception..ctor(string)""
IL_0065: throw
}
catch object
{
IL_0066: pop
IL_0067: nop
IL_0068: nop
IL_0069: leave.s IL_006b
}
IL_006b: ret
}
");
}
else
{
compVerifier.VerifyIL("C.M(string)", @"
{
// Code size 89 (0x59)
.maxstack 2
.locals init (System.Exception V_0, //e
bool V_1,
string V_2)
.try
{
IL_0000: ldarg.0
IL_0001: call ""void C.T(string)""
IL_0006: leave.s IL_0058
}
filter
{
IL_0008: isinst ""System.Exception""
IL_000d: dup
IL_000e: brtrue.s IL_0014
IL_0010: pop
IL_0011: ldc.i4.0
IL_0012: br.s IL_0046
IL_0014: stloc.0
IL_0015: ldloc.0
IL_0016: callvirt ""string System.Exception.Message.get""
IL_001b: stloc.2
IL_001c: ldloc.2
IL_001d: ldstr ""frog""
IL_0022: call ""bool string.op_Equality(string, string)""
IL_0027: brtrue.s IL_0038
IL_0029: ldloc.2
IL_002a: ldstr ""toad""
IL_002f: call ""bool string.op_Equality(string, string)""
IL_0034: brtrue.s IL_003c
IL_0036: br.s IL_0040
IL_0038: ldc.i4.1
IL_0039: stloc.1
IL_003a: br.s IL_0042
IL_003c: ldc.i4.1
IL_003d: stloc.1
IL_003e: br.s IL_0042
IL_0040: ldc.i4.0
IL_0041: stloc.1
IL_0042: ldloc.1
IL_0043: ldc.i4.0
IL_0044: cgt.un
IL_0046: endfilter
} // end filter
{ // handler
IL_0048: pop
IL_0049: ldloc.0
IL_004a: callvirt ""string System.Exception.Message.get""
IL_004f: newobj ""System.Exception..ctor(string)""
IL_0054: throw
}
catch object
{
IL_0055: pop
IL_0056: leave.s IL_0058
}
IL_0058: ret
}
");
}
}
}
[Fact]
public void SwitchExpressionAsExceptionFilter_02()
{
var source = @"
using System;
class C
{
public static void Main()
{
try
{
throw new Exception();
}
catch when ((3 is int i) switch { true when M(() => i) => true, _ => false })
{
Console.WriteLine(""correct"");
}
}
static bool M(Func<int> func)
{
func();
return true;
}
}
";
var expectedOutput = @"correct";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
[WorkItem(48259, "https://github.com/dotnet/roslyn/issues/48259")]
public void SwitchExpressionAsExceptionFilter_03()
{
var source = @"
using System;
using System.Threading.Tasks;
public static class Program
{
static async Task Main()
{
Exception ex = new ArgumentException();
try
{
throw ex;
}
catch (Exception e) when (e switch { InvalidOperationException => true, _ => false })
{
return;
}
catch (Exception)
{
Console.WriteLine(""correct"");
}
}
}
";
var expectedOutput = "correct";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics(
// (7,23): 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.
// static async Task Main()
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Main").WithLocation(7, 23));
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
[WorkItem(48259, "https://github.com/dotnet/roslyn/issues/48259")]
public void SwitchExpressionAsExceptionFilter_04()
{
var source = @"
using System;
using System.Threading.Tasks;
public static class Program
{
static async Task Main()
{
Exception ex = new ArgumentException();
try
{
throw ex;
}
catch (Exception e) when (e switch { ArgumentException => true, _ => false })
{
Console.WriteLine(""correct"");
return;
}
}
}
";
var expectedOutput = "correct";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics(
// (7,23): 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.
// static async Task Main()
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "Main").WithLocation(7, 23));
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[WorkItem(48563, "https://github.com/dotnet/roslyn/issues/48563")]
[Theory]
[InlineData("void*")]
[InlineData("char*")]
[InlineData("delegate*<void>")]
public void IsNull_01(string pointerType)
{
var source =
$@"using static System.Console;
unsafe class Program
{{
static void Main()
{{
Check(0);
Check(-1);
}}
static void Check(nint i)
{{
{pointerType} p = ({pointerType})i;
WriteLine(EqualNull(p));
WriteLine(IsNull(p));
WriteLine(NotEqualNull(p));
WriteLine(IsNotNull(p));
}}
static bool EqualNull({pointerType} p) => p == null;
static bool NotEqualNull({pointerType} p) => p != null;
static bool IsNull({pointerType} p) => p is null;
static bool IsNotNull({pointerType} p) => p is not null;
}}";
var verifier = CompileAndVerify(source, options: TestOptions.UnsafeReleaseExe, verify: Verification.Skipped, expectedOutput:
@"True
True
False
False
False
False
True
True");
string expectedEqualNull =
@"{
// Code size 6 (0x6)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: conv.u
IL_0003: ceq
IL_0005: ret
}";
string expectedNotEqualNull =
@"{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: conv.u
IL_0003: ceq
IL_0005: ldc.i4.0
IL_0006: ceq
IL_0008: ret
}";
verifier.VerifyIL("Program.EqualNull", expectedEqualNull);
verifier.VerifyIL("Program.NotEqualNull", expectedNotEqualNull);
verifier.VerifyIL("Program.IsNull", expectedEqualNull);
verifier.VerifyIL("Program.IsNotNull", expectedNotEqualNull);
}
[WorkItem(48563, "https://github.com/dotnet/roslyn/issues/48563")]
[Fact]
public void IsNull_02()
{
var source =
@"using static System.Console;
unsafe class Program
{
static void Main()
{
Check(0);
Check(-1);
}
static void Check(nint i)
{
char* p = (char*)i;
WriteLine(EqualNull(p));
}
static bool EqualNull(char* p) => p switch { null => true, _ => false };
}";
var verifier = CompileAndVerify(source, options: TestOptions.UnsafeReleaseExe, verify: Verification.Skipped, expectedOutput:
@"True
False");
verifier.VerifyIL("Program.EqualNull",
@"{
// Code size 13 (0xd)
.maxstack 2
.locals init (bool V_0)
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: conv.u
IL_0003: bne.un.s IL_0009
IL_0005: ldc.i4.1
IL_0006: stloc.0
IL_0007: br.s IL_000b
IL_0009: ldc.i4.0
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: ret
}");
}
[WorkItem(48563, "https://github.com/dotnet/roslyn/issues/48563")]
[Fact]
public void IsNull_03()
{
var source =
@"using static System.Console;
unsafe class C
{
public char* P;
}
unsafe class Program
{
static void Main()
{
Check(0);
Check(-1);
}
static void Check(nint i)
{
char* p = (char*)i;
WriteLine(EqualNull(new C() { P = p }));
}
static bool EqualNull(C c) => c switch { { P: null } => true, _ => false };
}";
var verifier = CompileAndVerify(source, options: TestOptions.UnsafeReleaseExe, verify: Verification.Skipped, expectedOutput:
@"True
False");
verifier.VerifyIL("Program.EqualNull",
@"{
// Code size 21 (0x15)
.maxstack 2
.locals init (bool V_0)
IL_0000: ldarg.0
IL_0001: brfalse.s IL_0011
IL_0003: ldarg.0
IL_0004: ldfld ""char* C.P""
IL_0009: ldc.i4.0
IL_000a: conv.u
IL_000b: bne.un.s IL_0011
IL_000d: ldc.i4.1
IL_000e: stloc.0
IL_000f: br.s IL_0013
IL_0011: ldc.i4.0
IL_0012: stloc.0
IL_0013: ldloc.0
IL_0014: ret
}");
}
#endregion Miscellaneous
#region Target Typed Switch
[Fact]
public void TargetTypedSwitch_Assignment()
{
var source = @"
using System;
class Program
{
public static void Main()
{
Console.Write(M(false));
Console.Write(M(true));
}
static object M(bool b)
{
int result = b switch { false => new A(), true => new B() };
return result;
}
}
class A
{
public static implicit operator int(A a) => throw null;
public static implicit operator B(A a) => new B();
}
class B
{
public static implicit operator int(B b) => (b == null) ? throw null : 2;
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
var expectedOutput = @"22";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void TargetTypedSwitch_Return()
{
var source = @"
using System;
class Program
{
public static void Main()
{
Console.Write(M(false));
Console.Write(M(true));
}
static long M(bool b)
{
return b switch { false => new A(), true => new B() };
}
}
class A
{
public static implicit operator int(A a) => throw null;
public static implicit operator B(A a) => new B();
}
class B
{
public static implicit operator int(B b) => (b == null) ? throw null : 2;
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
var expectedOutput = @"22";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void TargetTypedSwitch_Argument_01()
{
var source = @"
using System;
class Program
{
public static void Main()
{
Console.Write(M1(false));
Console.Write(M1(true));
}
static object M1(bool b)
{
return M2(b switch { false => new A(), true => new B() });
}
static Exception M2(Exception ex) => ex;
static int M2(int i) => i;
static int M2(string s) => s.Length;
}
class A : Exception
{
public static implicit operator int(A a) => throw null;
public static implicit operator B(A a) => throw null;
}
class B : Exception
{
public static implicit operator int(B b) => throw null;
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics(
// (12,16): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M2(Exception)' and 'Program.M2(int)'
// return M2(b switch { false => new A(), true => new B() });
Diagnostic(ErrorCode.ERR_AmbigCall, "M2").WithArguments("Program.M2(System.Exception)", "Program.M2(int)").WithLocation(12, 16)
);
}
[Fact]
public void TargetTypedSwitch_Argument_02()
{
var source = @"
using System;
class Program
{
public static void Main()
{
Console.Write(M1(false));
Console.Write(M1(true));
}
static object M1(bool b)
{
return M2(b switch { false => new A(), true => new B() });
}
// static Exception M2(Exception ex) => ex;
static int M2(int i) => i;
static int M2(string s) => s.Length;
}
class A : Exception
{
public static implicit operator int(A a) => throw null;
public static implicit operator B(A a) => new B();
}
class B : Exception
{
public static implicit operator int(B b) => (b == null) ? throw null : 2;
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
var expectedOutput = @"22";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)]
public void TargetTypedSwitch_Arglist()
{
var source = @"
using System;
class Program
{
public static void Main()
{
Console.WriteLine(M1(false));
Console.WriteLine(M1(true));
}
static object M1(bool b)
{
return M2(__arglist(b switch { false => new A(), true => new B() }));
}
static int M2(__arglist) => 1;
}
class A
{
public A() { Console.Write(""new A; ""); }
public static implicit operator B(A a) { Console.Write(""A->""); return new B(); }
}
class B
{
public B() { Console.Write(""new B; ""); }
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
var expectedOutput =
@"new A; A->new B; 1
new B; 1";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void TargetTypedSwitch_StackallocSize()
{
var source = @"
using System;
class Program
{
public static void Main()
{
M1(false);
M1(true);
}
static void M1(bool b)
{
Span<int> s = stackalloc int[b switch { false => new A(), true => new B() }];
Console.WriteLine(s.Length);
}
}
class A
{
public A() { Console.Write(""new A; ""); }
public static implicit operator int(A a) { Console.Write(""A->int; ""); return 4; }
}
class B
{
public B() { Console.Write(""new B; ""); }
public static implicit operator int(B b) { Console.Write(""B->int; ""); return 2; }
}
";
var compilation = CreateCompilationWithMscorlibAndSpan(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
var expectedOutput =
@"new A; A->int; 4
new B; B->int; 2";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput, verify: Verification.Skipped);
}
[Fact]
public void TargetTypedSwitch_Attribute()
{
var source = @"
using System;
class Program
{
[My(1 switch { 1 => 1, _ => 2 })]
public static void M1() { }
[My(1 switch { 1 => new A(), _ => new B() })]
public static void M2() { }
[My(1 switch { 1 => 1, _ => string.Empty })]
public static void M3() { }
}
public class MyAttribute : Attribute
{
public MyAttribute(int Value) { }
}
public class A
{
public static implicit operator int(A a) => 4;
}
public class B
{
public static implicit operator int(B b) => 2;
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (5,9): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [My(1 switch { 1 => 1, _ => 2 })]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "1 switch { 1 => 1, _ => 2 }").WithLocation(5, 9),
// (8,9): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [My(1 switch { 1 => new A(), _ => new B() })]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "1 switch { 1 => new A(), _ => new B() }").WithLocation(8, 9),
// (11,9): error CS1503: Argument 1: cannot convert from '<switch expression>' to 'int'
// [My(1 switch { 1 => 1, _ => string.Empty })]
Diagnostic(ErrorCode.ERR_BadArgType, "1 switch { 1 => 1, _ => string.Empty }").WithArguments("1", "<switch expression>", "int").WithLocation(11, 9)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var switchExpressions = tree.GetRoot().DescendantNodes().OfType<SwitchExpressionSyntax>().ToArray();
VerifyOperationTreeForNode(compilation, model, switchExpressions[0], @"
ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: '1 switch { ... 1, _ => 2 }')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Arms(2):
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '1 => 1')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '_ => 2')
Pattern:
IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null, IsInvalid) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2')
");
VerifyOperationTreeForNode(compilation, model, switchExpressions[1], @"
ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: '1 switch { ... > new B() }')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Arms(2):
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '1 => new A()')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Int32 A.op_Implicit(A a)) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'new A()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 A.op_Implicit(A a))
Operand:
IObjectCreationOperation (Constructor: A..ctor()) (OperationKind.ObjectCreation, Type: A, IsInvalid) (Syntax: 'new A()')
Arguments(0)
Initializer:
null
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '_ => new B()')
Pattern:
IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null, IsInvalid) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Int32 B.op_Implicit(B b)) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'new B()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 B.op_Implicit(B b))
Operand:
IObjectCreationOperation (Constructor: B..ctor()) (OperationKind.ObjectCreation, Type: B, IsInvalid) (Syntax: 'new B()')
Arguments(0)
Initializer:
null
");
VerifyOperationTreeForNode(compilation, model, switchExpressions[2], @"
ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: ?, IsInvalid) (Syntax: '1 switch { ... ing.Empty }')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Arms(2):
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '1 => 1')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsInvalid, IsImplicit) (Syntax: '1')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '_ => string.Empty')
Pattern:
IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null, IsInvalid) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsInvalid, IsImplicit) (Syntax: 'string.Empty')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String, IsInvalid) (Syntax: 'string.Empty')
Instance Receiver:
null
");
}
[Fact]
public void TargetTypedSwitch_Attribute_NamedArgument()
{
var source = @"
using System;
class Program
{
[My(Value = 1 switch { 1 => 1, _ => 2 })]
public static void M1() { }
[My(Value = 1 switch { 1 => new A(), _ => new B() })]
public static void M2() { }
[My(Value = 1 switch { 1 => 1, _ => string.Empty })]
public static void M3() { }
}
public class MyAttribute : Attribute
{
public MyAttribute() { }
public int Value { get; set; }
}
public class A
{
public static implicit operator int(A a) => 4;
}
public class B
{
public static implicit operator int(B b) => 2;
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (5,17): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [My(Value = 1 switch { 1 => 1, _ => 2 })]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "1 switch { 1 => 1, _ => 2 }").WithLocation(5, 17),
// (8,17): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [My(Value = 1 switch { 1 => new A(), _ => new B() })]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "1 switch { 1 => new A(), _ => new B() }").WithLocation(8, 17),
// (11,41): error CS0029: Cannot implicitly convert type 'string' to 'int'
// [My(Value = 1 switch { 1 => 1, _ => string.Empty })]
Diagnostic(ErrorCode.ERR_NoImplicitConv, "string.Empty").WithArguments("string", "int").WithLocation(11, 41)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var attributeArguments = tree.GetRoot().DescendantNodes().OfType<AttributeArgumentSyntax>().ToArray();
VerifyOperationTreeForNode(compilation, model, attributeArguments[0], @"
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'Value = 1 s ... 1, _ => 2 }')
Left:
IPropertyReferenceOperation: System.Int32 MyAttribute.Value { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Value')
Instance Receiver:
null
Right:
ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: '1 switch { ... 1, _ => 2 }')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Arms(2):
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '1 => 1')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '_ => 2')
Pattern:
IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null, IsInvalid) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2')
");
VerifyOperationTreeForNode(compilation, model, attributeArguments[1], @"
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'Value = 1 s ... > new B() }')
Left:
IPropertyReferenceOperation: System.Int32 MyAttribute.Value { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Value')
Instance Receiver:
null
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '1 switch { ... > new B() }')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: '1 switch { ... > new B() }')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Arms(2):
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '1 => new A()')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Int32 A.op_Implicit(A a)) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'new A()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 A.op_Implicit(A a))
Operand:
IObjectCreationOperation (Constructor: A..ctor()) (OperationKind.ObjectCreation, Type: A, IsInvalid) (Syntax: 'new A()')
Arguments(0)
Initializer:
null
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '_ => new B()')
Pattern:
IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null, IsInvalid) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: System.Int32 B.op_Implicit(B b)) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'new B()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: System.Int32 B.op_Implicit(B b))
Operand:
IObjectCreationOperation (Constructor: B..ctor()) (OperationKind.ObjectCreation, Type: B, IsInvalid) (Syntax: 'new B()')
Arguments(0)
Initializer:
null
");
VerifyOperationTreeForNode(compilation, model, attributeArguments[2], @"
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'Value = 1 s ... ing.Empty }')
Left:
IPropertyReferenceOperation: System.Int32 MyAttribute.Value { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Value')
Instance Receiver:
null
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '1 switch { ... ing.Empty }')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: ?, IsInvalid) (Syntax: '1 switch { ... ing.Empty }')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Arms(2):
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '1 => 1')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: '1')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '_ => string.Empty')
Pattern:
IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsInvalid, IsImplicit) (Syntax: 'string.Empty')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String, IsInvalid) (Syntax: 'string.Empty')
Instance Receiver:
null
");
}
[Fact]
public void TargetTypedSwitch_Attribute_MissingNamedArgument()
{
var source = @"
using System;
class Program
{
[My(Value = 1 switch { 1 => 1, _ => 2 })]
public static void M1() { }
[My(Value = 1 switch { 1 => new A(), _ => new B() })]
public static void M2() { }
[My(Value = 1 switch { 1 => 1, _ => string.Empty })]
public static void M3() { }
}
public class MyAttribute : Attribute
{
public MyAttribute() { }
}
public class A
{
public static implicit operator int(A a) => 4;
}
public class B
{
public static implicit operator int(B b) => 2;
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (5,9): error CS0246: The type or namespace name 'Value' could not be found (are you missing a using directive or an assembly reference?)
// [My(Value = 1 switch { 1 => 1, _ => 2 })]
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Value").WithArguments("Value").WithLocation(5, 9),
// (8,9): error CS0246: The type or namespace name 'Value' could not be found (are you missing a using directive or an assembly reference?)
// [My(Value = 1 switch { 1 => new A(), _ => new B() })]
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Value").WithArguments("Value").WithLocation(8, 9),
// (11,9): error CS0246: The type or namespace name 'Value' could not be found (are you missing a using directive or an assembly reference?)
// [My(Value = 1 switch { 1 => 1, _ => string.Empty })]
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Value").WithArguments("Value").WithLocation(11, 9)
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var attributeArguments = tree.GetRoot().DescendantNodes().OfType<AttributeArgumentSyntax>().ToArray();
VerifyOperationTreeForNode(compilation, model, attributeArguments[0], @"
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'Value = 1 s ... 1, _ => 2 }')
Left:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Value')
Children(0)
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: '1 switch { ... 1, _ => 2 }')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32) (Syntax: '1 switch { ... 1, _ => 2 }')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Arms(2):
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '1 => 1')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '_ => 2')
Pattern:
IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
");
VerifyOperationTreeForNode(compilation, model, attributeArguments[1], @"
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'Value = 1 s ... > new B() }')
Left:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Value')
Children(0)
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: '1 switch { ... > new B() }')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: ?) (Syntax: '1 switch { ... > new B() }')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Arms(2):
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '1 => new A()')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: 'new A()')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IObjectCreationOperation (Constructor: A..ctor()) (OperationKind.ObjectCreation, Type: A) (Syntax: 'new A()')
Arguments(0)
Initializer:
null
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '_ => new B()')
Pattern:
IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: 'new B()')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IObjectCreationOperation (Constructor: B..ctor()) (OperationKind.ObjectCreation, Type: B) (Syntax: 'new B()')
Arguments(0)
Initializer:
null
");
VerifyOperationTreeForNode(compilation, model, attributeArguments[2], @"
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'Value = 1 s ... ing.Empty }')
Left:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Value')
Children(0)
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: '1 switch { ... ing.Empty }')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: ?) (Syntax: '1 switch { ... ing.Empty }')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Arms(2):
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '1 => 1')
Pattern:
IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: '1')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '_ => string.Empty')
Pattern:
IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32)
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: 'string.Empty')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String) (Syntax: 'string.Empty')
Instance Receiver:
null
");
}
[Fact]
public void TargetTypedSwitch_As()
{
var source = @"
class Program
{
public static void M(int i, string s)
{
// we do not target-type the left-hand-side of an as expression
_ = i switch { 1 => i, _ => s } as object;
}
}
";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (7,15): error CS8506: No best type was found for the switch expression.
// _ = i switch { 1 => i, _ => s } as object;
Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(7, 15)
);
}
[Fact]
public void TargetTypedSwitch_DoubleConversion()
{
var source = @"using System;
class Program
{
public static void Main(string[] args)
{
M(false);
M(true);
}
public static void M(bool b)
{
C c = b switch { false => new A(), true => new B() };
Console.WriteLine(""."");
}
}
class A
{
public A()
{
Console.Write(""new A; "");
}
public static implicit operator B(A a)
{
Console.Write(""A->"");
return new B();
}
}
class B
{
public B()
{
Console.Write(""new B; "");
}
public static implicit operator C(B a)
{
Console.Write(""B->"");
return new C();
}
}
class C
{
public C()
{
Console.Write(""new C; "");
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe);
compilation.VerifyDiagnostics();
var expectedOutput =
@"new A; A->new B; B->new C; .
new B; B->new C; .";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
}
[Fact]
public void TargetTypedSwitch_StringInsert()
{
var source = @"
using System;
class Program
{
public static void Main()
{
Console.Write($""{false switch { false => new A(), true => new B() }}"");
Console.Write($""{true switch { false => new A(), true => new B() }}"");
}
}
class A
{
}
class B
{
}
";
var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: "AB");
}
#endregion Target Typed Switch
#region Pattern Combinators
[Fact]
public void IsPatternDisjunct_01()
{
var source = @"
using System;
class C
{
static bool M1(object o) => o is int or long;
static bool M2(object o) => o is int || o is long;
public static void Main()
{
Console.Write(M1(1));
Console.Write(M1(string.Empty));
Console.Write(M1(1L));
Console.Write(M1(1UL));
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithPatternCombinators);
compilation.VerifyDiagnostics();
var expectedOutput = @"TrueFalseTrueFalse";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
var code = @"
{
// Code size 21 (0x15)
.maxstack 2
IL_0000: ldarg.0
IL_0001: isinst ""int""
IL_0006: brtrue.s IL_0013
IL_0008: ldarg.0
IL_0009: isinst ""long""
IL_000e: ldnull
IL_000f: cgt.un
IL_0011: br.s IL_0014
IL_0013: ldc.i4.1
IL_0014: ret
}
";
compVerifier.VerifyIL("C.M1", code);
compVerifier.VerifyIL("C.M2", code);
compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.RegularWithPatternCombinators);
compilation.VerifyDiagnostics();
compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
code = @"
{
// Code size 20 (0x14)
.maxstack 2
IL_0000: ldarg.0
IL_0001: isinst ""int""
IL_0006: brtrue.s IL_0012
IL_0008: ldarg.0
IL_0009: isinst ""long""
IL_000e: ldnull
IL_000f: cgt.un
IL_0011: ret
IL_0012: ldc.i4.1
IL_0013: ret
}
";
compVerifier.VerifyIL("C.M1", code);
compVerifier.VerifyIL("C.M2", code);
}
[Fact]
public void IsPatternDisjunct_02()
{
var source = @"
using System;
class C
{
static string M1(object o) => (o is int or long) ? ""True"" : ""False"";
static string M2(object o) => (o is int || o is long) ? ""True"" : ""False"";
public static void Main()
{
Console.Write(M1(1));
Console.Write(M1(string.Empty));
Console.Write(M1(1L));
Console.Write(M1(1UL));
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithPatternCombinators);
compilation.VerifyDiagnostics();
var expectedOutput = @"TrueFalseTrueFalse";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
var code = @"
{
// Code size 29 (0x1d)
.maxstack 1
IL_0000: ldarg.0
IL_0001: isinst ""int""
IL_0006: brtrue.s IL_0017
IL_0008: ldarg.0
IL_0009: isinst ""long""
IL_000e: brtrue.s IL_0017
IL_0010: ldstr ""False""
IL_0015: br.s IL_001c
IL_0017: ldstr ""True""
IL_001c: ret
}
";
compVerifier.VerifyIL("C.M1", code);
compVerifier.VerifyIL("C.M2", code);
compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.RegularWithPatternCombinators);
compilation.VerifyDiagnostics();
compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
code = @"
{
// Code size 28 (0x1c)
.maxstack 1
IL_0000: ldarg.0
IL_0001: isinst ""int""
IL_0006: brtrue.s IL_0016
IL_0008: ldarg.0
IL_0009: isinst ""long""
IL_000e: brtrue.s IL_0016
IL_0010: ldstr ""False""
IL_0015: ret
IL_0016: ldstr ""True""
IL_001b: ret
}
";
compVerifier.VerifyIL("C.M1", code);
compVerifier.VerifyIL("C.M2", code);
}
[Fact]
public void IsPatternDisjunct_03()
{
var source = @"
using System;
class C
{
static bool M1(object o) => o is >= 'A' and <= 'Z' or >= 'a' and <= 'z';
static bool M2(object o) => o is char c && (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z');
public static void Main()
{
Console.Write(M1('A'));
Console.Write(M1('0'));
Console.Write(M1('q'));
Console.Write(M1(2));
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithPatternCombinators);
compilation.VerifyDiagnostics();
var expectedOutput = @"TrueFalseTrueFalse";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("C.M1", @"
{
// Code size 47 (0x2f)
.maxstack 2
.locals init (char V_0,
bool V_1)
IL_0000: ldarg.0
IL_0001: isinst ""char""
IL_0006: brfalse.s IL_002b
IL_0008: ldarg.0
IL_0009: unbox.any ""char""
IL_000e: stloc.0
IL_000f: ldloc.0
IL_0010: ldc.i4.s 97
IL_0012: blt.s IL_001b
IL_0014: ldloc.0
IL_0015: ldc.i4.s 122
IL_0017: ble.s IL_0027
IL_0019: br.s IL_002b
IL_001b: ldloc.0
IL_001c: ldc.i4.s 65
IL_001e: blt.s IL_002b
IL_0020: ldloc.0
IL_0021: ldc.i4.s 90
IL_0023: ble.s IL_0027
IL_0025: br.s IL_002b
IL_0027: ldc.i4.1
IL_0028: stloc.1
IL_0029: br.s IL_002d
IL_002b: ldc.i4.0
IL_002c: stloc.1
IL_002d: ldloc.1
IL_002e: ret
}
");
compVerifier.VerifyIL("C.M2", @"
{
// Code size 48 (0x30)
.maxstack 2
.locals init (char V_0) //c
IL_0000: ldarg.0
IL_0001: isinst ""char""
IL_0006: brfalse.s IL_002e
IL_0008: ldarg.0
IL_0009: unbox.any ""char""
IL_000e: stloc.0
IL_000f: ldloc.0
IL_0010: ldc.i4.s 65
IL_0012: blt.s IL_0019
IL_0014: ldloc.0
IL_0015: ldc.i4.s 90
IL_0017: ble.s IL_002b
IL_0019: ldloc.0
IL_001a: ldc.i4.s 97
IL_001c: blt.s IL_0028
IL_001e: ldloc.0
IL_001f: ldc.i4.s 122
IL_0021: cgt
IL_0023: ldc.i4.0
IL_0024: ceq
IL_0026: br.s IL_0029
IL_0028: ldc.i4.0
IL_0029: br.s IL_002c
IL_002b: ldc.i4.1
IL_002c: br.s IL_002f
IL_002e: ldc.i4.0
IL_002f: ret
}
");
compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.RegularWithPatternCombinators);
compilation.VerifyDiagnostics();
compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("C.M1", @"
{
// Code size 45 (0x2d)
.maxstack 2
.locals init (char V_0,
bool V_1)
IL_0000: ldarg.0
IL_0001: isinst ""char""
IL_0006: brfalse.s IL_0029
IL_0008: ldarg.0
IL_0009: unbox.any ""char""
IL_000e: stloc.0
IL_000f: ldloc.0
IL_0010: ldc.i4.s 97
IL_0012: blt.s IL_001b
IL_0014: ldloc.0
IL_0015: ldc.i4.s 122
IL_0017: ble.s IL_0025
IL_0019: br.s IL_0029
IL_001b: ldloc.0
IL_001c: ldc.i4.s 65
IL_001e: blt.s IL_0029
IL_0020: ldloc.0
IL_0021: ldc.i4.s 90
IL_0023: bgt.s IL_0029
IL_0025: ldc.i4.1
IL_0026: stloc.1
IL_0027: br.s IL_002b
IL_0029: ldc.i4.0
IL_002a: stloc.1
IL_002b: ldloc.1
IL_002c: ret
}
");
compVerifier.VerifyIL("C.M2", @"
{
// Code size 45 (0x2d)
.maxstack 2
.locals init (char V_0) //c
IL_0000: ldarg.0
IL_0001: isinst ""char""
IL_0006: brfalse.s IL_002b
IL_0008: ldarg.0
IL_0009: unbox.any ""char""
IL_000e: stloc.0
IL_000f: ldloc.0
IL_0010: ldc.i4.s 65
IL_0012: blt.s IL_0019
IL_0014: ldloc.0
IL_0015: ldc.i4.s 90
IL_0017: ble.s IL_0029
IL_0019: ldloc.0
IL_001a: ldc.i4.s 97
IL_001c: blt.s IL_0027
IL_001e: ldloc.0
IL_001f: ldc.i4.s 122
IL_0021: cgt
IL_0023: ldc.i4.0
IL_0024: ceq
IL_0026: ret
IL_0027: ldc.i4.0
IL_0028: ret
IL_0029: ldc.i4.1
IL_002a: ret
IL_002b: ldc.i4.0
IL_002c: ret
}
");
}
[Fact]
public void IsPatternDisjunct_04()
{
var source = @"
using System;
class C
{
static int M1(char c) => (c is >= 'A' and <= 'Z' or >= 'a' and <= 'z') ? 1 : 0;
static int M2(char c) => (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') ? 1 : 0;
public static void Main()
{
Console.Write(M1('A'));
Console.Write(M1('0'));
Console.Write(M1('q'));
Console.Write(M1(' '));
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithPatternCombinators);
compilation.VerifyDiagnostics();
var expectedOutput = @"1010";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("C.M1", @"
{
// Code size 38 (0x26)
.maxstack 2
.locals init (bool V_0)
IL_0000: ldarg.0
IL_0001: ldc.i4.s 97
IL_0003: blt.s IL_000c
IL_0005: ldarg.0
IL_0006: ldc.i4.s 122
IL_0008: ble.s IL_0018
IL_000a: br.s IL_001c
IL_000c: ldarg.0
IL_000d: ldc.i4.s 65
IL_000f: blt.s IL_001c
IL_0011: ldarg.0
IL_0012: ldc.i4.s 90
IL_0014: ble.s IL_0018
IL_0016: br.s IL_001c
IL_0018: ldc.i4.1
IL_0019: stloc.0
IL_001a: br.s IL_001e
IL_001c: ldc.i4.0
IL_001d: stloc.0
IL_001e: ldloc.0
IL_001f: brtrue.s IL_0024
IL_0021: ldc.i4.0
IL_0022: br.s IL_0025
IL_0024: ldc.i4.1
IL_0025: ret
}
");
compVerifier.VerifyIL("C.M2", @"
{
// Code size 25 (0x19)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 65
IL_0003: blt.s IL_000a
IL_0005: ldarg.0
IL_0006: ldc.i4.s 90
IL_0008: ble.s IL_0017
IL_000a: ldarg.0
IL_000b: ldc.i4.s 97
IL_000d: blt.s IL_0014
IL_000f: ldarg.0
IL_0010: ldc.i4.s 122
IL_0012: ble.s IL_0017
IL_0014: ldc.i4.0
IL_0015: br.s IL_0018
IL_0017: ldc.i4.1
IL_0018: ret
}
");
compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.RegularWithPatternCombinators);
compilation.VerifyDiagnostics();
compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("C.M1", @"
{
// Code size 35 (0x23)
.maxstack 2
.locals init (bool V_0)
IL_0000: ldarg.0
IL_0001: ldc.i4.s 97
IL_0003: blt.s IL_000c
IL_0005: ldarg.0
IL_0006: ldc.i4.s 122
IL_0008: ble.s IL_0016
IL_000a: br.s IL_001a
IL_000c: ldarg.0
IL_000d: ldc.i4.s 65
IL_000f: blt.s IL_001a
IL_0011: ldarg.0
IL_0012: ldc.i4.s 90
IL_0014: bgt.s IL_001a
IL_0016: ldc.i4.1
IL_0017: stloc.0
IL_0018: br.s IL_001c
IL_001a: ldc.i4.0
IL_001b: stloc.0
IL_001c: ldloc.0
IL_001d: brtrue.s IL_0021
IL_001f: ldc.i4.0
IL_0020: ret
IL_0021: ldc.i4.1
IL_0022: ret
}
");
compVerifier.VerifyIL("C.M2", @"
{
// Code size 24 (0x18)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 65
IL_0003: blt.s IL_000a
IL_0005: ldarg.0
IL_0006: ldc.i4.s 90
IL_0008: ble.s IL_0016
IL_000a: ldarg.0
IL_000b: ldc.i4.s 97
IL_000d: blt.s IL_0014
IL_000f: ldarg.0
IL_0010: ldc.i4.s 122
IL_0012: ble.s IL_0016
IL_0014: ldc.i4.0
IL_0015: ret
IL_0016: ldc.i4.1
IL_0017: ret
}
");
}
[Fact]
public void IsPatternDisjunct_05()
{
var source = @"
using System;
class C
{
static int M1(char c)
{
if (c is >= 'A' and <= 'Z' or >= 'a' and <= 'z')
return 1;
else
return 0;
}
static int M2(char c)
{
if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z')
return 1;
else
return 0;
}
public static void Main()
{
Console.Write(M1('A'));
Console.Write(M1('0'));
Console.Write(M1('q'));
Console.Write(M1(' '));
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.RegularWithPatternCombinators);
compilation.VerifyDiagnostics();
var expectedOutput = @"1010";
var compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("C.M1", @"
{
// Code size 46 (0x2e)
.maxstack 2
.locals init (bool V_0,
bool V_1,
int V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldc.i4.s 97
IL_0004: blt.s IL_000d
IL_0006: ldarg.0
IL_0007: ldc.i4.s 122
IL_0009: ble.s IL_0019
IL_000b: br.s IL_001d
IL_000d: ldarg.0
IL_000e: ldc.i4.s 65
IL_0010: blt.s IL_001d
IL_0012: ldarg.0
IL_0013: ldc.i4.s 90
IL_0015: ble.s IL_0019
IL_0017: br.s IL_001d
IL_0019: ldc.i4.1
IL_001a: stloc.0
IL_001b: br.s IL_001f
IL_001d: ldc.i4.0
IL_001e: stloc.0
IL_001f: ldloc.0
IL_0020: stloc.1
IL_0021: ldloc.1
IL_0022: brfalse.s IL_0028
IL_0024: ldc.i4.1
IL_0025: stloc.2
IL_0026: br.s IL_002c
IL_0028: ldc.i4.0
IL_0029: stloc.2
IL_002a: br.s IL_002c
IL_002c: ldloc.2
IL_002d: ret
}
");
compVerifier.VerifyIL("C.M2", @"
{
// Code size 44 (0x2c)
.maxstack 2
.locals init (bool V_0,
int V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldc.i4.s 65
IL_0004: blt.s IL_000b
IL_0006: ldarg.0
IL_0007: ldc.i4.s 90
IL_0009: ble.s IL_001d
IL_000b: ldarg.0
IL_000c: ldc.i4.s 97
IL_000e: blt.s IL_001a
IL_0010: ldarg.0
IL_0011: ldc.i4.s 122
IL_0013: cgt
IL_0015: ldc.i4.0
IL_0016: ceq
IL_0018: br.s IL_001b
IL_001a: ldc.i4.0
IL_001b: br.s IL_001e
IL_001d: ldc.i4.1
IL_001e: stloc.0
IL_001f: ldloc.0
IL_0020: brfalse.s IL_0026
IL_0022: ldc.i4.1
IL_0023: stloc.1
IL_0024: br.s IL_002a
IL_0026: ldc.i4.0
IL_0027: stloc.1
IL_0028: br.s IL_002a
IL_002a: ldloc.1
IL_002b: ret
}
");
compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.RegularWithPatternCombinators);
compilation.VerifyDiagnostics();
compVerifier = CompileAndVerify(compilation, expectedOutput: expectedOutput);
compVerifier.VerifyIL("C.M1", @"
{
// Code size 35 (0x23)
.maxstack 2
.locals init (bool V_0)
IL_0000: ldarg.0
IL_0001: ldc.i4.s 97
IL_0003: blt.s IL_000c
IL_0005: ldarg.0
IL_0006: ldc.i4.s 122
IL_0008: ble.s IL_0016
IL_000a: br.s IL_001a
IL_000c: ldarg.0
IL_000d: ldc.i4.s 65
IL_000f: blt.s IL_001a
IL_0011: ldarg.0
IL_0012: ldc.i4.s 90
IL_0014: bgt.s IL_001a
IL_0016: ldc.i4.1
IL_0017: stloc.0
IL_0018: br.s IL_001c
IL_001a: ldc.i4.0
IL_001b: stloc.0
IL_001c: ldloc.0
IL_001d: brfalse.s IL_0021
IL_001f: ldc.i4.1
IL_0020: ret
IL_0021: ldc.i4.0
IL_0022: ret
}
");
compVerifier.VerifyIL("C.M2", @"
{
// Code size 24 (0x18)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 65
IL_0003: blt.s IL_000a
IL_0005: ldarg.0
IL_0006: ldc.i4.s 90
IL_0008: ble.s IL_0014
IL_000a: ldarg.0
IL_000b: ldc.i4.s 97
IL_000d: blt.s IL_0016
IL_000f: ldarg.0
IL_0010: ldc.i4.s 122
IL_0012: bgt.s IL_0016
IL_0014: ldc.i4.1
IL_0015: ret
IL_0016: ldc.i4.0
IL_0017: ret
}
");
}
[Fact, WorkItem(46536, "https://github.com/dotnet/roslyn/issues/46536")]
public void MultiplePathsToNode_SwitchDispatch_01()
{
var source = @"
using System;
class Program
{
static void Main()
{
Console.Write(M("""", 0)); // 0
Console.Write(M("""", 1)); // 1
Console.Write(M("""", 2)); // 2
Console.Write(M("""", 3)); // 3
Console.Write(M(""a"", 2)); // 2
Console.Write(M(""a"", 10)); // 3
}
static int M(string x, int y)
{
return (x, y) switch
{
("""", 0) => 0,
("""", 1) => 1,
(_, 2) => 2,
_ => 3
};
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "012323", options: TestOptions.DebugExe);
verifier.VerifyDiagnostics();
verifier.VerifyIL("Program.M", @"{
// Code size 70 (0x46)
.maxstack 2
.locals init (int V_0,
int V_1)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: brtrue.s IL_0005
IL_0004: nop
IL_0005: ldarg.0
IL_0006: ldstr """"
IL_000b: call ""bool string.op_Equality(string, string)""
IL_0010: brfalse.s IL_0026
IL_0012: ldarg.1
IL_0013: switch (
IL_002c,
IL_0030,
IL_0034)
IL_0024: br.s IL_0038
IL_0026: ldarg.1
IL_0027: ldc.i4.2
IL_0028: beq.s IL_0034
IL_002a: br.s IL_0038
IL_002c: ldc.i4.0
IL_002d: stloc.0
IL_002e: br.s IL_003c
IL_0030: ldc.i4.1
IL_0031: stloc.0
IL_0032: br.s IL_003c
IL_0034: ldc.i4.2
IL_0035: stloc.0
IL_0036: br.s IL_003c
IL_0038: ldc.i4.3
IL_0039: stloc.0
IL_003a: br.s IL_003c
IL_003c: ldc.i4.1
IL_003d: brtrue.s IL_0040
IL_003f: nop
IL_0040: ldloc.0
IL_0041: stloc.1
IL_0042: br.s IL_0044
IL_0044: ldloc.1
IL_0045: ret
}");
}
[Fact, WorkItem(46536, "https://github.com/dotnet/roslyn/issues/46536")]
public void MultiplePathsToNode_SwitchDispatch_02()
{
var source = @"
using System;
class Program
{
static void Main()
{
Console.Write(M0("""", 0)); // 0
Console.Write(M0("""", 1)); // 1
Console.Write(M0("""", 2)); // 2
Console.Write(M0("""", 3)); // 3
Console.Write(M0(""a"", 2)); // 2
Console.Write(M0(""a"", 10)); // 3
}
static int M0(string x, int y)
{
return (x, y) switch
{
("""", 0) => M1(0),
("""", 1) => M1(1),
(_, 2) => M1(2),
_ => M1(3)
};
}
static int M1(int z)
{
Console.Write(' ');
return z;
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: " 0 1 2 3 2 3", options: TestOptions.DebugExe);
verifier.VerifyDiagnostics();
verifier.VerifyIL("Program.M0", @"{
// Code size 90 (0x5a)
.maxstack 2
.locals init (int V_0,
int V_1)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: brtrue.s IL_0005
IL_0004: nop
IL_0005: ldarg.0
IL_0006: ldstr """"
IL_000b: call ""bool string.op_Equality(string, string)""
IL_0010: brfalse.s IL_0026
IL_0012: ldarg.1
IL_0013: switch (
IL_002c,
IL_0035,
IL_003e)
IL_0024: br.s IL_0047
IL_0026: ldarg.1
IL_0027: ldc.i4.2
IL_0028: beq.s IL_003e
IL_002a: br.s IL_0047
IL_002c: ldc.i4.0
IL_002d: call ""int Program.M1(int)""
IL_0032: stloc.0
IL_0033: br.s IL_0050
IL_0035: ldc.i4.1
IL_0036: call ""int Program.M1(int)""
IL_003b: stloc.0
IL_003c: br.s IL_0050
IL_003e: ldc.i4.2
IL_003f: call ""int Program.M1(int)""
IL_0044: stloc.0
IL_0045: br.s IL_0050
IL_0047: ldc.i4.3
IL_0048: call ""int Program.M1(int)""
IL_004d: stloc.0
IL_004e: br.s IL_0050
IL_0050: ldc.i4.1
IL_0051: brtrue.s IL_0054
IL_0053: nop
IL_0054: ldloc.0
IL_0055: stloc.1
IL_0056: br.s IL_0058
IL_0058: ldloc.1
IL_0059: ret
}");
}
[Fact, WorkItem(46536, "https://github.com/dotnet/roslyn/issues/46536")]
public void MultiplePathsToNode_SwitchDispatch_03()
{
var source = @"
using System;
class Program
{
static void Main()
{
Console.Write(M("""", 0)); // 0
Console.Write(M("""", 1)); // 1
Console.Write(M("""", 2)); // 2
Console.Write(M("""", 3)); // 3
Console.Write(M("""", 4)); // 4
Console.Write(M("""", 5)); // 5
Console.Write(M(""a"", 2)); // 2
Console.Write(M(""a"", 3)); // 3
Console.Write(M(""a"", 4)); // 4
Console.Write(M(""a"", 10)); // 5
}
static int M(string x, int y)
{
return (x, y) switch
{
("""", 0) => 0,
("""", 1) => 1,
(_, 2) => 2,
(_, 3) => 3,
(_, 4) => 4,
_ => 5
};
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "0123452345", options: TestOptions.DebugExe);
verifier.VerifyDiagnostics();
verifier.VerifyIL("Program.M", @"{
// Code size 98 (0x62)
.maxstack 2
.locals init (int V_0,
int V_1)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: brtrue.s IL_0005
IL_0004: nop
IL_0005: ldarg.0
IL_0006: ldstr """"
IL_000b: call ""bool string.op_Equality(string, string)""
IL_0010: brfalse.s IL_002e
IL_0012: ldarg.1
IL_0013: switch (
IL_0040,
IL_0044,
IL_0048,
IL_004c,
IL_0050)
IL_002c: br.s IL_0054
IL_002e: ldarg.1
IL_002f: ldc.i4.2
IL_0030: beq.s IL_0048
IL_0032: br.s IL_0034
IL_0034: ldarg.1
IL_0035: ldc.i4.3
IL_0036: beq.s IL_004c
IL_0038: br.s IL_003a
IL_003a: ldarg.1
IL_003b: ldc.i4.4
IL_003c: beq.s IL_0050
IL_003e: br.s IL_0054
IL_0040: ldc.i4.0
IL_0041: stloc.0
IL_0042: br.s IL_0058
IL_0044: ldc.i4.1
IL_0045: stloc.0
IL_0046: br.s IL_0058
IL_0048: ldc.i4.2
IL_0049: stloc.0
IL_004a: br.s IL_0058
IL_004c: ldc.i4.3
IL_004d: stloc.0
IL_004e: br.s IL_0058
IL_0050: ldc.i4.4
IL_0051: stloc.0
IL_0052: br.s IL_0058
IL_0054: ldc.i4.5
IL_0055: stloc.0
IL_0056: br.s IL_0058
IL_0058: ldc.i4.1
IL_0059: brtrue.s IL_005c
IL_005b: nop
IL_005c: ldloc.0
IL_005d: stloc.1
IL_005e: br.s IL_0060
IL_0060: ldloc.1
IL_0061: ret
}");
}
[Fact, WorkItem(46536, "https://github.com/dotnet/roslyn/issues/46536")]
public void MultiplePathsToNode_SwitchDispatch_04()
{
var source = @"
using System;
class Program
{
static void Main()
{
Console.Write(M(""a"", ""x"")); // 0
Console.Write(M(""a"", ""y"")); // 1
Console.Write(M(""a"", ""z"")); // 2
Console.Write(M(""a"", ""w"")); // 3
Console.Write(M(""b"", ""z"")); // 2
Console.Write(M(""c"", ""z"")); // 3
Console.Write(M(""c"", ""w"")); // 3
}
static int M(string x, string y)
{
return (x, y) switch
{
(""a"", ""x"") => 0,
(""a"", ""y"") => 1,
(""a"" or ""b"", ""z"") => 2,
_ => 3
};
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "0123233", options: TestOptions.DebugExe, parseOptions: TestOptions.RegularPreview);
verifier.VerifyDiagnostics();
verifier.VerifyIL("Program.M", @"{
// Code size 115 (0x73)
.maxstack 2
.locals init (int V_0,
int V_1)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: brtrue.s IL_0005
IL_0004: nop
IL_0005: ldarg.0
IL_0006: ldstr ""a""
IL_000b: call ""bool string.op_Equality(string, string)""
IL_0010: brtrue.s IL_0021
IL_0012: ldarg.0
IL_0013: ldstr ""b""
IL_0018: call ""bool string.op_Equality(string, string)""
IL_001d: brtrue.s IL_004a
IL_001f: br.s IL_0065
IL_0021: ldarg.1
IL_0022: ldstr ""z""
IL_0027: call ""bool string.op_Equality(string, string)""
IL_002c: brtrue.s IL_0061
IL_002e: ldarg.1
IL_002f: ldstr ""x""
IL_0034: call ""bool string.op_Equality(string, string)""
IL_0039: brtrue.s IL_0059
IL_003b: ldarg.1
IL_003c: ldstr ""y""
IL_0041: call ""bool string.op_Equality(string, string)""
IL_0046: brtrue.s IL_005d
IL_0048: br.s IL_0065
IL_004a: ldarg.1
IL_004b: ldstr ""z""
IL_0050: call ""bool string.op_Equality(string, string)""
IL_0055: brtrue.s IL_0061
IL_0057: br.s IL_0065
IL_0059: ldc.i4.0
IL_005a: stloc.0
IL_005b: br.s IL_0069
IL_005d: ldc.i4.1
IL_005e: stloc.0
IL_005f: br.s IL_0069
IL_0061: ldc.i4.2
IL_0062: stloc.0
IL_0063: br.s IL_0069
IL_0065: ldc.i4.3
IL_0066: stloc.0
IL_0067: br.s IL_0069
IL_0069: ldc.i4.1
IL_006a: brtrue.s IL_006d
IL_006c: nop
IL_006d: ldloc.0
IL_006e: stloc.1
IL_006f: br.s IL_0071
IL_0071: ldloc.1
IL_0072: ret
}");
}
[Fact, WorkItem(46536, "https://github.com/dotnet/roslyn/issues/46536")]
public void MultiplePathsToNode_SwitchDispatch_05()
{
var source = @"
using System;
public enum EnumA { A, B, C }
public enum EnumB { X, Y, Z }
public class Class1
{
public string Repro(EnumA a, EnumB b)
=> (a, b) switch
{
(EnumA.A, EnumB.X) => ""AX"",
(_, EnumB.Y) => ""_Y"",
(EnumA.B, EnumB.X) => ""BZ"",
(_, EnumB.Z) => ""_Z"",
(_, _) => throw new ArgumentException()
};
}
";
var verifier = CompileAndVerify(source, options: TestOptions.DebugDll);
verifier.VerifyDiagnostics();
verifier.VerifyIL("Class1.Repro", @"{
// Code size 90 (0x5a)
.maxstack 2
.locals init (string V_0)
IL_0000: ldc.i4.1
IL_0001: brtrue.s IL_0004
IL_0003: nop
IL_0004: ldarg.1
IL_0005: brtrue.s IL_001b
IL_0007: ldarg.2
IL_0008: switch (
IL_002e,
IL_0036,
IL_0046)
IL_0019: br.s IL_004e
IL_001b: ldarg.2
IL_001c: ldc.i4.1
IL_001d: beq.s IL_0036
IL_001f: ldarg.1
IL_0020: ldc.i4.1
IL_0021: bne.un.s IL_0028
IL_0023: ldarg.2
IL_0024: brfalse.s IL_003e
IL_0026: br.s IL_0028
IL_0028: ldarg.2
IL_0029: ldc.i4.2
IL_002a: beq.s IL_0046
IL_002c: br.s IL_004e
IL_002e: ldstr ""AX""
IL_0033: stloc.0
IL_0034: br.s IL_0054
IL_0036: ldstr ""_Y""
IL_003b: stloc.0
IL_003c: br.s IL_0054
IL_003e: ldstr ""BZ""
IL_0043: stloc.0
IL_0044: br.s IL_0054
IL_0046: ldstr ""_Z""
IL_004b: stloc.0
IL_004c: br.s IL_0054
IL_004e: newobj ""System.ArgumentException..ctor()""
IL_0053: throw
IL_0054: ldc.i4.1
IL_0055: brtrue.s IL_0058
IL_0057: nop
IL_0058: ldloc.0
IL_0059: ret
}");
}
#endregion Pattern Combinators
}
}
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IForLoopStatement.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.Operations
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Partial Public Class IOperationTests
Inherits SemanticModelTestBase
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_SimpleForLoopsTest()
Dim source = <![CDATA[
Public Class MyClass1
Public Shared Sub Main()
Dim myarray As Integer() = New Integer(2) {1, 2, 3}
For i As Integer = 0 To myarray.Length - 1'BIND:"For i As Integer = 0 To myarray.Length - 1"
System.Console.WriteLine(myarray(i))
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For i As In ... Next')
Locals: Local_1: i As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: i As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i As Integer')
Initializer:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
LimitValue:
IBinaryOperation (BinaryOperatorKind.Subtract, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'myarray.Length - 1')
Left:
IPropertyReferenceOperation: ReadOnly Property System.Array.Length As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'myarray.Length')
Instance Receiver:
ILocalReferenceOperation: myarray (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'myarray')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i As In ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i As In ... Next')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For i As In ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... myarray(i))')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... myarray(i))')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'myarray(i)')
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'myarray(i)')
Array reference:
ILocalReferenceOperation: myarray (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'myarray')
Indices(1):
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_SimpleForLoopsTestConversion()
Dim source = <![CDATA[
Option Strict Off
Public Class MyClass1
Public Shared Sub Main()
Dim myarray As Integer() = New Integer(1) {}
myarray(0) = 1
myarray(1) = 2
Dim s As Double = 1.1
For i As Integer = 0 To "1" Step s'BIND:"For i As Integer = 0 To "1" Step s"
System.Console.WriteLine(myarray(i))
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For i As In ... Next')
Locals: Local_1: i As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: i As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i As Integer')
Initializer:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
LimitValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: '"1"')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "1") (Syntax: '"1"')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 's')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.Double) (Syntax: 's')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For i As In ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... myarray(i))')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... myarray(i))')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'myarray(i)')
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'myarray(i)')
Array reference:
ILocalReferenceOperation: myarray (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'myarray')
Indices(1):
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree, TestOptions.ReleaseDll.WithOverflowChecks(False))
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_ForLoopStepIsFloatNegativeVar()
Dim source = <![CDATA[
Option Strict On
Public Class MyClass1
Public Shared Sub Main()
Dim s As Double = -1.1
For i As Double = 2 To 0 Step s'BIND:"For i As Double = 2 To 0 Step s"
System.Console.WriteLine(i)
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For i As Do ... Next')
Locals: Local_1: i As System.Double
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: i As System.Double) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i As Double')
Initializer:
null
InitialValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Double, Constant: 2, IsImplicit) (Syntax: '2')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
LimitValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Double, Constant: 0, IsImplicit) (Syntax: '0')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
StepValue:
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.Double) (Syntax: 's')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For i As Do ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(i)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Double)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(i)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'i')
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Double) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_ForLoopObject()
Dim source = <![CDATA[
Option Strict On
Public Class MyClass1
Public Shared Sub Main()
Dim ctrlVar As Object
Dim initValue As Object = 0
Dim limit As Object = 2
Dim stp As Object = 1
For ctrlVar = initValue To limit Step stp'BIND:"For ctrlVar = initValue To limit Step stp"
System.Console.WriteLine(ctrlVar)
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For ctrlVar ... Next')
LoopControlVariable:
ILocalReferenceOperation: ctrlVar (OperationKind.LocalReference, Type: System.Object) (Syntax: 'ctrlVar')
InitialValue:
ILocalReferenceOperation: initValue (OperationKind.LocalReference, Type: System.Object) (Syntax: 'initValue')
LimitValue:
ILocalReferenceOperation: limit (OperationKind.LocalReference, Type: System.Object) (Syntax: 'limit')
StepValue:
ILocalReferenceOperation: stp (OperationKind.LocalReference, Type: System.Object) (Syntax: 'stp')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For ctrlVar ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... ne(ctrlVar)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... ne(ctrlVar)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'ctrlVar')
ILocalReferenceOperation: ctrlVar (OperationKind.LocalReference, Type: System.Object) (Syntax: 'ctrlVar')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_ForLoopNested()
Dim source = <![CDATA[
Option Strict On
Option Infer On
Public Class MyClass1
Public Shared Sub Main()
For AVarName = 1 To 2'BIND:"For AVarName = 1 To 2"
For B = 1 To 2
For C = 1 To 2
For D = 1 To 2
Next D
Next C
Next B
Next AVarName
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For AVarNam ... xt AVarName')
Locals: Local_1: AVarName As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: AVarName As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'AVarName')
Initializer:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For AVarNam ... xt AVarName')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For AVarNam ... xt AVarName')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For AVarNam ... xt AVarName')
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 2, Exit Label Id: 3, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For B = 1 T ... Next B')
Locals: Local_1: B As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: B As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'B')
Initializer:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For B = 1 T ... Next B')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For B = 1 T ... Next B')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For B = 1 T ... Next B')
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 4, Exit Label Id: 5, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For C = 1 T ... Next C')
Locals: Local_1: C As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: C As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'C')
Initializer:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For C = 1 T ... Next C')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For C = 1 T ... Next C')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For C = 1 T ... Next C')
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 6, Exit Label Id: 7, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For D = 1 T ... Next D')
Locals: Local_1: D As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: D As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'D')
Initializer:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For D = 1 T ... Next D')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For D = 1 T ... Next D')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For D = 1 T ... Next D')
NextVariables(1):
ILocalReferenceOperation: D (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'D')
NextVariables(1):
ILocalReferenceOperation: C (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'C')
NextVariables(1):
ILocalReferenceOperation: B (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'B')
NextVariables(1):
ILocalReferenceOperation: AVarName (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'AVarName')
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_ChangeOuterVarInInnerFor()
Dim source = <![CDATA[
Option Strict On
Option Infer On
Public Class MyClass1
Public Shared Sub Main()
For I = 1 To 2'BIND:"For I = 1 To 2"
For J = 1 To 2
I = 3
System.Console.WriteLine(I)
Next
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For I = 1 T ... Next')
Locals: Local_1: I As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: I As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'I')
Initializer:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For I = 1 T ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For I = 1 T ... Next')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For I = 1 T ... Next')
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 2, Exit Label Id: 3, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For J = 1 T ... Next')
Locals: Local_1: J As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: J As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'J')
Initializer:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For J = 1 T ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For J = 1 T ... Next')
Body:
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For J = 1 T ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'I = 3')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'I = 3')
Left:
ILocalReferenceOperation: I (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'I')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(I)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(I)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'I')
ILocalReferenceOperation: I (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'I')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
NextVariables(0)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_InnerForRefOuterForVar()
Dim source = <![CDATA[
Option Strict On
Option Infer On
Public Class MyClass1
Public Shared Sub Main()
For I = 1 To 2'BIND:"For I = 1 To 2"
For J = I + 1 To 2
System.Console.WriteLine(J)
Next
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For I = 1 T ... Next')
Locals: Local_1: I As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: I As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'I')
Initializer:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For I = 1 T ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For I = 1 T ... Next')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For I = 1 T ... Next')
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 2, Exit Label Id: 3, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For J = I + ... Next')
Locals: Local_1: J As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: J As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'J')
Initializer:
null
InitialValue:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'I + 1')
Left:
ILocalReferenceOperation: I (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'I')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For J = I + ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For J = I + ... Next')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For J = I + ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(J)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(J)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'J')
ILocalReferenceOperation: J (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'J')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
NextVariables(0)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_ExitNestedFor()
Dim source = <![CDATA[
Option Strict On
Option Infer On
Public Class MyClass1
Public Shared Sub Main()
For I = 1 To 2'BIND:"For I = 1 To 2"
For J = 1 To 2
Exit For
Next
System.Console.WriteLine(I)
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For I = 1 T ... Next')
Locals: Local_1: I As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: I As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'I')
Initializer:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For I = 1 T ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For I = 1 T ... Next')
Body:
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For I = 1 T ... Next')
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 2, Exit Label Id: 3, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For J = 1 T ... Next')
Locals: Local_1: J As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: J As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'J')
Initializer:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For J = 1 T ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For J = 1 T ... Next')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For J = 1 T ... Next')
IBranchOperation (BranchKind.Break, Label Id: 3) (OperationKind.Branch, Type: null) (Syntax: 'Exit For')
NextVariables(0)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(I)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(I)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'I')
ILocalReferenceOperation: I (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'I')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_EnumAsStart()
Dim source = <![CDATA[
Option Strict Off
Option Infer Off
Public Class MyClass1
Public Shared Sub Main()
For x As e1 = e1.a To e1.c'BIND:"For x As e1 = e1.a To e1.c"
Next
End Sub
End Class
Enum e1
a
b
c
End Enum
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x As e1 ... Next')
Locals: Local_1: x As e1
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: x As e1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x As e1')
Initializer:
null
InitialValue:
IFieldReferenceOperation: e1.a (Static) (OperationKind.FieldReference, Type: e1, Constant: 0) (Syntax: 'e1.a')
Instance Receiver:
null
LimitValue:
IFieldReferenceOperation: e1.c (Static) (OperationKind.FieldReference, Type: e1, Constant: 2) (Syntax: 'e1.c')
Instance Receiver:
null
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: e1, Constant: 1, IsImplicit) (Syntax: 'For x As e1 ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x As e1 ... Next')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x As e1 ... Next')
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_PropertyAsStart()
Dim source = <![CDATA[
Option Strict Off
Option Infer Off
Public Class MyClass1
Property P1(ByVal x As Long) As Byte
Get
Return x - 10
End Get
Set(ByVal Value As Byte)
End Set
End Property
Public Shared Sub Main()
End Sub
Public Sub F()
For i As Integer = P1(30 + i) To 30'BIND:"For i As Integer = P1(30 + i) To 30"
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For i As In ... Next')
Locals: Local_1: i As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: i As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i As Integer')
Initializer:
null
InitialValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'P1(30 + i)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IPropertyReferenceOperation: Property MyClass1.P1(x As System.Int64) As System.Byte (OperationKind.PropertyReference, Type: System.Byte) (Syntax: 'P1(30 + i)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: MyClass1, IsImplicit) (Syntax: 'P1')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '30 + i')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: '30 + i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: '30 + i')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30')
Right:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i As In ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i As In ... Next')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For i As In ... Next')
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_FieldNameAsIteration()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Public Class MyClass1
Dim global_x As Integer = 10
Const global_y As Long = 20
Public Shared Sub Main()
For global_x As Integer = global_y To 10'BIND:"For global_x As Integer = global_y To 10"
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For global_ ... Next')
Locals: Local_1: global_x As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: global_x As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'global_x As Integer')
Initializer:
null
InitialValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: 'global_y')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IFieldReferenceOperation: MyClass1.global_y As System.Int64 (Static) (OperationKind.FieldReference, Type: System.Int64, Constant: 20) (Syntax: 'global_y')
Instance Receiver:
null
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For global_ ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For global_ ... Next')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For global_ ... Next')
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_SingleLine()
Dim source = <![CDATA[
Option Strict On
Public Class MyClass1
Public Shared Sub Main()
For x As Integer = 0 To 10 : Next'BIND:"For x As Integer = 0 To 10 : Next"
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x As In ... o 10 : Next')
Locals: Local_1: x As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: x As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x As Integer')
Initializer:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x As In ... o 10 : Next')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x As In ... o 10 : Next')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x As In ... o 10 : Next')
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_VarDeclOutOfForeach()
Dim source = <![CDATA[
Option Strict On
Option Infer On
Public Class MyClass1
Public Shared Sub Main()
Dim Y As Integer
For Y = 1 To 2'BIND:"For Y = 1 To 2"
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For Y = 1 T ... Next')
LoopControlVariable:
ILocalReferenceOperation: Y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'Y')
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For Y = 1 T ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For Y = 1 T ... Next')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Y = 1 T ... Next')
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_GetDeclaredSymbolOfForStatement()
Dim source = <![CDATA[
Option Strict On
Option Infer On
Imports System
Imports System.Collection
Class C1
Public Shared Sub Main()
For element1 = 23 To 42'BIND:"For element1 = 23 To 42"
Next
For element2 As Integer = 23 To 42
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For element ... Next')
Locals: Local_1: element1 As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: element1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'element1')
Initializer:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 23) (Syntax: '23')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For element ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For element ... Next')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For element ... Next')
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_ForLoopContinue()
Dim source = <![CDATA[
Option Strict On
Option Infer On
Imports System
Imports System.Collection
Class C1
Public Shared Sub Main()
For i As Integer = 0 To 5'BIND:"For i As Integer = 0 To 5"
If i Mod 2 = 0 Then
Continue For
End If
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For i As In ... Next')
Locals: Local_1: i As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: i As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i As Integer')
Initializer:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i As In ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i As In ... Next')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For i As In ... Next')
IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If i Mod 2 ... End If')
Condition:
IBinaryOperation (BinaryOperatorKind.Equals, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i Mod 2 = 0')
Left:
IBinaryOperation (BinaryOperatorKind.Remainder, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i Mod 2')
Left:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
WhenTrue:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If i Mod 2 ... End If')
IBranchOperation (BranchKind.Continue, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'Continue For')
WhenFalse:
null
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_ForReverse()
Dim source = <![CDATA[
Option Infer On
Module Program
Sub Main()
For X = 10 To 0'BIND:"For X = 10 To 0"
Next
End Sub
End Module
Module M
Public X As Integer
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For X = 10 ... Next')
LoopControlVariable:
IFieldReferenceOperation: M.X As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'X')
Instance Receiver:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For X = 10 ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For X = 10 ... Next')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For X = 10 ... Next')
NextVariables(0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ForBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_InValid()
Dim source = <![CDATA[
Option Infer On
Module Program
Sub Main()
For X = 10 To 0'BIND:"For X = 10 To 0"
Next
End Sub
End Module
Module M
Public X As String
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null, IsInvalid) (Syntax: 'For X = 10 ... Next')
LoopControlVariable:
IFieldReferenceOperation: M.X As System.String (Static) (OperationKind.FieldReference, Type: System.String, IsInvalid) (Syntax: 'X')
Instance Receiver:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
StepValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'For X = 10 ... Next')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'For X = 10 ... Next')
NextVariables(0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30337: 'For' loop control variable cannot be of type 'String' because the type does not support the required operators.
For X = 10 To 0'BIND:"For X = 10 To 0"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ForBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_ForCombined()
Dim source = <![CDATA[
Option Infer On
Module Program
Sub Main(args As String())
For A = 1 To 2'BIND:"For A = 1 To 2"
For B = A To 2
Next B, A
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For A = 1 T ... Next B, A')
Locals: Local_1: A As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: A As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'A')
Initializer:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For A = 1 T ... Next B, A')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For A = 1 T ... Next B, A')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For A = 1 T ... Next B, A')
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 2, Exit Label Id: 3, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For B = A T ... Next B, A')
Locals: Local_1: B As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: B As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'B')
Initializer:
null
InitialValue:
ILocalReferenceOperation: A (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'A')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For B = A T ... Next B, A')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For B = A T ... Next B, A')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For B = A T ... Next B, A')
NextVariables(2):
ILocalReferenceOperation: B (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'B')
ILocalReferenceOperation: A (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'A')
NextVariables(0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ForBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub VerifyForToLoop1()
Dim source = <![CDATA[
Structure C
Sub F()
Dim x As Integer
Dim y As Integer = 16
For x = 12 To y 'BIND:"For x = 12 To y"
Next
End Sub
End Structure
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x = 12 ... Next')
LoopControlVariable:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12')
LimitValue:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x = 12 ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x = 12 ... Next')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x = 12 ... Next')
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub VerifyForToLoop2()
Dim source = <![CDATA[
Structure C
Sub F()
Dim x As Integer?
Dim y As Integer = 16
For x = 12 To y 'BIND:"For x = 12 To y"
Next
End Sub
End Structure
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x = 12 ... Next')
LoopControlVariable:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'x')
InitialValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '12')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12')
LimitValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'y')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'For x = 12 ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x = 12 ... Next')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x = 12 ... Next')
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub VerifyForToLoop3()
Dim source = <![CDATA[
Structure C
Sub F()
Dim x As Integer
Dim y As Integer? = 16
For x = 12 To y 'BIND:"For x = 12 To y"
Next
End Sub
End Structure
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x = 12 ... Next')
LoopControlVariable:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12')
LimitValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'y')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'y')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x = 12 ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x = 12 ... Next')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x = 12 ... Next')
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub VerifyForToLoop4()
Dim source = <![CDATA[
Structure C
Sub F()
Dim x As Integer?
Dim y As Integer? = 16
For x = 12 To y 'BIND:"For x = 12 To y"
Next
End Sub
End Structure
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x = 12 ... Next')
LoopControlVariable:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'x')
InitialValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '12')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12')
LimitValue:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'y')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'For x = 12 ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x = 12 ... Next')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x = 12 ... Next')
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub VerifyForToLoop5()
Dim source = <![CDATA[
Structure C
Sub F()
Dim x As Integer
Dim y As Integer = 16
Dim s As Integer? = nothing
For x = 12 To y Step s 'BIND:"For x = 12 To y Step s"
Next
End Sub
End Structure
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x = 12 ... Next')
LoopControlVariable:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12')
LimitValue:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 's')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 's')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x = 12 ... Next')
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub VerifyForToLoop6()
Dim source = <![CDATA[
Structure C
Sub F()
Dim x As Integer?
Dim y As Integer = 16
Dim s As Integer? = nothing
For x = 12 To y Step s 'BIND:"For x = 12 To y Step s"
Next
End Sub
End Structure
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x = 12 ... Next')
LoopControlVariable:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'x')
InitialValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '12')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12')
LimitValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'y')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y')
StepValue:
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 's')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x = 12 ... Next')
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub VerifyForToLoop7()
Dim source = <![CDATA[
Structure C
Sub F()
Dim x As Integer
Dim y As Integer? = 16
Dim s As Integer? = nothing
For x = 12 To y Step s 'BIND:"For x = 12 To y Step s"
Next
End Sub
End Structure
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x = 12 ... Next')
LoopControlVariable:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12')
LimitValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'y')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'y')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 's')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 's')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x = 12 ... Next')
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub VerifyForToLoop8()
Dim source = <![CDATA[
Structure C
Sub F()
Dim x As Integer?
Dim y As Integer? = 16
Dim s As Integer? = nothing
For x = 12 To y Step s 'BIND:"For x = 12 To y Step s"
Next
End Sub
End Structure
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x = 12 ... Next')
LoopControlVariable:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'x')
InitialValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '12')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12')
LimitValue:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'y')
StepValue:
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 's')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x = 12 ... Next')
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub VerifyForToLoop_FieldAsIterationVariable()
Dim source = <![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class C
Private X As Integer = 0
Sub M()
For X = 0 To 10'BIND:"For X = 0 To 10"
Next X
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For X = 0 T ... Next X')
LoopControlVariable:
IFieldReferenceOperation: C.X As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'X')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X')
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For X = 0 T ... Next X')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For X = 0 T ... Next X')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For X = 0 T ... Next X')
NextVariables(1):
IFieldReferenceOperation: C.X As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'X')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ForBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub VerifyForToLoop_FieldWithExplicitReceiverAsIterationVariable()
Dim source = <![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class C
Private X As Integer = 0
Sub M(c As C)
For c.X = 0 To 10'BIND:"For c.X = 0 To 10"
Next c.X
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For c.X = 0 ... Next c.X')
LoopControlVariable:
IFieldReferenceOperation: C.X As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'c.X')
Instance Receiver:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c')
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For c.X = 0 ... Next c.X')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For c.X = 0 ... Next c.X')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For c.X = 0 ... Next c.X')
NextVariables(1):
IFieldReferenceOperation: C.X As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'c.X')
Instance Receiver:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ForBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub VerifyForToLoop_InvalidLoopControlVariableDeclaration()
Dim source = <![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class C
Sub M()
Dim i as Integer = 0
For i as Integer = 0 To 10'BIND:"For i as Integer = 0 To 10"
Next i
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null, IsInvalid) (Syntax: 'For i as In ... Next i')
Locals: Local_1: i As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: i As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i as Integer')
Initializer:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'For i as In ... Next i')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'For i as In ... Next i')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'For i as In ... Next i')
NextVariables(1):
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30616: Variable 'i' hides a variable in an enclosing block.
For i as Integer = 0 To 10'BIND:"For i as Integer = 0 To 10"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ForBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_01()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(result As Integer) 'BIND:"Sub M"
For i As UInteger = 0UI To 2UI
result = if(i > 0UI, 3, 4)
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
Locals: [i As System.UInt32]
CaptureIds: [2] [3]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i As UInteger')
Value:
ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.UInt32, IsImplicit) (Syntax: 'i As UInteger')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '0UI')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.UInt32, Constant: 0) (Syntax: '0UI')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2UI')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.UInt32, Constant: 2) (Syntax: '2UI')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'For i As UI ... Next')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.UInt32, Constant: 1, IsImplicit) (Syntax: 'For i As UI ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningNumeric, InvolvesNarrowingFromNumericConstant)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i As UI ... Next')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '0UI')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.UInt32, IsImplicit) (Syntax: 'i As UInteger')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.UInt32, Constant: 0, IsImplicit) (Syntax: '0UI')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B7]
Statements (0)
Jump if False (Regular) to Block[B8]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '2UI')
Left:
ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.UInt32, IsImplicit) (Syntax: 'i As UInteger')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.UInt32, Constant: 2, IsImplicit) (Syntax: '2UI')
Leaving: {R1}
Next (Regular) Block[B3]
Entering: {R3}
.locals {R3}
{
CaptureIds: [4] [5]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
Jump if False (Regular) to Block[B5]
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i > 0UI')
Left:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt32) (Syntax: 'i')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.UInt32, Constant: 0) (Syntax: '0UI')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Next (Regular) Block[B6]
Block[B5] - Block
Predecessors: [B3]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '4')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = if ... 0UI, 3, 4)')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = if ... 0UI, 3, 4)')
Left:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'if(i > 0UI, 3, 4)')
Next (Regular) Block[B7]
Leaving: {R3}
}
Block[B7] - Block
Predecessors: [B6]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i As UInteger')
Left:
ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.UInt32, IsImplicit) (Syntax: 'i As UInteger')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.UInt32, IsImplicit) (Syntax: 'For i As UI ... Next')
Left:
ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.UInt32, IsImplicit) (Syntax: 'i As UInteger')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.UInt32, Constant: 1, IsImplicit) (Syntax: 'For i As UI ... Next')
Next (Regular) Block[B2]
}
Block[B8] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_02()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As Integer, result As Integer) 'BIND:"Sub M"
For i = 0 To 4 Step 2
result = i
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '0')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '4')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '0')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '0')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '4')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 4, IsImplicit) (Syntax: '4')
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: '2')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '2')
Next (Regular) Block[B2]
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseDll.WithOverflowChecks(False))
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_03()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As Decimal, result As Decimal) 'BIND:"Sub M"
For i = 3D To 0D Step -1D
result = i
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3D')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Decimal, Constant: 3) (Syntax: '3D')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '0D')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Decimal, Constant: 0) (Syntax: '0D')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '-1D')
Value:
IUnaryOperation (UnaryOperatorKind.Minus, Checked) (OperationKind.Unary, Type: System.Decimal, Constant: -1) (Syntax: '-1D')
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Decimal, Constant: 1) (Syntax: '1D')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '3D')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Decimal, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Decimal, Constant: 3, IsImplicit) (Syntax: '3D')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '0D')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Decimal, Constant: 0, IsImplicit) (Syntax: '0D')
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Decimal, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Decimal) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Decimal, IsImplicit) (Syntax: '-1D')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Decimal, Constant: -1, IsImplicit) (Syntax: '-1D')
Next (Regular) Block[B2]
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_04()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As Short, [step] As Short, result As Short) 'BIND:"Sub M"
For i = 0S To 4S Step [step]
result = i
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int16) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '0S')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int16, Constant: 0) (Syntax: '0S')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '4S')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int16, Constant: 4) (Syntax: '4S')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: System.Int16) (Syntax: '[step]')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '0S')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int16, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int16, Constant: 0, IsImplicit) (Syntax: '0S')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '4S')
Left:
IBinaryOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.Binary, Type: System.Int16, IsImplicit) (Syntax: 'i')
Left:
IBinaryOperation (BinaryOperatorKind.RightShift) (OperationKind.Binary, Type: System.Int16, IsImplicit) (Syntax: 'i')
Left:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int16, IsImplicit) (Syntax: '[step]')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 15, IsImplicit) (Syntax: 'i')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int16, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.Binary, Type: System.Int16, IsImplicit) (Syntax: '4S')
Left:
IBinaryOperation (BinaryOperatorKind.RightShift) (OperationKind.Binary, Type: System.Int16, IsImplicit) (Syntax: '4S')
Left:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int16, IsImplicit) (Syntax: '[step]')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 15, IsImplicit) (Syntax: '4S')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int16, Constant: 4, IsImplicit) (Syntax: '4S')
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int16, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int16) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int16) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int16, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int16, IsImplicit) (Syntax: '[step]')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int16, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int16, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_05()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As Decimal, [step] As Decimal, result As Decimal) 'BIND:"Sub M"
For i = 3D To 0D Step [step]
result = i
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3] [4]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (6)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3D')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Decimal, Constant: 3) (Syntax: '3D')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '0D')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Decimal, Constant: 0) (Syntax: '0D')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: System.Decimal) (Syntax: '[step]')
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Left:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Decimal, IsImplicit) (Syntax: '[step]')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Decimal, Constant: 0, IsImplicit) (Syntax: '[step]')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '3D')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Decimal, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Decimal, Constant: 3, IsImplicit) (Syntax: '3D')
Next (Regular) Block[B2]
Leaving: {R2}
Entering: {R3}
}
.locals {R3}
{
CaptureIds: [5]
Block[B2] - Block
Predecessors: [B1] [B5]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal, IsImplicit) (Syntax: 'i')
Jump if False (Regular) to Block[B4]
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B6]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '0D')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Decimal, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Decimal, Constant: 0, IsImplicit) (Syntax: '0D')
Leaving: {R3} {R1}
Next (Regular) Block[B5]
Leaving: {R3}
Block[B4] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B6]
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '0D')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Decimal, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Decimal, Constant: 0, IsImplicit) (Syntax: '0D')
Leaving: {R3} {R1}
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Decimal, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Decimal) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Decimal, IsImplicit) (Syntax: '[step]')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Decimal, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
Entering: {R3}
}
Block[B6] - Exit
Predecessors: [B3] [B4]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_06()
Dim source = <![CDATA[
Imports System
Public Enum MyEnum As UShort
One = 1
End Enum
Public Class C
Sub M(i as MyEnum, init As MyEnum, limit As MyEnum, [step] as MyEnum, result As MyEnum) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init')
Value:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit')
Value:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: MyEnum) (Syntax: '[step]')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'init')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'limit')
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: MyEnum, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: MyEnum, IsImplicit) (Syntax: '[step]')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_07()
Dim source = <![CDATA[
Imports System
Public Enum MyEnum As SByte
One = 1
End Enum
Public Class C
Sub M(i as MyEnum, init As MyEnum, limit As MyEnum, [step] as MyEnum, result As MyEnum) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init')
Value:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit')
Value:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: MyEnum) (Syntax: '[step]')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'init')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Left:
IBinaryOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.Binary, Type: MyEnum, IsImplicit) (Syntax: 'i')
Left:
IBinaryOperation (BinaryOperatorKind.RightShift) (OperationKind.Binary, Type: MyEnum, IsImplicit) (Syntax: 'i')
Left:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: '[step]')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 7, IsImplicit) (Syntax: 'i')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.Binary, Type: MyEnum, IsImplicit) (Syntax: 'limit')
Left:
IBinaryOperation (BinaryOperatorKind.RightShift) (OperationKind.Binary, Type: MyEnum, IsImplicit) (Syntax: 'limit')
Left:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: '[step]')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 7, IsImplicit) (Syntax: 'limit')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'limit')
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: MyEnum, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: MyEnum, IsImplicit) (Syntax: '[step]')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_08()
Dim source = <![CDATA[
Imports System
Public Enum MyEnum As Long
MinusOne = -1
End Enum
Public Class C
Sub M(i as MyEnum, init As MyEnum, limit As MyEnum, result As MyEnum) 'BIND:"Sub M"
For i = init To limit Step MyEnum.MinusOne
result = i
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init')
Value:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit')
Value:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'MyEnum.MinusOne')
Value:
IFieldReferenceOperation: MyEnum.MinusOne (Static) (OperationKind.FieldReference, Type: MyEnum, Constant: -1) (Syntax: 'MyEnum.MinusOne')
Instance Receiver:
null
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'init')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'limit')
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: MyEnum, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: MyEnum, IsImplicit) (Syntax: 'MyEnum.MinusOne')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: MyEnum, Constant: -1, IsImplicit) (Syntax: 'MyEnum.MinusOne')
Next (Regular) Block[B2]
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_09()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As Integer?, init As Integer?, limit As Integer?, [step] As Integer?, result As Integer?) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3] [4]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (4)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init')
Value:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit')
Value:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: '[step]')
Jump if False (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Operand:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Left:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: '[step]')
Instance Receiver:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]')
Arguments(0)
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'init')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B5] - Block
Predecessors: [B4] [B11] [B12]
Statements (0)
Jump if False (Regular) to Block[B6]
IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Left:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'limit')
Right:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i')
Operand:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Entering: {R3}
Next (Regular) Block[B13]
Leaving: {R1}
.locals {R3}
{
CaptureIds: [5]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i')
Instance Receiver:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Arguments(0)
Jump if False (Regular) to Block[B8]
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B6]
Statements (0)
Jump if False (Regular) to Block[B13]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'limit')
Instance Receiver:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'limit')
Arguments(0)
Leaving: {R3} {R1}
Next (Regular) Block[B9]
Leaving: {R3}
Block[B8] - Block
Predecessors: [B6]
Statements (0)
Jump if False (Regular) to Block[B13]
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'limit')
Instance Receiver:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'limit')
Arguments(0)
Leaving: {R3} {R1}
Next (Regular) Block[B9]
Leaving: {R3}
}
Block[B9] - Block
Predecessors: [B7] [B8]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i')
Next (Regular) Block[B10]
Entering: {R4}
.locals {R4}
{
CaptureIds: [6]
Block[B10] - Block
Predecessors: [B9]
Statements (1)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Jump if False (Regular) to Block[B12]
IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Left:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Operand:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]')
Right:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i')
Operand:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B10]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Right:
IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Next (Regular) Block[B5]
Leaving: {R4}
Block[B12] - Block
Predecessors: [B10]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningNullable)
Operand:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: '[step]')
Left:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i')
Instance Receiver:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Arguments(0)
Right:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: '[step]')
Instance Receiver:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R4}
}
}
Block[B13] - Exit
Predecessors: [B5] [B7] [B8]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_10()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As C, init As C, limit As C, [step] As C, result As C) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC33038: Type 'C' must define operator '-' to be used in a 'For' statement.
For i = init To limit Step [step]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC33038: Type 'C' must define operator '+' to be used in a 'For' statement.
For i = init To limit Step [step]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC33038: Type 'C' must define operator '<=' to be used in a 'For' statement.
For i = init To limit Step [step]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC33038: Type 'C' must define operator '>=' to be used in a 'For' statement.
For i = init To limit Step [step]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'init')
Value:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'limit')
Value:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: '[step]')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'init')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'limit')
Children(2):
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'limit')
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_11()
Dim source = <![CDATA[
Imports System
Public Structure C
Sub M(i As C?, init As C?, limit As C?, [step] As C?, result As C?) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
End Structure]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC33038: Type 'C?' must define operator '-' to be used in a 'For' statement.
For i = init To limit Step [step]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC33038: Type 'C?' must define operator '+' to be used in a 'For' statement.
For i = init To limit Step [step]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC33038: Type 'C?' must define operator '<=' to be used in a 'For' statement.
For i = init To limit Step [step]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC33038: Type 'C?' must define operator '>=' to be used in a 'For' statement.
For i = init To limit Step [step]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsInvalid) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'init')
Value:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsInvalid) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'limit')
Value:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsInvalid) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsInvalid) (Syntax: '[step]')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'init')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B5] [B6]
Statements (0)
Jump if False (Regular) to Block[B7]
IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'limit')
Children(2):
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'i')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'limit')
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'i')
Next (Regular) Block[B4]
Entering: {R3}
.locals {R3}
{
CaptureIds: [4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'i')
Jump if False (Regular) to Block[B6]
IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '[step]')
Left:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '[step]')
Operand:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: '[step]')
Right:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'i')
Operand:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'i')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Left:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'i')
Next (Regular) Block[B2]
Leaving: {R3}
Block[B6] - Block
Predecessors: [B4]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Left:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: '[step]')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningNullable)
Operand:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]')
Left:
IInvocationOperation ( Function System.Nullable(Of C).GetValueOrDefault() As C) (OperationKind.Invocation, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Instance Receiver:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'i')
Arguments(0)
Right:
IInvocationOperation ( Function System.Nullable(Of C).GetValueOrDefault() As C) (OperationKind.Invocation, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]')
Instance Receiver:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: '[step]')
Arguments(0)
Next (Regular) Block[B2]
Leaving: {R3}
}
}
Block[B7] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_12()
Dim source = <![CDATA[
Imports System
Public Class C1
Sub M(i As C1, init As C2, limit As C3, [step] As C4, result As C1) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
End Class
Public Class C2
End Class
Public Class C3
End Class
Public Class C4
End Class
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30311: Value of type 'C2' cannot be converted to 'C1'.
For i = init To limit Step [step]
~~~~
BC30311: Value of type 'C3' cannot be converted to 'C1'.
For i = init To limit Step [step]
~~~~~
BC30311: Value of type 'C4' cannot be converted to 'C1'.
For i = init To limit Step [step]
~~~~~~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C1) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'init')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: C1, IsInvalid, IsImplicit) (Syntax: 'init')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(DelegateRelaxationLevelNone)
Operand:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C2, IsInvalid) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'limit')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: C1, IsInvalid, IsImplicit) (Syntax: 'limit')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(DelegateRelaxationLevelNone)
Operand:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C3, IsInvalid) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '[step]')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: C1, IsInvalid, IsImplicit) (Syntax: '[step]')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(DelegateRelaxationLevelNone)
Operand:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C4, IsInvalid) (Syntax: '[step]')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'init')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'limit')
Children(2):
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'i')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'limit')
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C1) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C1) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: C1, IsInvalid, IsImplicit) (Syntax: '[step]')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C1, IsInvalid, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_13()
Dim source = <![CDATA[
Imports System
Public Enum MyEnum As Integer
MinusOne = -1
End Enum
Public Class C
Sub M(i As MyEnum?, init As MyEnum?, limit As MyEnum?, [step] As MyEnum?, result As MyEnum?) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3] [4]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (4)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum)) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init')
Value:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum)) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit')
Value:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum)) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum)) (Syntax: '[step]')
Jump if False (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Operand:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Left:
IInvocationOperation ( Function System.Nullable(Of MyEnum).GetValueOrDefault() As MyEnum) (OperationKind.Invocation, Type: MyEnum, IsImplicit) (Syntax: '[step]')
Instance Receiver:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: '[step]')
Arguments(0)
Right:
ILiteralOperation (OperationKind.Literal, Type: MyEnum, Constant: 0, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'init')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B5] - Block
Predecessors: [B4] [B11] [B12]
Statements (0)
Jump if False (Regular) to Block[B6]
IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Left:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'limit')
Right:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i')
Operand:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i')
Entering: {R3}
Next (Regular) Block[B13]
Leaving: {R1}
.locals {R3}
{
CaptureIds: [5]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IInvocationOperation ( Function System.Nullable(Of MyEnum).GetValueOrDefault() As MyEnum) (OperationKind.Invocation, Type: MyEnum, IsImplicit) (Syntax: 'i')
Instance Receiver:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i')
Arguments(0)
Jump if False (Regular) to Block[B8]
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B6]
Statements (0)
Jump if False (Regular) to Block[B13]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'i')
Right:
IInvocationOperation ( Function System.Nullable(Of MyEnum).GetValueOrDefault() As MyEnum) (OperationKind.Invocation, Type: MyEnum, IsImplicit) (Syntax: 'limit')
Instance Receiver:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'limit')
Arguments(0)
Leaving: {R3} {R1}
Next (Regular) Block[B9]
Leaving: {R3}
Block[B8] - Block
Predecessors: [B6]
Statements (0)
Jump if False (Regular) to Block[B13]
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'i')
Right:
IInvocationOperation ( Function System.Nullable(Of MyEnum).GetValueOrDefault() As MyEnum) (OperationKind.Invocation, Type: MyEnum, IsImplicit) (Syntax: 'limit')
Instance Receiver:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'limit')
Arguments(0)
Leaving: {R3} {R1}
Next (Regular) Block[B9]
Leaving: {R3}
}
Block[B9] - Block
Predecessors: [B7] [B8]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum)) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum)) (Syntax: 'i')
Next (Regular) Block[B10]
Entering: {R4}
.locals {R4}
{
CaptureIds: [6]
Block[B10] - Block
Predecessors: [B9]
Statements (1)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i')
Jump if False (Regular) to Block[B12]
IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Left:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Operand:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: '[step]')
Right:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i')
Operand:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i')
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B10]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i')
Right:
IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i')
Next (Regular) Block[B5]
Leaving: {R4}
Block[B12] - Block
Predecessors: [B10]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: '[step]')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningNullable)
Operand:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: MyEnum, IsImplicit) (Syntax: '[step]')
Left:
IInvocationOperation ( Function System.Nullable(Of MyEnum).GetValueOrDefault() As MyEnum) (OperationKind.Invocation, Type: MyEnum, IsImplicit) (Syntax: 'i')
Instance Receiver:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i')
Arguments(0)
Right:
IInvocationOperation ( Function System.Nullable(Of MyEnum).GetValueOrDefault() As MyEnum) (OperationKind.Invocation, Type: MyEnum, IsImplicit) (Syntax: '[step]')
Instance Receiver:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: '[step]')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R4}
}
}
Block[B13] - Exit
Predecessors: [B5] [B7] [B8]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub ForToFlow_14()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(c1 As C, c2 As C, bInit As Boolean, init1 As Integer, init2 As Integer, bLimit As Boolean, limit1 As Integer, limit2 As Integer, result As Boolean) 'BIND:"Sub M"
For If(c1, c2).i = If(bInit, init1, init2) To If(bLimit, limit1, limit2) Step 2
result = true
Next
End Sub
Public i As Integer
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2} {R3} {R4}
.locals {R1}
{
CaptureIds: [4] [5]
.locals {R2}
{
CaptureIds: [2] [3]
.locals {R3}
{
CaptureIds: [1]
.locals {R4}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R4}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B4]
Leaving: {R4}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B5] - Block
Predecessors: [B4]
Statements (0)
Jump if False (Regular) to Block[B7]
IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1')
Value:
IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'init1')
Next (Regular) Block[B8]
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2')
Value:
IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'init2')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (0)
Jump if False (Regular) to Block[B10]
IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit')
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1')
Value:
IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'limit1')
Next (Regular) Block[B11]
Block[B10] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2')
Value:
IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'limit2')
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B9] [B10]
Statements (2)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)')
Left:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bInit, init1, init2)')
Next (Regular) Block[B12]
Leaving: {R2}
Entering: {R5} {R6}
}
.locals {R5}
{
CaptureIds: [7]
.locals {R6}
{
CaptureIds: [6]
Block[B12] - Block
Predecessors: [B11] [B24]
Statements (1)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B14]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R6}
Next (Regular) Block[B13]
Block[B13] - Block
Predecessors: [B12]
Statements (1)
IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B15]
Leaving: {R6}
}
Block[B14] - Block
Predecessors: [B12]
Statements (1)
IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B15]
Block[B15] - Block
Predecessors: [B13] [B14]
Statements (0)
Jump if False (Regular) to Block[B25]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Left:
IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Right:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Leaving: {R5} {R1}
Next (Regular) Block[B16]
Leaving: {R5}
}
Block[B16] - Block
Predecessors: [B15]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B17]
Entering: {R7} {R8} {R9}
.locals {R7}
{
CaptureIds: [10] [12]
.locals {R8}
{
CaptureIds: [9]
.locals {R9}
{
CaptureIds: [8]
Block[B17] - Block
Predecessors: [B16]
Statements (1)
IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B19]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R9}
Next (Regular) Block[B18]
Block[B18] - Block
Predecessors: [B17]
Statements (1)
IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B20]
Leaving: {R9}
}
Block[B19] - Block
Predecessors: [B17]
Statements (1)
IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B20]
Block[B20] - Block
Predecessors: [B18] [B19]
Statements (1)
IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B21]
Leaving: {R8}
Entering: {R10}
}
.locals {R10}
{
CaptureIds: [11]
Block[B21] - Block
Predecessors: [B20]
Statements (1)
IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B23]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R10}
Next (Regular) Block[B22]
Block[B22] - Block
Predecessors: [B21]
Statements (1)
IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B24]
Leaving: {R10}
}
Block[B23] - Block
Predecessors: [B21]
Statements (1)
IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B24]
Block[B24] - Block
Predecessors: [B22] [B23]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Left:
IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: '2')
Left:
IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Right:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '2')
Next (Regular) Block[B12]
Leaving: {R7}
Entering: {R5} {R6}
}
}
Block[B25] - Exit
Predecessors: [B15]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseDll.WithOverflowChecks(False))
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub ForToFlow_15()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(c1 As C, c2 As C, bInit As Boolean, init1 As Integer, init2 As Integer, bLimit As Boolean, limit1 As Integer, limit2 As Integer, result As Boolean) 'BIND:"Sub M"
For If(c1, c2).i = If(bInit, init1, init2) To If(bLimit, limit1, limit2) Step -2
result = true
Next
End Sub
Public i As Integer
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2} {R3} {R4}
.locals {R1}
{
CaptureIds: [4] [5]
.locals {R2}
{
CaptureIds: [2] [3]
.locals {R3}
{
CaptureIds: [1]
.locals {R4}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R4}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B4]
Leaving: {R4}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B5] - Block
Predecessors: [B4]
Statements (0)
Jump if False (Regular) to Block[B7]
IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1')
Value:
IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'init1')
Next (Regular) Block[B8]
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2')
Value:
IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'init2')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (0)
Jump if False (Regular) to Block[B10]
IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit')
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1')
Value:
IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'limit1')
Next (Regular) Block[B11]
Block[B10] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2')
Value:
IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'limit2')
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B9] [B10]
Statements (2)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '-2')
Value:
IUnaryOperation (UnaryOperatorKind.Minus, Checked) (OperationKind.Unary, Type: System.Int32, Constant: -2) (Syntax: '-2')
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)')
Left:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bInit, init1, init2)')
Next (Regular) Block[B12]
Leaving: {R2}
Entering: {R5} {R6}
}
.locals {R5}
{
CaptureIds: [7]
.locals {R6}
{
CaptureIds: [6]
Block[B12] - Block
Predecessors: [B11] [B24]
Statements (1)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B14]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R6}
Next (Regular) Block[B13]
Block[B13] - Block
Predecessors: [B12]
Statements (1)
IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B15]
Leaving: {R6}
}
Block[B14] - Block
Predecessors: [B12]
Statements (1)
IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B15]
Block[B15] - Block
Predecessors: [B13] [B14]
Statements (0)
Jump if False (Regular) to Block[B25]
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Left:
IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Right:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Leaving: {R5} {R1}
Next (Regular) Block[B16]
Leaving: {R5}
}
Block[B16] - Block
Predecessors: [B15]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B17]
Entering: {R7} {R8} {R9}
.locals {R7}
{
CaptureIds: [10] [12]
.locals {R8}
{
CaptureIds: [9]
.locals {R9}
{
CaptureIds: [8]
Block[B17] - Block
Predecessors: [B16]
Statements (1)
IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B19]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R9}
Next (Regular) Block[B18]
Block[B18] - Block
Predecessors: [B17]
Statements (1)
IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B20]
Leaving: {R9}
}
Block[B19] - Block
Predecessors: [B17]
Statements (1)
IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B20]
Block[B20] - Block
Predecessors: [B18] [B19]
Statements (1)
IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B21]
Leaving: {R8}
Entering: {R10}
}
.locals {R10}
{
CaptureIds: [11]
Block[B21] - Block
Predecessors: [B20]
Statements (1)
IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B23]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R10}
Next (Regular) Block[B22]
Block[B22] - Block
Predecessors: [B21]
Statements (1)
IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B24]
Leaving: {R10}
}
Block[B23] - Block
Predecessors: [B21]
Statements (1)
IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B24]
Block[B24] - Block
Predecessors: [B22] [B23]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Left:
IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: '-2')
Left:
IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Right:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: -2, IsImplicit) (Syntax: '-2')
Next (Regular) Block[B12]
Leaving: {R7}
Entering: {R5} {R6}
}
}
Block[B25] - Exit
Predecessors: [B15]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub ForToFlow_16()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(c1 As C, c2 As C, bInit As Boolean, init1 As Integer, init2 As Integer, bLimit As Boolean, limit1 As Integer, limit2 As Integer, bStep As Boolean, step1 As Integer, step2 As Integer, result As Boolean) 'BIND:"Sub M"
For If(c1, c2).i = If(bInit, init1, init2) To If(bLimit, limit1, limit2) Step If(bStep, step1, step2)
result = true
Next
End Sub
Public i As Integer
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2} {R3} {R4}
.locals {R1}
{
CaptureIds: [4] [5]
.locals {R2}
{
CaptureIds: [2] [3]
.locals {R3}
{
CaptureIds: [1]
.locals {R4}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R4}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B4]
Leaving: {R4}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B5] - Block
Predecessors: [B4]
Statements (0)
Jump if False (Regular) to Block[B7]
IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1')
Value:
IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'init1')
Next (Regular) Block[B8]
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2')
Value:
IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'init2')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (0)
Jump if False (Regular) to Block[B10]
IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit')
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1')
Value:
IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'limit1')
Next (Regular) Block[B11]
Block[B10] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2')
Value:
IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'limit2')
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B9] [B10]
Statements (0)
Jump if False (Regular) to Block[B13]
IParameterReferenceOperation: bStep (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bStep')
Next (Regular) Block[B12]
Block[B12] - Block
Predecessors: [B11]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step1')
Value:
IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'step1')
Next (Regular) Block[B14]
Block[B13] - Block
Predecessors: [B11]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step2')
Value:
IParameterReferenceOperation: step2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'step2')
Next (Regular) Block[B14]
Block[B14] - Block
Predecessors: [B12] [B13]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)')
Left:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bInit, init1, init2)')
Next (Regular) Block[B15]
Leaving: {R2}
Entering: {R5} {R6}
}
.locals {R5}
{
CaptureIds: [7]
.locals {R6}
{
CaptureIds: [6]
Block[B15] - Block
Predecessors: [B14] [B27]
Statements (1)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B17]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R6}
Next (Regular) Block[B16]
Block[B16] - Block
Predecessors: [B15]
Statements (1)
IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B18]
Leaving: {R6}
}
Block[B17] - Block
Predecessors: [B15]
Statements (1)
IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B18]
Block[B18] - Block
Predecessors: [B16] [B17]
Statements (0)
Jump if False (Regular) to Block[B28]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Left:
IBinaryOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Left:
IBinaryOperation (BinaryOperatorKind.RightShift) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 31, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Right:
IBinaryOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Left:
IBinaryOperation (BinaryOperatorKind.RightShift) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 31, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Right:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Leaving: {R5} {R1}
Next (Regular) Block[B19]
Leaving: {R5}
}
Block[B19] - Block
Predecessors: [B18]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B20]
Entering: {R7} {R8} {R9}
.locals {R7}
{
CaptureIds: [10] [12]
.locals {R8}
{
CaptureIds: [9]
.locals {R9}
{
CaptureIds: [8]
Block[B20] - Block
Predecessors: [B19]
Statements (1)
IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B22]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R9}
Next (Regular) Block[B21]
Block[B21] - Block
Predecessors: [B20]
Statements (1)
IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B23]
Leaving: {R9}
}
Block[B22] - Block
Predecessors: [B20]
Statements (1)
IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B23]
Block[B23] - Block
Predecessors: [B21] [B22]
Statements (1)
IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B24]
Leaving: {R8}
Entering: {R10}
}
.locals {R10}
{
CaptureIds: [11]
Block[B24] - Block
Predecessors: [B23]
Statements (1)
IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B26]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R10}
Next (Regular) Block[B25]
Block[B25] - Block
Predecessors: [B24]
Statements (1)
IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B27]
Leaving: {R10}
}
Block[B26] - Block
Predecessors: [B24]
Statements (1)
IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B27]
Block[B27] - Block
Predecessors: [B25] [B26]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Left:
IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Left:
IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Right:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Next (Regular) Block[B15]
Leaving: {R7}
Entering: {R5} {R6}
}
}
Block[B28] - Exit
Predecessors: [B18]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub ForToFlow_17()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(c1 As C, c2 As C, bInit As Boolean, init1 As Double, init2 As Double, bLimit As Boolean, limit1 As Double, limit2 As Double, bStep As Boolean, step1 As Double, step2 As Double, result As Boolean) 'BIND:"Sub M"
For If(c1, c2).i = If(bInit, init1, init2) To If(bLimit, limit1, limit2) Step If(bStep, step1, step2)
result = true
Next
End Sub
Public i As Double
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2} {R3} {R4}
.locals {R1}
{
CaptureIds: [4] [5] [6]
.locals {R2}
{
CaptureIds: [2] [3]
.locals {R3}
{
CaptureIds: [1]
.locals {R4}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R4}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B4]
Leaving: {R4}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As System.Double (OperationKind.FieldReference, Type: System.Double) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B5] - Block
Predecessors: [B4]
Statements (0)
Jump if False (Regular) to Block[B7]
IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1')
Value:
IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Double) (Syntax: 'init1')
Next (Regular) Block[B8]
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2')
Value:
IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: System.Double) (Syntax: 'init2')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (0)
Jump if False (Regular) to Block[B10]
IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit')
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1')
Value:
IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Double) (Syntax: 'limit1')
Next (Regular) Block[B11]
Block[B10] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2')
Value:
IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: System.Double) (Syntax: 'limit2')
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B9] [B10]
Statements (0)
Jump if False (Regular) to Block[B13]
IParameterReferenceOperation: bStep (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bStep')
Next (Regular) Block[B12]
Block[B12] - Block
Predecessors: [B11]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step1')
Value:
IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Double) (Syntax: 'step1')
Next (Regular) Block[B14]
Block[B13] - Block
Predecessors: [B11]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step2')
Value:
IParameterReferenceOperation: step2 (OperationKind.ParameterReference, Type: System.Double) (Syntax: 'step2')
Next (Regular) Block[B14]
Block[B14] - Block
Predecessors: [B12] [B13]
Statements (2)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Value:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 0, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)')
Left:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(bInit, init1, init2)')
Next (Regular) Block[B15]
Leaving: {R2}
Entering: {R5} {R6} {R7}
}
.locals {R5}
{
CaptureIds: [9]
.locals {R6}
{
CaptureIds: [8]
.locals {R7}
{
CaptureIds: [7]
Block[B15] - Block
Predecessors: [B14] [B30]
Statements (1)
IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B17]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R7}
Next (Regular) Block[B16]
Block[B16] - Block
Predecessors: [B15]
Statements (1)
IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B18]
Leaving: {R7}
}
Block[B17] - Block
Predecessors: [B15]
Statements (1)
IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B18]
Block[B18] - Block
Predecessors: [B16] [B17]
Statements (1)
IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As System.Double (OperationKind.FieldReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B19]
Leaving: {R6}
}
Block[B19] - Block
Predecessors: [B18]
Statements (0)
Jump if False (Regular) to Block[B21]
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Next (Regular) Block[B20]
Block[B20] - Block
Predecessors: [B19]
Statements (0)
Jump if False (Regular) to Block[B31]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Left:
IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Leaving: {R5} {R1}
Next (Regular) Block[B22]
Leaving: {R5}
Block[B21] - Block
Predecessors: [B19]
Statements (0)
Jump if False (Regular) to Block[B31]
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Left:
IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Leaving: {R5} {R1}
Next (Regular) Block[B22]
Leaving: {R5}
}
Block[B22] - Block
Predecessors: [B20] [B21]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B23]
Entering: {R8} {R9} {R10}
.locals {R8}
{
CaptureIds: [12] [14]
.locals {R9}
{
CaptureIds: [11]
.locals {R10}
{
CaptureIds: [10]
Block[B23] - Block
Predecessors: [B22]
Statements (1)
IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B25]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R10}
Next (Regular) Block[B24]
Block[B24] - Block
Predecessors: [B23]
Statements (1)
IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B26]
Leaving: {R10}
}
Block[B25] - Block
Predecessors: [B23]
Statements (1)
IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B26]
Block[B26] - Block
Predecessors: [B24] [B25]
Statements (1)
IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As System.Double (OperationKind.FieldReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B27]
Leaving: {R9}
Entering: {R11}
}
.locals {R11}
{
CaptureIds: [13]
Block[B27] - Block
Predecessors: [B26]
Statements (1)
IFlowCaptureOperation: 13 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B29]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 13 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R11}
Next (Regular) Block[B28]
Block[B28] - Block
Predecessors: [B27]
Statements (1)
IFlowCaptureOperation: 14 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 13 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B30]
Leaving: {R11}
}
Block[B29] - Block
Predecessors: [B27]
Statements (1)
IFlowCaptureOperation: 14 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B30]
Block[B30] - Block
Predecessors: [B28] [B29]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Left:
IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Double, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Left:
IFieldReferenceOperation: C.i As System.Double (OperationKind.FieldReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 14 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Right:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Next (Regular) Block[B15]
Leaving: {R8}
Entering: {R5} {R6} {R7}
}
}
Block[B31] - Exit
Predecessors: [B20] [B21]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub ForToFlow_18()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(c1 As C, c2 As C, bInit As Boolean, init1 As Double?, init2 As Double?, bLimit As Boolean, limit1 As Double?, limit2 As Double?, bStep As Boolean, step1 As Double?, step2 As Double?, result As Boolean) 'BIND:"Sub M"
For If(c1, c2).i = If(bInit, init1, init2) To If(bLimit, limit1, limit2) Step If(bStep, step1, step2)
result = true
Next
End Sub
Public i As Double?
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2} {R3} {R4}
.locals {R1}
{
CaptureIds: [4] [5] [6]
.locals {R2}
{
CaptureIds: [2] [3]
.locals {R3}
{
CaptureIds: [1]
.locals {R4}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R4}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B4]
Leaving: {R4}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As System.Nullable(Of System.Double) (OperationKind.FieldReference, Type: System.Nullable(Of System.Double)) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B5] - Block
Predecessors: [B4]
Statements (0)
Jump if False (Regular) to Block[B7]
IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1')
Value:
IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Double)) (Syntax: 'init1')
Next (Regular) Block[B8]
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2')
Value:
IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Double)) (Syntax: 'init2')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (0)
Jump if False (Regular) to Block[B10]
IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit')
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1')
Value:
IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Double)) (Syntax: 'limit1')
Next (Regular) Block[B11]
Block[B10] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2')
Value:
IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Double)) (Syntax: 'limit2')
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B9] [B10]
Statements (0)
Jump if False (Regular) to Block[B13]
IParameterReferenceOperation: bStep (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bStep')
Next (Regular) Block[B12]
Block[B12] - Block
Predecessors: [B11]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step1')
Value:
IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Double)) (Syntax: 'step1')
Next (Regular) Block[B14]
Block[B13] - Block
Predecessors: [B11]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step2')
Value:
IParameterReferenceOperation: step2 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Double)) (Syntax: 'step2')
Next (Regular) Block[B14]
Block[B14] - Block
Predecessors: [B12] [B13]
Statements (0)
Jump if False (Regular) to Block[B16]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Operand:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Next (Regular) Block[B15]
Block[B15] - Block
Predecessors: [B14]
Statements (1)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Next (Regular) Block[B17]
Block[B16] - Block
Predecessors: [B14]
Statements (1)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Value:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Left:
IInvocationOperation ( Function System.Nullable(Of System.Double).GetValueOrDefault() As System.Double) (OperationKind.Invocation, Type: System.Double, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Instance Receiver:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Arguments(0)
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 0, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Next (Regular) Block[B17]
Block[B17] - Block
Predecessors: [B15] [B16]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)')
Left:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bInit, init1, init2)')
Next (Regular) Block[B18]
Leaving: {R2}
Entering: {R5} {R6}
}
.locals {R5}
{
CaptureIds: [8]
.locals {R6}
{
CaptureIds: [7]
Block[B18] - Block
Predecessors: [B17] [B38] [B42]
Statements (1)
IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B20]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R6}
Next (Regular) Block[B19]
Block[B19] - Block
Predecessors: [B18]
Statements (1)
IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B21]
Leaving: {R6}
}
Block[B20] - Block
Predecessors: [B18]
Statements (1)
IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B21]
Block[B21] - Block
Predecessors: [B19] [B20]
Statements (0)
Jump if False (Regular) to Block[B22]
IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Left:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Operand:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Right:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'If(c1, c2).i')
Operand:
IFieldReferenceOperation: C.i As System.Nullable(Of System.Double) (OperationKind.FieldReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Leaving: {R5}
Entering: {R7} {R8} {R9}
Next (Regular) Block[B43]
Leaving: {R5} {R1}
}
.locals {R7}
{
CaptureIds: [11]
.locals {R8}
{
CaptureIds: [10]
.locals {R9}
{
CaptureIds: [9]
Block[B22] - Block
Predecessors: [B21]
Statements (1)
IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B24]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R9}
Next (Regular) Block[B23]
Block[B23] - Block
Predecessors: [B22]
Statements (1)
IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B25]
Leaving: {R9}
}
Block[B24] - Block
Predecessors: [B22]
Statements (1)
IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B25]
Block[B25] - Block
Predecessors: [B23] [B24]
Statements (1)
IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Double).GetValueOrDefault() As System.Double) (OperationKind.Invocation, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFieldReferenceOperation: C.i As System.Nullable(Of System.Double) (OperationKind.FieldReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Arguments(0)
Next (Regular) Block[B26]
Leaving: {R8}
}
Block[B26] - Block
Predecessors: [B25]
Statements (0)
Jump if False (Regular) to Block[B28]
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Next (Regular) Block[B27]
Block[B27] - Block
Predecessors: [B26]
Statements (0)
Jump if False (Regular) to Block[B43]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Left:
IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IInvocationOperation ( Function System.Nullable(Of System.Double).GetValueOrDefault() As System.Double) (OperationKind.Invocation, Type: System.Double, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Instance Receiver:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Arguments(0)
Leaving: {R7} {R1}
Next (Regular) Block[B29]
Leaving: {R7}
Block[B28] - Block
Predecessors: [B26]
Statements (0)
Jump if False (Regular) to Block[B43]
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Left:
IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IInvocationOperation ( Function System.Nullable(Of System.Double).GetValueOrDefault() As System.Double) (OperationKind.Invocation, Type: System.Double, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Instance Receiver:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Arguments(0)
Leaving: {R7} {R1}
Next (Regular) Block[B29]
Leaving: {R7}
}
Block[B29] - Block
Predecessors: [B27] [B28]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B30]
Entering: {R10} {R11} {R12}
.locals {R10}
{
CaptureIds: [14]
.locals {R11}
{
CaptureIds: [13]
.locals {R12}
{
CaptureIds: [12]
Block[B30] - Block
Predecessors: [B29]
Statements (1)
IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B32]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R12}
Next (Regular) Block[B31]
Block[B31] - Block
Predecessors: [B30]
Statements (1)
IFlowCaptureOperation: 13 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B33]
Leaving: {R12}
}
Block[B32] - Block
Predecessors: [B30]
Statements (1)
IFlowCaptureOperation: 13 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B33]
Block[B33] - Block
Predecessors: [B31] [B32]
Statements (1)
IFlowCaptureOperation: 14 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As System.Nullable(Of System.Double) (OperationKind.FieldReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 13 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B34]
Leaving: {R11}
Entering: {R13} {R14}
}
.locals {R13}
{
CaptureIds: [16]
.locals {R14}
{
CaptureIds: [15]
Block[B34] - Block
Predecessors: [B33]
Statements (1)
IFlowCaptureOperation: 15 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B36]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 15 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R14}
Next (Regular) Block[B35]
Block[B35] - Block
Predecessors: [B34]
Statements (1)
IFlowCaptureOperation: 16 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 15 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B37]
Leaving: {R14}
}
Block[B36] - Block
Predecessors: [B34]
Statements (1)
IFlowCaptureOperation: 16 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B37]
Block[B37] - Block
Predecessors: [B35] [B36]
Statements (0)
Jump if False (Regular) to Block[B39]
IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Left:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Operand:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Right:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'If(c1, c2).i')
Operand:
IFieldReferenceOperation: C.i As System.Nullable(Of System.Double) (OperationKind.FieldReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 16 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Leaving: {R13}
Entering: {R15} {R16}
Next (Regular) Block[B38]
Leaving: {R13}
}
Block[B38] - Block
Predecessors: [B37]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Left:
IFlowCaptureReferenceOperation: 14 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i')
Next (Regular) Block[B18]
Leaving: {R10}
Entering: {R5} {R6}
.locals {R15}
{
CaptureIds: [18]
.locals {R16}
{
CaptureIds: [17]
Block[B39] - Block
Predecessors: [B37]
Statements (1)
IFlowCaptureOperation: 17 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B41]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 17 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R16}
Next (Regular) Block[B40]
Block[B40] - Block
Predecessors: [B39]
Statements (1)
IFlowCaptureOperation: 18 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 17 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B42]
Leaving: {R16}
}
Block[B41] - Block
Predecessors: [B39]
Statements (1)
IFlowCaptureOperation: 18 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B42]
Block[B42] - Block
Predecessors: [B40] [B41]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Left:
IFlowCaptureReferenceOperation: 14 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningNullable)
Operand:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Double, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Left:
IInvocationOperation ( Function System.Nullable(Of System.Double).GetValueOrDefault() As System.Double) (OperationKind.Invocation, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFieldReferenceOperation: C.i As System.Nullable(Of System.Double) (OperationKind.FieldReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 18 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Arguments(0)
Right:
IInvocationOperation ( Function System.Nullable(Of System.Double).GetValueOrDefault() As System.Double) (OperationKind.Invocation, Type: System.Double, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Instance Receiver:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Arguments(0)
Next (Regular) Block[B18]
Leaving: {R15} {R10}
Entering: {R5} {R6}
}
}
}
Block[B43] - Exit
Predecessors: [B21] [B27] [B28]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_19()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As Integer, result As Integer) 'BIND:"Sub M"
For i = 0 To 4 Step 2
if result = i
Exit For
End If
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '0')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '4')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '0')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '0')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B4]
Statements (0)
Jump if False (Regular) to Block[B5]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '4')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 4, IsImplicit) (Syntax: '4')
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B4]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Next (Regular) Block[B5]
Leaving: {R1}
Block[B4] - Block
Predecessors: [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: '2')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '2')
Next (Regular) Block[B2]
}
Block[B5] - Exit
Predecessors: [B2] [B3]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseDll.WithOverflowChecks(False))
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_20()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As Integer, result As Integer) 'BIND:"Sub M"
For i = 0 To 4 Step 2
if result = i
Continue For
End If
result = i
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '0')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '4')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '0')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '0')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B5]
Statements (0)
Jump if False (Regular) to Block[B6]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '4')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 4, IsImplicit) (Syntax: '4')
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B4]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Next (Regular) Block[B5]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: '2')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '2')
Next (Regular) Block[B2]
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseDll.WithOverflowChecks(False))
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_21()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As C, init As C, limit As C, [step] As C, result As C) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
Public Shared Operator <=(x As C, y As C) As Boolean
Return False
End Operator
Public Shared Operator -(x As C, y As C) As C
Return Nothing
End Operator
Public Shared Operator +(x As C, y As C) As C
Return Nothing
End Operator
End Class
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC33038: Type 'C' must define operator '>=' to be used in a 'For' statement.
For i = init To limit Step [step]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC33033: Matching '>=' operator is required for 'Public Shared Operator <=(x As C, y As C) As Boolean'.
Public Shared Operator <=(x As C, y As C) As Boolean
~~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'init')
Value:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'limit')
Value:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: '[step]')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'init')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'limit')
Children(2):
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'limit')
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_22()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As C, init As C, limit As C, [step] As C, result As C) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
Public Shared Operator >=(x As C, y As C) As Boolean
Return False
End Operator
Public Shared Operator -(x As C, y As C) As C
Return Nothing
End Operator
Public Shared Operator +(x As C, y As C) As C
Return Nothing
End Operator
End Class
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC33038: Type 'C' must define operator '<=' to be used in a 'For' statement.
For i = init To limit Step [step]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC33033: Matching '<=' operator is required for 'Public Shared Operator >=(x As C, y As C) As Boolean'.
Public Shared Operator >=(x As C, y As C) As Boolean
~~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'init')
Value:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'limit')
Value:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: '[step]')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'init')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'limit')
Children(2):
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'limit')
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_23()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As C, init As C, limit As C, [step] As C, result As C) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
Public Shared Operator >=(x As C, y As C) As Boolean
Return False
End Operator
Public Shared Operator <=(x As C, y As C) As Boolean
Return False
End Operator
Public Shared Operator +(x As C, y As C) As C
Return Nothing
End Operator
End Class
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC33038: Type 'C' must define operator '-' to be used in a 'For' statement.
For i = init To limit Step [step]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'init')
Value:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'limit')
Value:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: '[step]')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'init')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'limit')
Children(2):
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'limit')
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_24()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As C, init As C, limit As C, [step] As C, result As C) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
Public Shared Operator >=(x As C, y As C) As Boolean
Return False
End Operator
Public Shared Operator <=(x As C, y As C) As Boolean
Return False
End Operator
Public Shared Operator -(x As C, y As C) As C
Return Nothing
End Operator
End Class
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC33038: Type 'C' must define operator '+' to be used in a 'For' statement.
For i = init To limit Step [step]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'init')
Value:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'limit')
Value:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: '[step]')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'init')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'limit')
Children(2):
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'limit')
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_25()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As C, init As C, limit As C, [step] As C, result As C) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
Public Shared Operator >=(x As C, y As C) As Boolean
Return False
End Operator
Public Shared Operator <=(x As C, y As C) As Boolean
Return False
End Operator
Public Shared Operator -(x As C, y As C) As C
Return Nothing
End Operator
Public Shared Operator +(x As C, y As C) As C
Return Nothing
End Operator
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3] [4]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (6)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init')
Value:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit')
Value:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C) (Syntax: '[step]')
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Value:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: '[step]')
Right:
IBinaryOperation (BinaryOperatorKind.Subtract, Checked) (OperatorMethod: Function C.op_Subtraction(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: '[step]')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: '[step]')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'init')
Next (Regular) Block[B2]
Leaving: {R2}
Entering: {R3}
}
.locals {R3}
{
CaptureIds: [5]
Block[B2] - Block
Predecessors: [B1] [B5]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'i')
Jump if False (Regular) to Block[B4]
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B6]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual, Checked) (OperatorMethod: Function C.op_LessThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'limit')
Leaving: {R3} {R1}
Next (Regular) Block[B5]
Leaving: {R3}
Block[B4] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B6]
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'limit')
Leaving: {R3} {R1}
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperatorMethod: Function C.op_Addition(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
Entering: {R3}
}
Block[B6] - Exit
Predecessors: [B3] [B4]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_26()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As C, init As C, limit As C, [step] As C, result As C) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
Public Shared Operator >=(x As C, y As C) As C
Return Nothing
End Operator
Public Shared Operator <=(x As C, y As C) As C
Return Nothing
End Operator
Public Shared Operator -(x As C, y As C) As C
Return Nothing
End Operator
Public Shared Operator +(x As C, y As C) As C
Return Nothing
End Operator
End Class
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30311: Value of type 'C' cannot be converted to 'Boolean'.
For i = init To limit Step [step]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3] [4]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (6)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'init')
Value:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'limit')
Value:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: '[step]')
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(DelegateRelaxationLevelNone)
Operand:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]')
Right:
IBinaryOperation (BinaryOperatorKind.Subtract, Checked) (OperatorMethod: Function C.op_Subtraction(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'init')
Next (Regular) Block[B2]
Leaving: {R2}
Entering: {R3}
}
.locals {R3}
{
CaptureIds: [5]
Block[B2] - Block
Predecessors: [B1] [B5]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Jump if False (Regular) to Block[B4]
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B6]
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(DelegateRelaxationLevelNone)
Operand:
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual, Checked) (OperatorMethod: Function C.op_LessThanOrEqual(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'limit')
Leaving: {R3} {R1}
Next (Regular) Block[B5]
Leaving: {R3}
Block[B4] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B6]
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(DelegateRelaxationLevelNone)
Operand:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'limit')
Leaving: {R3} {R1}
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperatorMethod: Function C.op_Addition(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
Entering: {R3}
}
Block[B6] - Exit
Predecessors: [B3] [B4]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_27()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As C, init As C, limit As C, [step] As C, result As C) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
Public Shared Operator >=(x As C, y As C) As C
Return Nothing
End Operator
Public Shared Operator <=(x As C, y As C) As C
Return Nothing
End Operator
Public Shared Operator -(x As C, y As C) As C
Return Nothing
End Operator
Public Shared Operator +(x As C, y As C) As C
Return Nothing
End Operator
Public Shared Operator IsTrue(x As C) As Boolean
Return Nothing
End Operator
Public Shared Operator IsFalse(x As C) As Boolean
Return Nothing
End Operator
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3] [4]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (6)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init')
Value:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit')
Value:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C) (Syntax: '[step]')
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Value:
IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: Function C.op_True(x As C) As System.Boolean) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Operand:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: '[step]')
Right:
IBinaryOperation (BinaryOperatorKind.Subtract, Checked) (OperatorMethod: Function C.op_Subtraction(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: '[step]')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: '[step]')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'init')
Next (Regular) Block[B2]
Leaving: {R2}
Entering: {R3}
}
.locals {R3}
{
CaptureIds: [5]
Block[B2] - Block
Predecessors: [B1] [B5]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'i')
Jump if False (Regular) to Block[B4]
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B6]
IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: Function C.op_True(x As C) As System.Boolean) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Operand:
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual, Checked) (OperatorMethod: Function C.op_LessThanOrEqual(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'limit')
Leaving: {R3} {R1}
Next (Regular) Block[B5]
Leaving: {R3}
Block[B4] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B6]
IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: Function C.op_True(x As C) As System.Boolean) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Operand:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'limit')
Leaving: {R3} {R1}
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperatorMethod: Function C.op_Addition(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
Entering: {R3}
}
Block[B6] - Exit
Predecessors: [B3] [B4]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_28()
Dim source = <![CDATA[
Imports System
Public Structure C
Sub M(i As C?, init As C?, limit As C?, [step] As C?, result As C?) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
Public Shared Operator >=(x As C, y As C) As Boolean
Return False
End Operator
Public Shared Operator <=(x As C, y As C) As Boolean
Return False
End Operator
Public Shared Operator -(x As C, y As C) As C
Return Nothing
End Operator
Public Shared Operator +(x As C, y As C) As C
Return Nothing
End Operator
End Structure
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3] [4]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (6)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init')
Value:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit')
Value:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: '[step]')
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Boolean).GetValueOrDefault() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Instance Receiver:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, IsLifted, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Nullable(Of System.Boolean), IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: '[step]')
Right:
IBinaryOperation (BinaryOperatorKind.Subtract, IsLifted, Checked) (OperatorMethod: Function C.op_Subtraction(x As C, y As C) As C) (OperationKind.Binary, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: '[step]')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: '[step]')
Arguments(0)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'init')
Next (Regular) Block[B2]
Leaving: {R2}
Entering: {R3}
}
.locals {R3}
{
CaptureIds: [5]
Block[B2] - Block
Predecessors: [B1] [B5]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'i')
Jump if False (Regular) to Block[B4]
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B6]
IInvocationOperation ( Function System.Nullable(Of System.Boolean).GetValueOrDefault() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Instance Receiver:
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual, IsLifted, Checked) (OperatorMethod: Function C.op_LessThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Nullable(Of System.Boolean), IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'limit')
Arguments(0)
Leaving: {R3} {R1}
Next (Regular) Block[B5]
Leaving: {R3}
Block[B4] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B6]
IInvocationOperation ( Function System.Nullable(Of System.Boolean).GetValueOrDefault() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Instance Receiver:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, IsLifted, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Nullable(Of System.Boolean), IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'limit')
Arguments(0)
Leaving: {R3} {R1}
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, IsLifted, Checked) (OperatorMethod: Function C.op_Addition(x As C, y As C) As C) (OperationKind.Binary, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
Entering: {R3}
}
Block[B6] - Exit
Predecessors: [B3] [B4]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_29()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(c1 As C, c2 As C, bInit As Boolean, init1 As C, init2 As C, bLimit As Boolean, limit1 As C, limit2 As C, bStep As Boolean, step1 As C, step2 As C, result As Boolean) 'BIND:"Sub M"
For If(c1, c2).i = If(bInit, init1, init2) To If(bLimit, limit1, limit2) Step If(bStep, step1, step2)
result = true
Next
End Sub
Public i As C
Public Shared Operator >=(x As C, y As C) As Boolean
Return False
End Operator
Public Shared Operator <=(x As C, y As C) As Boolean
Return False
End Operator
Public Shared Operator -(x As C, y As C) As C
Return Nothing
End Operator
Public Shared Operator +(x As C, y As C) As C
Return Nothing
End Operator
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2} {R3} {R4}
.locals {R1}
{
CaptureIds: [4] [5] [6]
.locals {R2}
{
CaptureIds: [2] [3]
.locals {R3}
{
CaptureIds: [1]
.locals {R4}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R4}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B4]
Leaving: {R4}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As C (OperationKind.FieldReference, Type: C) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B5] - Block
Predecessors: [B4]
Statements (0)
Jump if False (Regular) to Block[B7]
IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1')
Value:
IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: C) (Syntax: 'init1')
Next (Regular) Block[B8]
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2')
Value:
IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: C) (Syntax: 'init2')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (0)
Jump if False (Regular) to Block[B10]
IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit')
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1')
Value:
IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: C) (Syntax: 'limit1')
Next (Regular) Block[B11]
Block[B10] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2')
Value:
IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: C) (Syntax: 'limit2')
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B9] [B10]
Statements (0)
Jump if False (Regular) to Block[B13]
IParameterReferenceOperation: bStep (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bStep')
Next (Regular) Block[B12]
Block[B12] - Block
Predecessors: [B11]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step1')
Value:
IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: C) (Syntax: 'step1')
Next (Regular) Block[B14]
Block[B13] - Block
Predecessors: [B11]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step2')
Value:
IParameterReferenceOperation: step2 (OperationKind.ParameterReference, Type: C) (Syntax: 'step2')
Next (Regular) Block[B14]
Block[B14] - Block
Predecessors: [B12] [B13]
Statements (2)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Value:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Right:
IBinaryOperation (BinaryOperatorKind.Subtract, Checked) (OperatorMethod: Function C.op_Subtraction(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Right:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)')
Left:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(bInit, init1, init2)')
Next (Regular) Block[B15]
Leaving: {R2}
Entering: {R5} {R6} {R7}
}
.locals {R5}
{
CaptureIds: [9]
.locals {R6}
{
CaptureIds: [8]
.locals {R7}
{
CaptureIds: [7]
Block[B15] - Block
Predecessors: [B14] [B30]
Statements (1)
IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B17]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R7}
Next (Regular) Block[B16]
Block[B16] - Block
Predecessors: [B15]
Statements (1)
IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B18]
Leaving: {R7}
}
Block[B17] - Block
Predecessors: [B15]
Statements (1)
IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B18]
Block[B18] - Block
Predecessors: [B16] [B17]
Statements (1)
IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As C (OperationKind.FieldReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B19]
Leaving: {R6}
}
Block[B19] - Block
Predecessors: [B18]
Statements (0)
Jump if False (Regular) to Block[B21]
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Next (Regular) Block[B20]
Block[B20] - Block
Predecessors: [B19]
Statements (0)
Jump if False (Regular) to Block[B31]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual, Checked) (OperatorMethod: Function C.op_LessThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Left:
IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Leaving: {R5} {R1}
Next (Regular) Block[B22]
Leaving: {R5}
Block[B21] - Block
Predecessors: [B19]
Statements (0)
Jump if False (Regular) to Block[B31]
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Left:
IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Leaving: {R5} {R1}
Next (Regular) Block[B22]
Leaving: {R5}
}
Block[B22] - Block
Predecessors: [B20] [B21]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B23]
Entering: {R8} {R9} {R10}
.locals {R8}
{
CaptureIds: [12] [14]
.locals {R9}
{
CaptureIds: [11]
.locals {R10}
{
CaptureIds: [10]
Block[B23] - Block
Predecessors: [B22]
Statements (1)
IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B25]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R10}
Next (Regular) Block[B24]
Block[B24] - Block
Predecessors: [B23]
Statements (1)
IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B26]
Leaving: {R10}
}
Block[B25] - Block
Predecessors: [B23]
Statements (1)
IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B26]
Block[B26] - Block
Predecessors: [B24] [B25]
Statements (1)
IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As C (OperationKind.FieldReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B27]
Leaving: {R9}
Entering: {R11}
}
.locals {R11}
{
CaptureIds: [13]
Block[B27] - Block
Predecessors: [B26]
Statements (1)
IFlowCaptureOperation: 13 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B29]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 13 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R11}
Next (Regular) Block[B28]
Block[B28] - Block
Predecessors: [B27]
Statements (1)
IFlowCaptureOperation: 14 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 13 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B30]
Leaving: {R11}
}
Block[B29] - Block
Predecessors: [B27]
Statements (1)
IFlowCaptureOperation: 14 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B30]
Block[B30] - Block
Predecessors: [B28] [B29]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Left:
IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperatorMethod: Function C.op_Addition(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Left:
IFieldReferenceOperation: C.i As C (OperationKind.FieldReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 14 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Right:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Next (Regular) Block[B15]
Leaving: {R8}
Entering: {R5} {R6} {R7}
}
}
Block[B31] - Exit
Predecessors: [B20] [B21]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_30()
Dim source = <![CDATA[
Imports System
Public Class C1
Sub M(c1 As C1, c2 As C1, bInit As Boolean, init1 As C?, init2 As C?, bLimit As Boolean, limit1 As C?, limit2 As C?, bStep As Boolean, step1 As C?, step2 As C?, result As Boolean) 'BIND:"Sub M"
For If(c1, c2).i = If(bInit, init1, init2) To If(bLimit, limit1, limit2) Step If(bStep, step1, step2)
result = true
Next
End Sub
Public i As C?
End Class
Public Structure C
Public Shared Operator >=(x As C, y As C) As Boolean
Return False
End Operator
Public Shared Operator <=(x As C, y As C) As Boolean
Return False
End Operator
Public Shared Operator -(x As C, y As C) As C
Return Nothing
End Operator
Public Shared Operator +(x As C, y As C) As C
Return Nothing
End Operator
End Structure
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2} {R3} {R4}
.locals {R1}
{
CaptureIds: [4] [5] [6]
.locals {R2}
{
CaptureIds: [2] [3]
.locals {R3}
{
CaptureIds: [1]
.locals {R4}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C1) (Syntax: 'c1')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1')
Leaving: {R4}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B4]
Leaving: {R4}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C1) (Syntax: 'c2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C1.i As System.Nullable(Of C) (OperationKind.FieldReference, Type: System.Nullable(Of C)) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B5] - Block
Predecessors: [B4]
Statements (0)
Jump if False (Regular) to Block[B7]
IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1')
Value:
IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'init1')
Next (Regular) Block[B8]
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2')
Value:
IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'init2')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (0)
Jump if False (Regular) to Block[B10]
IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit')
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1')
Value:
IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'limit1')
Next (Regular) Block[B11]
Block[B10] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2')
Value:
IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'limit2')
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B9] [B10]
Statements (0)
Jump if False (Regular) to Block[B13]
IParameterReferenceOperation: bStep (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bStep')
Next (Regular) Block[B12]
Block[B12] - Block
Predecessors: [B11]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step1')
Value:
IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'step1')
Next (Regular) Block[B14]
Block[B13] - Block
Predecessors: [B11]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step2')
Value:
IParameterReferenceOperation: step2 (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'step2')
Next (Regular) Block[B14]
Block[B14] - Block
Predecessors: [B12] [B13]
Statements (2)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Boolean).GetValueOrDefault() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Instance Receiver:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, IsLifted, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Nullable(Of System.Boolean), IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Right:
IBinaryOperation (BinaryOperatorKind.Subtract, IsLifted, Checked) (OperatorMethod: Function C.op_Subtraction(x As C, y As C) As C) (OperationKind.Binary, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Right:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Arguments(0)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)')
Left:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(bInit, init1, init2)')
Next (Regular) Block[B15]
Leaving: {R2}
Entering: {R5} {R6} {R7}
}
.locals {R5}
{
CaptureIds: [9]
.locals {R6}
{
CaptureIds: [8]
.locals {R7}
{
CaptureIds: [7]
Block[B15] - Block
Predecessors: [B14] [B30]
Statements (1)
IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B17]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1')
Leaving: {R7}
Next (Regular) Block[B16]
Block[B16] - Block
Predecessors: [B15]
Statements (1)
IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B18]
Leaving: {R7}
}
Block[B17] - Block
Predecessors: [B15]
Statements (1)
IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B18]
Block[B18] - Block
Predecessors: [B16] [B17]
Statements (1)
IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C1.i As System.Nullable(Of C) (OperationKind.FieldReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B19]
Leaving: {R6}
}
Block[B19] - Block
Predecessors: [B18]
Statements (0)
Jump if False (Regular) to Block[B21]
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Next (Regular) Block[B20]
Block[B20] - Block
Predecessors: [B19]
Statements (0)
Jump if False (Regular) to Block[B31]
IInvocationOperation ( Function System.Nullable(Of System.Boolean).GetValueOrDefault() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Instance Receiver:
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual, IsLifted, Checked) (OperatorMethod: Function C.op_LessThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Nullable(Of System.Boolean), IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Left:
IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Arguments(0)
Leaving: {R5} {R1}
Next (Regular) Block[B22]
Leaving: {R5}
Block[B21] - Block
Predecessors: [B19]
Statements (0)
Jump if False (Regular) to Block[B31]
IInvocationOperation ( Function System.Nullable(Of System.Boolean).GetValueOrDefault() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Instance Receiver:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, IsLifted, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Nullable(Of System.Boolean), IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Left:
IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Arguments(0)
Leaving: {R5} {R1}
Next (Regular) Block[B22]
Leaving: {R5}
}
Block[B22] - Block
Predecessors: [B20] [B21]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B23]
Entering: {R8} {R9} {R10}
.locals {R8}
{
CaptureIds: [12] [14]
.locals {R9}
{
CaptureIds: [11]
.locals {R10}
{
CaptureIds: [10]
Block[B23] - Block
Predecessors: [B22]
Statements (1)
IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B25]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1')
Leaving: {R10}
Next (Regular) Block[B24]
Block[B24] - Block
Predecessors: [B23]
Statements (1)
IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B26]
Leaving: {R10}
}
Block[B25] - Block
Predecessors: [B23]
Statements (1)
IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B26]
Block[B26] - Block
Predecessors: [B24] [B25]
Statements (1)
IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C1.i As System.Nullable(Of C) (OperationKind.FieldReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B27]
Leaving: {R9}
Entering: {R11}
}
.locals {R11}
{
CaptureIds: [13]
Block[B27] - Block
Predecessors: [B26]
Statements (1)
IFlowCaptureOperation: 13 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B29]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 13 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1')
Leaving: {R11}
Next (Regular) Block[B28]
Block[B28] - Block
Predecessors: [B27]
Statements (1)
IFlowCaptureOperation: 14 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 13 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B30]
Leaving: {R11}
}
Block[B29] - Block
Predecessors: [B27]
Statements (1)
IFlowCaptureOperation: 14 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B30]
Block[B30] - Block
Predecessors: [B28] [B29]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Left:
IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, IsLifted, Checked) (OperatorMethod: Function C.op_Addition(x As C, y As C) As C) (OperationKind.Binary, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Left:
IFieldReferenceOperation: C1.i As System.Nullable(Of C) (OperationKind.FieldReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 14 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'If(c1, c2)')
Right:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Next (Regular) Block[B15]
Leaving: {R8}
Entering: {R5} {R6} {R7}
}
}
Block[B31] - Exit
Predecessors: [B20] [B21]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_31()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As Object, init As Object, limit As Object, result As Object) 'BIND:"Sub M"
For i = init To limit
result = i
Next
End Sub
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [<anonymous local> As System.Object]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Counter As System.Object, Start As System.Object, Limit As System.Object, StepValue As System.Object, ByRef LoopForResult As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Instance Receiver:
null
Arguments(6):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Start) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'init')
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Limit) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit')
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: StepValue) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'For i = ini ... Next')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'For i = ini ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningValue)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i = ini ... Next')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopForResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1] [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'i')
Jump if False (Regular) to Block[B3]
IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Counter As System.Object, LoopObj As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Instance Receiver:
null
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit')
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopObj) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit')
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit')
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R1}
Next (Regular) Block[B2]
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_32()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(init As Object, limit As Object, [step] as Object, result As Object) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [<anonymous local> As System.Object] [i As System.Object]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Counter As System.Object, Start As System.Object, Limit As System.Object, StepValue As System.Object, ByRef LoopForResult As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Instance Receiver:
null
Arguments(6):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Start) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'init')
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Limit) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit')
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: StepValue) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '[step]')
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: System.Object) (Syntax: '[step]')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopForResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1] [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result')
Right:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Object) (Syntax: 'i')
Jump if False (Regular) to Block[B3]
IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Counter As System.Object, LoopObj As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Instance Receiver:
null
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit')
ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopObj) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit')
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit')
ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R1}
Next (Regular) Block[B2]
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_33()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(c1 As C, c2 As C, bInit As Boolean, init1 As Object, init2 As Object, bLimit As Boolean, limit1 As Object, limit2 As Object, bStep As Boolean, step1 As Object, step2 As Object, result As Boolean) 'BIND:"Sub M"
For If(c1, c2).i = If(bInit, init1, init2) To If(bLimit, limit1, limit2) Step If(bStep, step1, step2)
result = true
Next
End Sub
Public i As Object
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2} {R3} {R4}
.locals {R1}
{
Locals: [<anonymous local> As System.Object]
.locals {R2}
{
CaptureIds: [2] [3] [4] [5] [7]
.locals {R3}
{
CaptureIds: [1]
.locals {R4}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R4}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B4]
Leaving: {R4}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As System.Object (OperationKind.FieldReference, Type: System.Object) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B5] - Block
Predecessors: [B4]
Statements (0)
Jump if False (Regular) to Block[B7]
IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1')
Value:
IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init1')
Next (Regular) Block[B8]
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2')
Value:
IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init2')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (0)
Jump if False (Regular) to Block[B10]
IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit')
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1')
Value:
IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit1')
Next (Regular) Block[B11]
Block[B10] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2')
Value:
IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit2')
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B9] [B10]
Statements (0)
Jump if False (Regular) to Block[B13]
IParameterReferenceOperation: bStep (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bStep')
Next (Regular) Block[B12]
Block[B12] - Block
Predecessors: [B11]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step1')
Value:
IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'step1')
Next (Regular) Block[B14]
Entering: {R5}
Block[B13] - Block
Predecessors: [B11]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step2')
Value:
IParameterReferenceOperation: step2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'step2')
Next (Regular) Block[B14]
Entering: {R5}
.locals {R5}
{
CaptureIds: [6]
Block[B14] - Block
Predecessors: [B12] [B13]
Statements (1)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B16]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R5}
Next (Regular) Block[B15]
Block[B15] - Block
Predecessors: [B14]
Statements (1)
IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B17]
Leaving: {R5}
}
Block[B16] - Block
Predecessors: [B14]
Statements (1)
IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B17]
Block[B17] - Block
Predecessors: [B15] [B16]
Statements (0)
Jump if False (Regular) to Block[B27]
IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Counter As System.Object, Start As System.Object, Limit As System.Object, StepValue As System.Object, ByRef LoopForResult As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Instance Receiver:
null
Arguments(6):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Start) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)')
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(bInit, init1, init2)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Limit) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: StepValue) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopForResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
IFieldReferenceOperation: C.i As System.Object (OperationKind.FieldReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R2} {R1}
Next (Regular) Block[B26]
Leaving: {R2}
}
.locals {R6}
{
CaptureIds: [10] [12]
.locals {R7}
{
CaptureIds: [9]
.locals {R8}
{
CaptureIds: [8]
Block[B18] - Block
Predecessors: [B26]
Statements (1)
IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B20]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R8}
Next (Regular) Block[B19]
Block[B19] - Block
Predecessors: [B18]
Statements (1)
IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B21]
Leaving: {R8}
}
Block[B20] - Block
Predecessors: [B18]
Statements (1)
IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B21]
Block[B21] - Block
Predecessors: [B19] [B20]
Statements (1)
IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As System.Object (OperationKind.FieldReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B22]
Leaving: {R7}
Entering: {R9}
}
.locals {R9}
{
CaptureIds: [11]
Block[B22] - Block
Predecessors: [B21]
Statements (1)
IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B24]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R9}
Next (Regular) Block[B23]
Block[B23] - Block
Predecessors: [B22]
Statements (1)
IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B25]
Leaving: {R9}
}
Block[B24] - Block
Predecessors: [B22]
Statements (1)
IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B25]
Block[B25] - Block
Predecessors: [B23] [B24]
Statements (0)
Jump if False (Regular) to Block[B27]
IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Counter As System.Object, LoopObj As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Instance Receiver:
null
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopObj) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
IFieldReferenceOperation: C.i As System.Object (OperationKind.FieldReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R6} {R1}
Next (Regular) Block[B26]
Leaving: {R6}
}
Block[B26] - Block
Predecessors: [B17] [B25]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B18]
Entering: {R6} {R7} {R8}
}
Block[B27] - Exit
Predecessors: [B17] [B25]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_34()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(c1 As C, c2 As C, init1 As Object, limit1 As Object, step1 As Object, result As Boolean) 'BIND:"Sub M"
For If(c1, c2).i = init1 To limit1 Step step1
result = true
Next
End Sub
Public i As Object
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2} {R3} {R4}
.locals {R1}
{
Locals: [<anonymous local> As System.Object]
.locals {R2}
{
CaptureIds: [2] [3] [4] [5] [7]
.locals {R3}
{
CaptureIds: [1]
.locals {R4}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R4}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B4]
Leaving: {R4}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As System.Object (OperationKind.FieldReference, Type: System.Object) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B5] - Block
Predecessors: [B4]
Statements (3)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1')
Value:
IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init1')
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1')
Value:
IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit1')
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step1')
Value:
IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'step1')
Next (Regular) Block[B6]
Entering: {R5}
.locals {R5}
{
CaptureIds: [6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B8]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R5}
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B6]
Statements (1)
IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B9]
Leaving: {R5}
}
Block[B8] - Block
Predecessors: [B6]
Statements (1)
IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B7] [B8]
Statements (0)
Jump if False (Regular) to Block[B19]
IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Counter As System.Object, Start As System.Object, Limit As System.Object, StepValue As System.Object, ByRef LoopForResult As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit1')
Instance Receiver:
null
Arguments(6):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Start) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'init1')
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'init1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Limit) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1')
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'limit1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: StepValue) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'step1')
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'step1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopForResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
IFieldReferenceOperation: C.i As System.Object (OperationKind.FieldReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R2} {R1}
Next (Regular) Block[B18]
Leaving: {R2}
}
.locals {R6}
{
CaptureIds: [10] [12]
.locals {R7}
{
CaptureIds: [9]
.locals {R8}
{
CaptureIds: [8]
Block[B10] - Block
Predecessors: [B18]
Statements (1)
IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B12]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R8}
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B10]
Statements (1)
IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B13]
Leaving: {R8}
}
Block[B12] - Block
Predecessors: [B10]
Statements (1)
IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B13]
Block[B13] - Block
Predecessors: [B11] [B12]
Statements (1)
IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As System.Object (OperationKind.FieldReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B14]
Leaving: {R7}
Entering: {R9}
}
.locals {R9}
{
CaptureIds: [11]
Block[B14] - Block
Predecessors: [B13]
Statements (1)
IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B16]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R9}
Next (Regular) Block[B15]
Block[B15] - Block
Predecessors: [B14]
Statements (1)
IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B17]
Leaving: {R9}
}
Block[B16] - Block
Predecessors: [B14]
Statements (1)
IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B17]
Block[B17] - Block
Predecessors: [B15] [B16]
Statements (0)
Jump if False (Regular) to Block[B19]
IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Counter As System.Object, LoopObj As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit1')
Instance Receiver:
null
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1')
IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopObj) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1')
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1')
IFieldReferenceOperation: C.i As System.Object (OperationKind.FieldReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R6} {R1}
Next (Regular) Block[B18]
Leaving: {R6}
}
Block[B18] - Block
Predecessors: [B9] [B17]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B10]
Entering: {R6} {R7} {R8}
}
Block[B19] - Exit
Predecessors: [B9] [B17]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_35()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As Object, bInit As Boolean, init1 As Object, init2 As Object, limit1 As Object, step1 As Object, result As Boolean) 'BIND:"Sub M"
For i = If(bInit, init1, init2) To limit1 Step step1
result = true
Next
End Sub
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
Locals: [<anonymous local> As System.Object]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'i')
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1')
Value:
IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init1')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2')
Value:
IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (0)
Jump if False (Regular) to Block[B6]
IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Counter As System.Object, Start As System.Object, Limit As System.Object, StepValue As System.Object, ByRef LoopForResult As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit1')
Instance Receiver:
null
Arguments(6):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Start) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)')
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(bInit, init1, init2)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Limit) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1')
IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: StepValue) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'step1')
IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'step1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopForResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R2} {R1}
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B5] - Block
Predecessors: [B4] [B5]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Jump if False (Regular) to Block[B6]
IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Counter As System.Object, LoopObj As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit1')
Instance Receiver:
null
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1')
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopObj) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1')
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1')
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R1}
Next (Regular) Block[B5]
}
Block[B6] - Exit
Predecessors: [B4] [B5]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_36()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As Object, init1 As Object, bLimit As Boolean, limit1 As Object, limit2 As Object, step1 As Object, result As Boolean) 'BIND:"Sub M"
For i = init1 To If(bLimit, limit1, limit2) Step step1
result = true
Next
End Sub
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
Locals: [<anonymous local> As System.Object]
.locals {R2}
{
CaptureIds: [0] [1] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1')
Value:
IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init1')
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1')
Value:
IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit1')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2')
Value:
IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (0)
Jump if False (Regular) to Block[B6]
IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Counter As System.Object, Start As System.Object, Limit As System.Object, StepValue As System.Object, ByRef LoopForResult As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Instance Receiver:
null
Arguments(6):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Start) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'init1')
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'init1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Limit) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: StepValue) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'step1')
IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'step1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopForResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R2} {R1}
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B5] - Block
Predecessors: [B4] [B5]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Jump if False (Regular) to Block[B6]
IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Counter As System.Object, LoopObj As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Instance Receiver:
null
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopObj) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R1}
Next (Regular) Block[B5]
}
Block[B6] - Exit
Predecessors: [B4] [B5]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_37()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As Object, init1 As Object, limit1 As Object, bStep As Boolean, step1 As Object, step2 As Object, result As Boolean) 'BIND:"Sub M"
For i = init1 To limit1 Step If(bStep, step1, step2)
result = true
Next
End Sub
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
Locals: [<anonymous local> As System.Object]
.locals {R2}
{
CaptureIds: [0] [1] [2] [3]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1')
Value:
IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init1')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1')
Value:
IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit1')
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: bStep (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bStep')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step1')
Value:
IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'step1')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step2')
Value:
IParameterReferenceOperation: step2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'step2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (0)
Jump if False (Regular) to Block[B6]
IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Counter As System.Object, Start As System.Object, Limit As System.Object, StepValue As System.Object, ByRef LoopForResult As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit1')
Instance Receiver:
null
Arguments(6):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Start) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'init1')
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'init1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Limit) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'limit1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: StepValue) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopForResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R2} {R1}
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B5] - Block
Predecessors: [B4] [B5]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Jump if False (Regular) to Block[B6]
IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Counter As System.Object, LoopObj As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit1')
Instance Receiver:
null
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1')
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopObj) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1')
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1')
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R1}
Next (Regular) Block[B5]
}
Block[B6] - Exit
Predecessors: [B4] [B5]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_38()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As Object, init As Object, limit As Object, result As Object) 'BIND:"Sub M"
For i = init To limit
result = i
Next
End Sub
End Class
]]>.Value
Dim compilation = CreateCompilationWithMscorlib45(source, options:=TestOptions.ReleaseDebugDll)
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [<anonymous local> As System.Object]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Children(5):
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'i')
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init')
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'For i = ini ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningValue)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i = ini ... Next')
ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1] [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'i')
Jump if False (Regular) to Block[B3]
IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Children(2):
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i')
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i')
Leaving: {R1}
Next (Regular) Block[B2]
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(compilation, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_39()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As Integer?, init As Integer?, limit As Integer?, [step] As Integer?, result As Integer?) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
End Class
]]>.Value
Dim compilation = CreateCompilationWithMscorlib45(source, options:=TestOptions.ReleaseDebugDll)
compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault)
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3] [4]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (4)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init')
Value:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit')
Value:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: '[step]')
Jump if False (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Operand:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Left:
IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: '[step]')
Children(1):
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'init')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B5] - Block
Predecessors: [B4] [B11] [B12]
Statements (0)
Jump if False (Regular) to Block[B6]
IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Left:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'limit')
Right:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i')
Operand:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Entering: {R3}
Next (Regular) Block[B13]
Leaving: {R1}
.locals {R3}
{
CaptureIds: [5]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: 'i')
Children(1):
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Jump if False (Regular) to Block[B8]
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B6]
Statements (0)
Jump if False (Regular) to Block[B13]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: 'limit')
Children(1):
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'limit')
Leaving: {R3} {R1}
Next (Regular) Block[B9]
Leaving: {R3}
Block[B8] - Block
Predecessors: [B6]
Statements (0)
Jump if False (Regular) to Block[B13]
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: 'limit')
Children(1):
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'limit')
Leaving: {R3} {R1}
Next (Regular) Block[B9]
Leaving: {R3}
}
Block[B9] - Block
Predecessors: [B7] [B8]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i')
Next (Regular) Block[B10]
Entering: {R4}
.locals {R4}
{
CaptureIds: [6]
Block[B10] - Block
Predecessors: [B9]
Statements (1)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Jump if False (Regular) to Block[B12]
IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Left:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Operand:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]')
Right:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i')
Operand:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B10]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Right:
IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Next (Regular) Block[B5]
Leaving: {R4}
Block[B12] - Block
Predecessors: [B10]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningNullable)
Operand:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: '[step]')
Left:
IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: 'i')
Children(1):
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Right:
IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: '[step]')
Children(1):
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B5]
Leaving: {R4}
}
}
Block[B13] - Exit
Predecessors: [B5] [B7] [B8]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(compilation, expectedFlowGraph, expectedDiagnostics)
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Operations
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Partial Public Class IOperationTests
Inherits SemanticModelTestBase
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_SimpleForLoopsTest()
Dim source = <![CDATA[
Public Class MyClass1
Public Shared Sub Main()
Dim myarray As Integer() = New Integer(2) {1, 2, 3}
For i As Integer = 0 To myarray.Length - 1'BIND:"For i As Integer = 0 To myarray.Length - 1"
System.Console.WriteLine(myarray(i))
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For i As In ... Next')
Locals: Local_1: i As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: i As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i As Integer')
Initializer:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
LimitValue:
IBinaryOperation (BinaryOperatorKind.Subtract, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'myarray.Length - 1')
Left:
IPropertyReferenceOperation: ReadOnly Property System.Array.Length As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'myarray.Length')
Instance Receiver:
ILocalReferenceOperation: myarray (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'myarray')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i As In ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i As In ... Next')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For i As In ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... myarray(i))')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... myarray(i))')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'myarray(i)')
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'myarray(i)')
Array reference:
ILocalReferenceOperation: myarray (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'myarray')
Indices(1):
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_SimpleForLoopsTestConversion()
Dim source = <![CDATA[
Option Strict Off
Public Class MyClass1
Public Shared Sub Main()
Dim myarray As Integer() = New Integer(1) {}
myarray(0) = 1
myarray(1) = 2
Dim s As Double = 1.1
For i As Integer = 0 To "1" Step s'BIND:"For i As Integer = 0 To "1" Step s"
System.Console.WriteLine(myarray(i))
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For i As In ... Next')
Locals: Local_1: i As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: i As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i As Integer')
Initializer:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
LimitValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: '"1"')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "1") (Syntax: '"1"')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 's')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.Double) (Syntax: 's')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For i As In ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... myarray(i))')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... myarray(i))')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'myarray(i)')
IArrayElementReferenceOperation (OperationKind.ArrayElementReference, Type: System.Int32) (Syntax: 'myarray(i)')
Array reference:
ILocalReferenceOperation: myarray (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'myarray')
Indices(1):
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree, TestOptions.ReleaseDll.WithOverflowChecks(False))
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_ForLoopStepIsFloatNegativeVar()
Dim source = <![CDATA[
Option Strict On
Public Class MyClass1
Public Shared Sub Main()
Dim s As Double = -1.1
For i As Double = 2 To 0 Step s'BIND:"For i As Double = 2 To 0 Step s"
System.Console.WriteLine(i)
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For i As Do ... Next')
Locals: Local_1: i As System.Double
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: i As System.Double) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i As Double')
Initializer:
null
InitialValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Double, Constant: 2, IsImplicit) (Syntax: '2')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
LimitValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Double, Constant: 0, IsImplicit) (Syntax: '0')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
StepValue:
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.Double) (Syntax: 's')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For i As Do ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(i)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Double)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(i)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'i')
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Double) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_ForLoopObject()
Dim source = <![CDATA[
Option Strict On
Public Class MyClass1
Public Shared Sub Main()
Dim ctrlVar As Object
Dim initValue As Object = 0
Dim limit As Object = 2
Dim stp As Object = 1
For ctrlVar = initValue To limit Step stp'BIND:"For ctrlVar = initValue To limit Step stp"
System.Console.WriteLine(ctrlVar)
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For ctrlVar ... Next')
LoopControlVariable:
ILocalReferenceOperation: ctrlVar (OperationKind.LocalReference, Type: System.Object) (Syntax: 'ctrlVar')
InitialValue:
ILocalReferenceOperation: initValue (OperationKind.LocalReference, Type: System.Object) (Syntax: 'initValue')
LimitValue:
ILocalReferenceOperation: limit (OperationKind.LocalReference, Type: System.Object) (Syntax: 'limit')
StepValue:
ILocalReferenceOperation: stp (OperationKind.LocalReference, Type: System.Object) (Syntax: 'stp')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For ctrlVar ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... ne(ctrlVar)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... ne(ctrlVar)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'ctrlVar')
ILocalReferenceOperation: ctrlVar (OperationKind.LocalReference, Type: System.Object) (Syntax: 'ctrlVar')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_ForLoopNested()
Dim source = <![CDATA[
Option Strict On
Option Infer On
Public Class MyClass1
Public Shared Sub Main()
For AVarName = 1 To 2'BIND:"For AVarName = 1 To 2"
For B = 1 To 2
For C = 1 To 2
For D = 1 To 2
Next D
Next C
Next B
Next AVarName
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For AVarNam ... xt AVarName')
Locals: Local_1: AVarName As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: AVarName As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'AVarName')
Initializer:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For AVarNam ... xt AVarName')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For AVarNam ... xt AVarName')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For AVarNam ... xt AVarName')
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 2, Exit Label Id: 3, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For B = 1 T ... Next B')
Locals: Local_1: B As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: B As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'B')
Initializer:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For B = 1 T ... Next B')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For B = 1 T ... Next B')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For B = 1 T ... Next B')
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 4, Exit Label Id: 5, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For C = 1 T ... Next C')
Locals: Local_1: C As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: C As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'C')
Initializer:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For C = 1 T ... Next C')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For C = 1 T ... Next C')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For C = 1 T ... Next C')
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 6, Exit Label Id: 7, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For D = 1 T ... Next D')
Locals: Local_1: D As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: D As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'D')
Initializer:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For D = 1 T ... Next D')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For D = 1 T ... Next D')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For D = 1 T ... Next D')
NextVariables(1):
ILocalReferenceOperation: D (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'D')
NextVariables(1):
ILocalReferenceOperation: C (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'C')
NextVariables(1):
ILocalReferenceOperation: B (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'B')
NextVariables(1):
ILocalReferenceOperation: AVarName (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'AVarName')
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_ChangeOuterVarInInnerFor()
Dim source = <![CDATA[
Option Strict On
Option Infer On
Public Class MyClass1
Public Shared Sub Main()
For I = 1 To 2'BIND:"For I = 1 To 2"
For J = 1 To 2
I = 3
System.Console.WriteLine(I)
Next
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For I = 1 T ... Next')
Locals: Local_1: I As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: I As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'I')
Initializer:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For I = 1 T ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For I = 1 T ... Next')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For I = 1 T ... Next')
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 2, Exit Label Id: 3, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For J = 1 T ... Next')
Locals: Local_1: J As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: J As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'J')
Initializer:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For J = 1 T ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For J = 1 T ... Next')
Body:
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For J = 1 T ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'I = 3')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'I = 3')
Left:
ILocalReferenceOperation: I (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'I')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(I)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(I)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'I')
ILocalReferenceOperation: I (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'I')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
NextVariables(0)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_InnerForRefOuterForVar()
Dim source = <![CDATA[
Option Strict On
Option Infer On
Public Class MyClass1
Public Shared Sub Main()
For I = 1 To 2'BIND:"For I = 1 To 2"
For J = I + 1 To 2
System.Console.WriteLine(J)
Next
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For I = 1 T ... Next')
Locals: Local_1: I As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: I As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'I')
Initializer:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For I = 1 T ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For I = 1 T ... Next')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For I = 1 T ... Next')
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 2, Exit Label Id: 3, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For J = I + ... Next')
Locals: Local_1: J As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: J As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'J')
Initializer:
null
InitialValue:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'I + 1')
Left:
ILocalReferenceOperation: I (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'I')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For J = I + ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For J = I + ... Next')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For J = I + ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(J)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(J)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'J')
ILocalReferenceOperation: J (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'J')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
NextVariables(0)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_ExitNestedFor()
Dim source = <![CDATA[
Option Strict On
Option Infer On
Public Class MyClass1
Public Shared Sub Main()
For I = 1 To 2'BIND:"For I = 1 To 2"
For J = 1 To 2
Exit For
Next
System.Console.WriteLine(I)
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For I = 1 T ... Next')
Locals: Local_1: I As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: I As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'I')
Initializer:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For I = 1 T ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For I = 1 T ... Next')
Body:
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For I = 1 T ... Next')
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 2, Exit Label Id: 3, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For J = 1 T ... Next')
Locals: Local_1: J As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: J As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'J')
Initializer:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For J = 1 T ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For J = 1 T ... Next')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For J = 1 T ... Next')
IBranchOperation (BranchKind.Break, Label Id: 3) (OperationKind.Branch, Type: null) (Syntax: 'Exit For')
NextVariables(0)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(I)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(I)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'I')
ILocalReferenceOperation: I (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'I')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_EnumAsStart()
Dim source = <![CDATA[
Option Strict Off
Option Infer Off
Public Class MyClass1
Public Shared Sub Main()
For x As e1 = e1.a To e1.c'BIND:"For x As e1 = e1.a To e1.c"
Next
End Sub
End Class
Enum e1
a
b
c
End Enum
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x As e1 ... Next')
Locals: Local_1: x As e1
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: x As e1) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x As e1')
Initializer:
null
InitialValue:
IFieldReferenceOperation: e1.a (Static) (OperationKind.FieldReference, Type: e1, Constant: 0) (Syntax: 'e1.a')
Instance Receiver:
null
LimitValue:
IFieldReferenceOperation: e1.c (Static) (OperationKind.FieldReference, Type: e1, Constant: 2) (Syntax: 'e1.c')
Instance Receiver:
null
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: e1, Constant: 1, IsImplicit) (Syntax: 'For x As e1 ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x As e1 ... Next')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x As e1 ... Next')
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_PropertyAsStart()
Dim source = <![CDATA[
Option Strict Off
Option Infer Off
Public Class MyClass1
Property P1(ByVal x As Long) As Byte
Get
Return x - 10
End Get
Set(ByVal Value As Byte)
End Set
End Property
Public Shared Sub Main()
End Sub
Public Sub F()
For i As Integer = P1(30 + i) To 30'BIND:"For i As Integer = P1(30 + i) To 30"
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For i As In ... Next')
Locals: Local_1: i As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: i As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i As Integer')
Initializer:
null
InitialValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'P1(30 + i)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IPropertyReferenceOperation: Property MyClass1.P1(x As System.Int64) As System.Byte (OperationKind.PropertyReference, Type: System.Byte) (Syntax: 'P1(30 + i)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: MyClass1, IsImplicit) (Syntax: 'P1')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '30 + i')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: '30 + i')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: '30 + i')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30')
Right:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 30) (Syntax: '30')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i As In ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i As In ... Next')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For i As In ... Next')
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_FieldNameAsIteration()
Dim source = <![CDATA[
Option Strict Off
Option Infer On
Public Class MyClass1
Dim global_x As Integer = 10
Const global_y As Long = 20
Public Shared Sub Main()
For global_x As Integer = global_y To 10'BIND:"For global_x As Integer = global_y To 10"
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For global_ ... Next')
Locals: Local_1: global_x As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: global_x As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'global_x As Integer')
Initializer:
null
InitialValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 20, IsImplicit) (Syntax: 'global_y')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IFieldReferenceOperation: MyClass1.global_y As System.Int64 (Static) (OperationKind.FieldReference, Type: System.Int64, Constant: 20) (Syntax: 'global_y')
Instance Receiver:
null
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For global_ ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For global_ ... Next')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For global_ ... Next')
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_SingleLine()
Dim source = <![CDATA[
Option Strict On
Public Class MyClass1
Public Shared Sub Main()
For x As Integer = 0 To 10 : Next'BIND:"For x As Integer = 0 To 10 : Next"
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x As In ... o 10 : Next')
Locals: Local_1: x As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: x As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x As Integer')
Initializer:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x As In ... o 10 : Next')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x As In ... o 10 : Next')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x As In ... o 10 : Next')
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_VarDeclOutOfForeach()
Dim source = <![CDATA[
Option Strict On
Option Infer On
Public Class MyClass1
Public Shared Sub Main()
Dim Y As Integer
For Y = 1 To 2'BIND:"For Y = 1 To 2"
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For Y = 1 T ... Next')
LoopControlVariable:
ILocalReferenceOperation: Y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'Y')
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For Y = 1 T ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For Y = 1 T ... Next')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Y = 1 T ... Next')
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_GetDeclaredSymbolOfForStatement()
Dim source = <![CDATA[
Option Strict On
Option Infer On
Imports System
Imports System.Collection
Class C1
Public Shared Sub Main()
For element1 = 23 To 42'BIND:"For element1 = 23 To 42"
Next
For element2 As Integer = 23 To 42
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For element ... Next')
Locals: Local_1: element1 As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: element1 As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'element1')
Initializer:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 23) (Syntax: '23')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For element ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For element ... Next')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For element ... Next')
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_ForLoopContinue()
Dim source = <![CDATA[
Option Strict On
Option Infer On
Imports System
Imports System.Collection
Class C1
Public Shared Sub Main()
For i As Integer = 0 To 5'BIND:"For i As Integer = 0 To 5"
If i Mod 2 = 0 Then
Continue For
End If
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For i As In ... Next')
Locals: Local_1: i As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: i As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i As Integer')
Initializer:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i As In ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i As In ... Next')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For i As In ... Next')
IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If i Mod 2 ... End If')
Condition:
IBinaryOperation (BinaryOperatorKind.Equals, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i Mod 2 = 0')
Left:
IBinaryOperation (BinaryOperatorKind.Remainder, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i Mod 2')
Left:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
WhenTrue:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If i Mod 2 ... End If')
IBranchOperation (BranchKind.Continue, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'Continue For')
WhenFalse:
null
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_ForReverse()
Dim source = <![CDATA[
Option Infer On
Module Program
Sub Main()
For X = 10 To 0'BIND:"For X = 10 To 0"
Next
End Sub
End Module
Module M
Public X As Integer
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For X = 10 ... Next')
LoopControlVariable:
IFieldReferenceOperation: M.X As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'X')
Instance Receiver:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For X = 10 ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For X = 10 ... Next')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For X = 10 ... Next')
NextVariables(0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ForBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_InValid()
Dim source = <![CDATA[
Option Infer On
Module Program
Sub Main()
For X = 10 To 0'BIND:"For X = 10 To 0"
Next
End Sub
End Module
Module M
Public X As String
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null, IsInvalid) (Syntax: 'For X = 10 ... Next')
LoopControlVariable:
IFieldReferenceOperation: M.X As System.String (Static) (OperationKind.FieldReference, Type: System.String, IsInvalid) (Syntax: 'X')
Instance Receiver:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
StepValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'For X = 10 ... Next')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'For X = 10 ... Next')
NextVariables(0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30337: 'For' loop control variable cannot be of type 'String' because the type does not support the required operators.
For X = 10 To 0'BIND:"For X = 10 To 0"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ForBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForLoopStatement_ForCombined()
Dim source = <![CDATA[
Option Infer On
Module Program
Sub Main(args As String())
For A = 1 To 2'BIND:"For A = 1 To 2"
For B = A To 2
Next B, A
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For A = 1 T ... Next B, A')
Locals: Local_1: A As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: A As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'A')
Initializer:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For A = 1 T ... Next B, A')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For A = 1 T ... Next B, A')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For A = 1 T ... Next B, A')
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 2, Exit Label Id: 3, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For B = A T ... Next B, A')
Locals: Local_1: B As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: B As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'B')
Initializer:
null
InitialValue:
ILocalReferenceOperation: A (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'A')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For B = A T ... Next B, A')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For B = A T ... Next B, A')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For B = A T ... Next B, A')
NextVariables(2):
ILocalReferenceOperation: B (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'B')
ILocalReferenceOperation: A (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'A')
NextVariables(0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ForBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub VerifyForToLoop1()
Dim source = <![CDATA[
Structure C
Sub F()
Dim x As Integer
Dim y As Integer = 16
For x = 12 To y 'BIND:"For x = 12 To y"
Next
End Sub
End Structure
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x = 12 ... Next')
LoopControlVariable:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12')
LimitValue:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x = 12 ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x = 12 ... Next')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x = 12 ... Next')
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub VerifyForToLoop2()
Dim source = <![CDATA[
Structure C
Sub F()
Dim x As Integer?
Dim y As Integer = 16
For x = 12 To y 'BIND:"For x = 12 To y"
Next
End Sub
End Structure
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x = 12 ... Next')
LoopControlVariable:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'x')
InitialValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '12')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12')
LimitValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'y')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'For x = 12 ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x = 12 ... Next')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x = 12 ... Next')
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub VerifyForToLoop3()
Dim source = <![CDATA[
Structure C
Sub F()
Dim x As Integer
Dim y As Integer? = 16
For x = 12 To y 'BIND:"For x = 12 To y"
Next
End Sub
End Structure
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x = 12 ... Next')
LoopControlVariable:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12')
LimitValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'y')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'y')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x = 12 ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x = 12 ... Next')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x = 12 ... Next')
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub VerifyForToLoop4()
Dim source = <![CDATA[
Structure C
Sub F()
Dim x As Integer?
Dim y As Integer? = 16
For x = 12 To y 'BIND:"For x = 12 To y"
Next
End Sub
End Structure
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x = 12 ... Next')
LoopControlVariable:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'x')
InitialValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '12')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12')
LimitValue:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'y')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'For x = 12 ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For x = 12 ... Next')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x = 12 ... Next')
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub VerifyForToLoop5()
Dim source = <![CDATA[
Structure C
Sub F()
Dim x As Integer
Dim y As Integer = 16
Dim s As Integer? = nothing
For x = 12 To y Step s 'BIND:"For x = 12 To y Step s"
Next
End Sub
End Structure
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x = 12 ... Next')
LoopControlVariable:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12')
LimitValue:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 's')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 's')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x = 12 ... Next')
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub VerifyForToLoop6()
Dim source = <![CDATA[
Structure C
Sub F()
Dim x As Integer?
Dim y As Integer = 16
Dim s As Integer? = nothing
For x = 12 To y Step s 'BIND:"For x = 12 To y Step s"
Next
End Sub
End Structure
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x = 12 ... Next')
LoopControlVariable:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'x')
InitialValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '12')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12')
LimitValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'y')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y')
StepValue:
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 's')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x = 12 ... Next')
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub VerifyForToLoop7()
Dim source = <![CDATA[
Structure C
Sub F()
Dim x As Integer
Dim y As Integer? = 16
Dim s As Integer? = nothing
For x = 12 To y Step s 'BIND:"For x = 12 To y Step s"
Next
End Sub
End Structure
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x = 12 ... Next')
LoopControlVariable:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12')
LimitValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'y')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'y')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 's')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 's')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x = 12 ... Next')
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub VerifyForToLoop8()
Dim source = <![CDATA[
Structure C
Sub F()
Dim x As Integer?
Dim y As Integer? = 16
Dim s As Integer? = nothing
For x = 12 To y Step s 'BIND:"For x = 12 To y Step s"
Next
End Sub
End Structure
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For x = 12 ... Next')
LoopControlVariable:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'x')
InitialValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '12')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 12) (Syntax: '12')
LimitValue:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'y')
StepValue:
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.Nullable(Of System.Int32)) (Syntax: 's')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For x = 12 ... Next')
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub VerifyForToLoop_FieldAsIterationVariable()
Dim source = <![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class C
Private X As Integer = 0
Sub M()
For X = 0 To 10'BIND:"For X = 0 To 10"
Next X
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For X = 0 T ... Next X')
LoopControlVariable:
IFieldReferenceOperation: C.X As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'X')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X')
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For X = 0 T ... Next X')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For X = 0 T ... Next X')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For X = 0 T ... Next X')
NextVariables(1):
IFieldReferenceOperation: C.X As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'X')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ForBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub VerifyForToLoop_FieldWithExplicitReceiverAsIterationVariable()
Dim source = <![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class C
Private X As Integer = 0
Sub M(c As C)
For c.X = 0 To 10'BIND:"For c.X = 0 To 10"
Next c.X
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null) (Syntax: 'For c.X = 0 ... Next c.X')
LoopControlVariable:
IFieldReferenceOperation: C.X As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'c.X')
Instance Receiver:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c')
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For c.X = 0 ... Next c.X')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For c.X = 0 ... Next c.X')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For c.X = 0 ... Next c.X')
NextVariables(1):
IFieldReferenceOperation: C.X As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'c.X')
Instance Receiver:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ForBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub VerifyForToLoop_InvalidLoopControlVariableDeclaration()
Dim source = <![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class C
Sub M()
Dim i as Integer = 0
For i as Integer = 0 To 10'BIND:"For i as Integer = 0 To 10"
Next i
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IForToLoopOperation (LoopKind.ForTo, Continue Label Id: 0, Exit Label Id: 1, Checked) (OperationKind.Loop, Type: null, IsInvalid) (Syntax: 'For i as In ... Next i')
Locals: Local_1: i As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: i As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i as Integer')
Initializer:
null
InitialValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
LimitValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
StepValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'For i as In ... Next i')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: 'For i as In ... Next i')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'For i as In ... Next i')
NextVariables(1):
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30616: Variable 'i' hides a variable in an enclosing block.
For i as Integer = 0 To 10'BIND:"For i as Integer = 0 To 10"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ForBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_01()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(result As Integer) 'BIND:"Sub M"
For i As UInteger = 0UI To 2UI
result = if(i > 0UI, 3, 4)
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
Locals: [i As System.UInt32]
CaptureIds: [2] [3]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i As UInteger')
Value:
ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.UInt32, IsImplicit) (Syntax: 'i As UInteger')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '0UI')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.UInt32, Constant: 0) (Syntax: '0UI')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2UI')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.UInt32, Constant: 2) (Syntax: '2UI')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'For i As UI ... Next')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.UInt32, Constant: 1, IsImplicit) (Syntax: 'For i As UI ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningNumeric, InvolvesNarrowingFromNumericConstant)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i As UI ... Next')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '0UI')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.UInt32, IsImplicit) (Syntax: 'i As UInteger')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.UInt32, Constant: 0, IsImplicit) (Syntax: '0UI')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B7]
Statements (0)
Jump if False (Regular) to Block[B8]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '2UI')
Left:
ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.UInt32, IsImplicit) (Syntax: 'i As UInteger')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.UInt32, Constant: 2, IsImplicit) (Syntax: '2UI')
Leaving: {R1}
Next (Regular) Block[B3]
Entering: {R3}
.locals {R3}
{
CaptureIds: [4] [5]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
Jump if False (Regular) to Block[B5]
IBinaryOperation (BinaryOperatorKind.GreaterThan, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i > 0UI')
Left:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.UInt32) (Syntax: 'i')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.UInt32, Constant: 0) (Syntax: '0UI')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Next (Regular) Block[B6]
Block[B5] - Block
Predecessors: [B3]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '4')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = if ... 0UI, 3, 4)')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = if ... 0UI, 3, 4)')
Left:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'if(i > 0UI, 3, 4)')
Next (Regular) Block[B7]
Leaving: {R3}
}
Block[B7] - Block
Predecessors: [B6]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i As UInteger')
Left:
ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.UInt32, IsImplicit) (Syntax: 'i As UInteger')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.UInt32, IsImplicit) (Syntax: 'For i As UI ... Next')
Left:
ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.UInt32, IsImplicit) (Syntax: 'i As UInteger')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.UInt32, Constant: 1, IsImplicit) (Syntax: 'For i As UI ... Next')
Next (Regular) Block[B2]
}
Block[B8] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_02()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As Integer, result As Integer) 'BIND:"Sub M"
For i = 0 To 4 Step 2
result = i
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '0')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '4')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '0')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '0')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '4')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 4, IsImplicit) (Syntax: '4')
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: '2')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '2')
Next (Regular) Block[B2]
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseDll.WithOverflowChecks(False))
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_03()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As Decimal, result As Decimal) 'BIND:"Sub M"
For i = 3D To 0D Step -1D
result = i
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3D')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Decimal, Constant: 3) (Syntax: '3D')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '0D')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Decimal, Constant: 0) (Syntax: '0D')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '-1D')
Value:
IUnaryOperation (UnaryOperatorKind.Minus, Checked) (OperationKind.Unary, Type: System.Decimal, Constant: -1) (Syntax: '-1D')
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Decimal, Constant: 1) (Syntax: '1D')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '3D')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Decimal, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Decimal, Constant: 3, IsImplicit) (Syntax: '3D')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '0D')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Decimal, Constant: 0, IsImplicit) (Syntax: '0D')
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Decimal, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Decimal) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Decimal, IsImplicit) (Syntax: '-1D')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Decimal, Constant: -1, IsImplicit) (Syntax: '-1D')
Next (Regular) Block[B2]
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_04()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As Short, [step] As Short, result As Short) 'BIND:"Sub M"
For i = 0S To 4S Step [step]
result = i
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int16) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '0S')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int16, Constant: 0) (Syntax: '0S')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '4S')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int16, Constant: 4) (Syntax: '4S')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: System.Int16) (Syntax: '[step]')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '0S')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int16, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int16, Constant: 0, IsImplicit) (Syntax: '0S')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '4S')
Left:
IBinaryOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.Binary, Type: System.Int16, IsImplicit) (Syntax: 'i')
Left:
IBinaryOperation (BinaryOperatorKind.RightShift) (OperationKind.Binary, Type: System.Int16, IsImplicit) (Syntax: 'i')
Left:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int16, IsImplicit) (Syntax: '[step]')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 15, IsImplicit) (Syntax: 'i')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int16, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.Binary, Type: System.Int16, IsImplicit) (Syntax: '4S')
Left:
IBinaryOperation (BinaryOperatorKind.RightShift) (OperationKind.Binary, Type: System.Int16, IsImplicit) (Syntax: '4S')
Left:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int16, IsImplicit) (Syntax: '[step]')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 15, IsImplicit) (Syntax: '4S')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int16, Constant: 4, IsImplicit) (Syntax: '4S')
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int16, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int16) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int16) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int16, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int16, IsImplicit) (Syntax: '[step]')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int16, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int16, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_05()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As Decimal, [step] As Decimal, result As Decimal) 'BIND:"Sub M"
For i = 3D To 0D Step [step]
result = i
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3] [4]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (6)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '3D')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Decimal, Constant: 3) (Syntax: '3D')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '0D')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Decimal, Constant: 0) (Syntax: '0D')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: System.Decimal) (Syntax: '[step]')
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Left:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Decimal, IsImplicit) (Syntax: '[step]')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Decimal, Constant: 0, IsImplicit) (Syntax: '[step]')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '3D')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Decimal, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Decimal, Constant: 3, IsImplicit) (Syntax: '3D')
Next (Regular) Block[B2]
Leaving: {R2}
Entering: {R3}
}
.locals {R3}
{
CaptureIds: [5]
Block[B2] - Block
Predecessors: [B1] [B5]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal, IsImplicit) (Syntax: 'i')
Jump if False (Regular) to Block[B4]
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B6]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '0D')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Decimal, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Decimal, Constant: 0, IsImplicit) (Syntax: '0D')
Leaving: {R3} {R1}
Next (Regular) Block[B5]
Leaving: {R3}
Block[B4] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B6]
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '0D')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Decimal, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Decimal, Constant: 0, IsImplicit) (Syntax: '0D')
Leaving: {R3} {R1}
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Decimal, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Decimal) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Decimal, IsImplicit) (Syntax: '[step]')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Decimal, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Decimal, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
Entering: {R3}
}
Block[B6] - Exit
Predecessors: [B3] [B4]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_06()
Dim source = <![CDATA[
Imports System
Public Enum MyEnum As UShort
One = 1
End Enum
Public Class C
Sub M(i as MyEnum, init As MyEnum, limit As MyEnum, [step] as MyEnum, result As MyEnum) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init')
Value:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit')
Value:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: MyEnum) (Syntax: '[step]')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'init')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'limit')
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: MyEnum, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: MyEnum, IsImplicit) (Syntax: '[step]')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_07()
Dim source = <![CDATA[
Imports System
Public Enum MyEnum As SByte
One = 1
End Enum
Public Class C
Sub M(i as MyEnum, init As MyEnum, limit As MyEnum, [step] as MyEnum, result As MyEnum) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init')
Value:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit')
Value:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: MyEnum) (Syntax: '[step]')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'init')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Left:
IBinaryOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.Binary, Type: MyEnum, IsImplicit) (Syntax: 'i')
Left:
IBinaryOperation (BinaryOperatorKind.RightShift) (OperationKind.Binary, Type: MyEnum, IsImplicit) (Syntax: 'i')
Left:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: '[step]')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 7, IsImplicit) (Syntax: 'i')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.Binary, Type: MyEnum, IsImplicit) (Syntax: 'limit')
Left:
IBinaryOperation (BinaryOperatorKind.RightShift) (OperationKind.Binary, Type: MyEnum, IsImplicit) (Syntax: 'limit')
Left:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: '[step]')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 7, IsImplicit) (Syntax: 'limit')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'limit')
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: MyEnum, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: MyEnum, IsImplicit) (Syntax: '[step]')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_08()
Dim source = <![CDATA[
Imports System
Public Enum MyEnum As Long
MinusOne = -1
End Enum
Public Class C
Sub M(i as MyEnum, init As MyEnum, limit As MyEnum, result As MyEnum) 'BIND:"Sub M"
For i = init To limit Step MyEnum.MinusOne
result = i
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init')
Value:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit')
Value:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'MyEnum.MinusOne')
Value:
IFieldReferenceOperation: MyEnum.MinusOne (Static) (OperationKind.FieldReference, Type: MyEnum, Constant: -1) (Syntax: 'MyEnum.MinusOne')
Instance Receiver:
null
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'init')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'limit')
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: MyEnum, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: MyEnum, IsImplicit) (Syntax: 'MyEnum.MinusOne')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: MyEnum, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: MyEnum, Constant: -1, IsImplicit) (Syntax: 'MyEnum.MinusOne')
Next (Regular) Block[B2]
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_09()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As Integer?, init As Integer?, limit As Integer?, [step] As Integer?, result As Integer?) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3] [4]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (4)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init')
Value:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit')
Value:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: '[step]')
Jump if False (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Operand:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Left:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: '[step]')
Instance Receiver:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]')
Arguments(0)
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'init')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B5] - Block
Predecessors: [B4] [B11] [B12]
Statements (0)
Jump if False (Regular) to Block[B6]
IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Left:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'limit')
Right:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i')
Operand:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Entering: {R3}
Next (Regular) Block[B13]
Leaving: {R1}
.locals {R3}
{
CaptureIds: [5]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i')
Instance Receiver:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Arguments(0)
Jump if False (Regular) to Block[B8]
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B6]
Statements (0)
Jump if False (Regular) to Block[B13]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'limit')
Instance Receiver:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'limit')
Arguments(0)
Leaving: {R3} {R1}
Next (Regular) Block[B9]
Leaving: {R3}
Block[B8] - Block
Predecessors: [B6]
Statements (0)
Jump if False (Regular) to Block[B13]
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'limit')
Instance Receiver:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'limit')
Arguments(0)
Leaving: {R3} {R1}
Next (Regular) Block[B9]
Leaving: {R3}
}
Block[B9] - Block
Predecessors: [B7] [B8]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i')
Next (Regular) Block[B10]
Entering: {R4}
.locals {R4}
{
CaptureIds: [6]
Block[B10] - Block
Predecessors: [B9]
Statements (1)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Jump if False (Regular) to Block[B12]
IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Left:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Operand:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]')
Right:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i')
Operand:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B10]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Right:
IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Next (Regular) Block[B5]
Leaving: {R4}
Block[B12] - Block
Predecessors: [B10]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningNullable)
Operand:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: '[step]')
Left:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i')
Instance Receiver:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Arguments(0)
Right:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: '[step]')
Instance Receiver:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R4}
}
}
Block[B13] - Exit
Predecessors: [B5] [B7] [B8]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_10()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As C, init As C, limit As C, [step] As C, result As C) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC33038: Type 'C' must define operator '-' to be used in a 'For' statement.
For i = init To limit Step [step]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC33038: Type 'C' must define operator '+' to be used in a 'For' statement.
For i = init To limit Step [step]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC33038: Type 'C' must define operator '<=' to be used in a 'For' statement.
For i = init To limit Step [step]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC33038: Type 'C' must define operator '>=' to be used in a 'For' statement.
For i = init To limit Step [step]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'init')
Value:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'limit')
Value:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: '[step]')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'init')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'limit')
Children(2):
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'limit')
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_11()
Dim source = <![CDATA[
Imports System
Public Structure C
Sub M(i As C?, init As C?, limit As C?, [step] As C?, result As C?) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
End Structure]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC33038: Type 'C?' must define operator '-' to be used in a 'For' statement.
For i = init To limit Step [step]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC33038: Type 'C?' must define operator '+' to be used in a 'For' statement.
For i = init To limit Step [step]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC33038: Type 'C?' must define operator '<=' to be used in a 'For' statement.
For i = init To limit Step [step]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC33038: Type 'C?' must define operator '>=' to be used in a 'For' statement.
For i = init To limit Step [step]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsInvalid) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'init')
Value:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsInvalid) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'limit')
Value:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsInvalid) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsInvalid) (Syntax: '[step]')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'init')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B5] [B6]
Statements (0)
Jump if False (Regular) to Block[B7]
IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'limit')
Children(2):
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'i')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'limit')
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'i')
Next (Regular) Block[B4]
Entering: {R3}
.locals {R3}
{
CaptureIds: [4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'i')
Jump if False (Regular) to Block[B6]
IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '[step]')
Left:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '[step]')
Operand:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: '[step]')
Right:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'i')
Operand:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'i')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Left:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'i')
Next (Regular) Block[B2]
Leaving: {R3}
Block[B6] - Block
Predecessors: [B4]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Left:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: '[step]')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningNullable)
Operand:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]')
Left:
IInvocationOperation ( Function System.Nullable(Of C).GetValueOrDefault() As C) (OperationKind.Invocation, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Instance Receiver:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: 'i')
Arguments(0)
Right:
IInvocationOperation ( Function System.Nullable(Of C).GetValueOrDefault() As C) (OperationKind.Invocation, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]')
Instance Receiver:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsInvalid, IsImplicit) (Syntax: '[step]')
Arguments(0)
Next (Regular) Block[B2]
Leaving: {R3}
}
}
Block[B7] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_12()
Dim source = <![CDATA[
Imports System
Public Class C1
Sub M(i As C1, init As C2, limit As C3, [step] As C4, result As C1) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
End Class
Public Class C2
End Class
Public Class C3
End Class
Public Class C4
End Class
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30311: Value of type 'C2' cannot be converted to 'C1'.
For i = init To limit Step [step]
~~~~
BC30311: Value of type 'C3' cannot be converted to 'C1'.
For i = init To limit Step [step]
~~~~~
BC30311: Value of type 'C4' cannot be converted to 'C1'.
For i = init To limit Step [step]
~~~~~~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C1) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'init')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: C1, IsInvalid, IsImplicit) (Syntax: 'init')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(DelegateRelaxationLevelNone)
Operand:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C2, IsInvalid) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'limit')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: C1, IsInvalid, IsImplicit) (Syntax: 'limit')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(DelegateRelaxationLevelNone)
Operand:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C3, IsInvalid) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '[step]')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: C1, IsInvalid, IsImplicit) (Syntax: '[step]')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(DelegateRelaxationLevelNone)
Operand:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C4, IsInvalid) (Syntax: '[step]')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'init')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'limit')
Children(2):
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'i')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C1, IsInvalid, IsImplicit) (Syntax: 'limit')
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C1, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C1) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C1) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: C1, IsInvalid, IsImplicit) (Syntax: '[step]')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C1, IsInvalid, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_13()
Dim source = <![CDATA[
Imports System
Public Enum MyEnum As Integer
MinusOne = -1
End Enum
Public Class C
Sub M(i As MyEnum?, init As MyEnum?, limit As MyEnum?, [step] As MyEnum?, result As MyEnum?) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3] [4]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (4)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum)) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init')
Value:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum)) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit')
Value:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum)) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum)) (Syntax: '[step]')
Jump if False (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Operand:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Left:
IInvocationOperation ( Function System.Nullable(Of MyEnum).GetValueOrDefault() As MyEnum) (OperationKind.Invocation, Type: MyEnum, IsImplicit) (Syntax: '[step]')
Instance Receiver:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: '[step]')
Arguments(0)
Right:
ILiteralOperation (OperationKind.Literal, Type: MyEnum, Constant: 0, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'init')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B5] - Block
Predecessors: [B4] [B11] [B12]
Statements (0)
Jump if False (Regular) to Block[B6]
IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Left:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'limit')
Right:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i')
Operand:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i')
Entering: {R3}
Next (Regular) Block[B13]
Leaving: {R1}
.locals {R3}
{
CaptureIds: [5]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IInvocationOperation ( Function System.Nullable(Of MyEnum).GetValueOrDefault() As MyEnum) (OperationKind.Invocation, Type: MyEnum, IsImplicit) (Syntax: 'i')
Instance Receiver:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i')
Arguments(0)
Jump if False (Regular) to Block[B8]
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B6]
Statements (0)
Jump if False (Regular) to Block[B13]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'i')
Right:
IInvocationOperation ( Function System.Nullable(Of MyEnum).GetValueOrDefault() As MyEnum) (OperationKind.Invocation, Type: MyEnum, IsImplicit) (Syntax: 'limit')
Instance Receiver:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'limit')
Arguments(0)
Leaving: {R3} {R1}
Next (Regular) Block[B9]
Leaving: {R3}
Block[B8] - Block
Predecessors: [B6]
Statements (0)
Jump if False (Regular) to Block[B13]
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: MyEnum, IsImplicit) (Syntax: 'i')
Right:
IInvocationOperation ( Function System.Nullable(Of MyEnum).GetValueOrDefault() As MyEnum) (OperationKind.Invocation, Type: MyEnum, IsImplicit) (Syntax: 'limit')
Instance Receiver:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'limit')
Arguments(0)
Leaving: {R3} {R1}
Next (Regular) Block[B9]
Leaving: {R3}
}
Block[B9] - Block
Predecessors: [B7] [B8]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum)) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum)) (Syntax: 'i')
Next (Regular) Block[B10]
Entering: {R4}
.locals {R4}
{
CaptureIds: [6]
Block[B10] - Block
Predecessors: [B9]
Statements (1)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i')
Jump if False (Regular) to Block[B12]
IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Left:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Operand:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: '[step]')
Right:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i')
Operand:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i')
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B10]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i')
Right:
IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i')
Next (Regular) Block[B5]
Leaving: {R4}
Block[B12] - Block
Predecessors: [B10]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: '[step]')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningNullable)
Operand:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: MyEnum, IsImplicit) (Syntax: '[step]')
Left:
IInvocationOperation ( Function System.Nullable(Of MyEnum).GetValueOrDefault() As MyEnum) (OperationKind.Invocation, Type: MyEnum, IsImplicit) (Syntax: 'i')
Instance Receiver:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: 'i')
Arguments(0)
Right:
IInvocationOperation ( Function System.Nullable(Of MyEnum).GetValueOrDefault() As MyEnum) (OperationKind.Invocation, Type: MyEnum, IsImplicit) (Syntax: '[step]')
Instance Receiver:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of MyEnum), IsImplicit) (Syntax: '[step]')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R4}
}
}
Block[B13] - Exit
Predecessors: [B5] [B7] [B8]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub ForToFlow_14()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(c1 As C, c2 As C, bInit As Boolean, init1 As Integer, init2 As Integer, bLimit As Boolean, limit1 As Integer, limit2 As Integer, result As Boolean) 'BIND:"Sub M"
For If(c1, c2).i = If(bInit, init1, init2) To If(bLimit, limit1, limit2) Step 2
result = true
Next
End Sub
Public i As Integer
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2} {R3} {R4}
.locals {R1}
{
CaptureIds: [4] [5]
.locals {R2}
{
CaptureIds: [2] [3]
.locals {R3}
{
CaptureIds: [1]
.locals {R4}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R4}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B4]
Leaving: {R4}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B5] - Block
Predecessors: [B4]
Statements (0)
Jump if False (Regular) to Block[B7]
IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1')
Value:
IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'init1')
Next (Regular) Block[B8]
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2')
Value:
IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'init2')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (0)
Jump if False (Regular) to Block[B10]
IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit')
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1')
Value:
IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'limit1')
Next (Regular) Block[B11]
Block[B10] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2')
Value:
IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'limit2')
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B9] [B10]
Statements (2)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)')
Left:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bInit, init1, init2)')
Next (Regular) Block[B12]
Leaving: {R2}
Entering: {R5} {R6}
}
.locals {R5}
{
CaptureIds: [7]
.locals {R6}
{
CaptureIds: [6]
Block[B12] - Block
Predecessors: [B11] [B24]
Statements (1)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B14]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R6}
Next (Regular) Block[B13]
Block[B13] - Block
Predecessors: [B12]
Statements (1)
IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B15]
Leaving: {R6}
}
Block[B14] - Block
Predecessors: [B12]
Statements (1)
IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B15]
Block[B15] - Block
Predecessors: [B13] [B14]
Statements (0)
Jump if False (Regular) to Block[B25]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Left:
IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Right:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Leaving: {R5} {R1}
Next (Regular) Block[B16]
Leaving: {R5}
}
Block[B16] - Block
Predecessors: [B15]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B17]
Entering: {R7} {R8} {R9}
.locals {R7}
{
CaptureIds: [10] [12]
.locals {R8}
{
CaptureIds: [9]
.locals {R9}
{
CaptureIds: [8]
Block[B17] - Block
Predecessors: [B16]
Statements (1)
IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B19]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R9}
Next (Regular) Block[B18]
Block[B18] - Block
Predecessors: [B17]
Statements (1)
IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B20]
Leaving: {R9}
}
Block[B19] - Block
Predecessors: [B17]
Statements (1)
IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B20]
Block[B20] - Block
Predecessors: [B18] [B19]
Statements (1)
IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B21]
Leaving: {R8}
Entering: {R10}
}
.locals {R10}
{
CaptureIds: [11]
Block[B21] - Block
Predecessors: [B20]
Statements (1)
IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B23]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R10}
Next (Regular) Block[B22]
Block[B22] - Block
Predecessors: [B21]
Statements (1)
IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B24]
Leaving: {R10}
}
Block[B23] - Block
Predecessors: [B21]
Statements (1)
IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B24]
Block[B24] - Block
Predecessors: [B22] [B23]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Left:
IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: '2')
Left:
IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Right:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '2')
Next (Regular) Block[B12]
Leaving: {R7}
Entering: {R5} {R6}
}
}
Block[B25] - Exit
Predecessors: [B15]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseDll.WithOverflowChecks(False))
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub ForToFlow_15()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(c1 As C, c2 As C, bInit As Boolean, init1 As Integer, init2 As Integer, bLimit As Boolean, limit1 As Integer, limit2 As Integer, result As Boolean) 'BIND:"Sub M"
For If(c1, c2).i = If(bInit, init1, init2) To If(bLimit, limit1, limit2) Step -2
result = true
Next
End Sub
Public i As Integer
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2} {R3} {R4}
.locals {R1}
{
CaptureIds: [4] [5]
.locals {R2}
{
CaptureIds: [2] [3]
.locals {R3}
{
CaptureIds: [1]
.locals {R4}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R4}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B4]
Leaving: {R4}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B5] - Block
Predecessors: [B4]
Statements (0)
Jump if False (Regular) to Block[B7]
IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1')
Value:
IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'init1')
Next (Regular) Block[B8]
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2')
Value:
IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'init2')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (0)
Jump if False (Regular) to Block[B10]
IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit')
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1')
Value:
IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'limit1')
Next (Regular) Block[B11]
Block[B10] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2')
Value:
IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'limit2')
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B9] [B10]
Statements (2)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '-2')
Value:
IUnaryOperation (UnaryOperatorKind.Minus, Checked) (OperationKind.Unary, Type: System.Int32, Constant: -2) (Syntax: '-2')
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)')
Left:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bInit, init1, init2)')
Next (Regular) Block[B12]
Leaving: {R2}
Entering: {R5} {R6}
}
.locals {R5}
{
CaptureIds: [7]
.locals {R6}
{
CaptureIds: [6]
Block[B12] - Block
Predecessors: [B11] [B24]
Statements (1)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B14]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R6}
Next (Regular) Block[B13]
Block[B13] - Block
Predecessors: [B12]
Statements (1)
IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B15]
Leaving: {R6}
}
Block[B14] - Block
Predecessors: [B12]
Statements (1)
IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B15]
Block[B15] - Block
Predecessors: [B13] [B14]
Statements (0)
Jump if False (Regular) to Block[B25]
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Left:
IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Right:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Leaving: {R5} {R1}
Next (Regular) Block[B16]
Leaving: {R5}
}
Block[B16] - Block
Predecessors: [B15]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B17]
Entering: {R7} {R8} {R9}
.locals {R7}
{
CaptureIds: [10] [12]
.locals {R8}
{
CaptureIds: [9]
.locals {R9}
{
CaptureIds: [8]
Block[B17] - Block
Predecessors: [B16]
Statements (1)
IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B19]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R9}
Next (Regular) Block[B18]
Block[B18] - Block
Predecessors: [B17]
Statements (1)
IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B20]
Leaving: {R9}
}
Block[B19] - Block
Predecessors: [B17]
Statements (1)
IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B20]
Block[B20] - Block
Predecessors: [B18] [B19]
Statements (1)
IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B21]
Leaving: {R8}
Entering: {R10}
}
.locals {R10}
{
CaptureIds: [11]
Block[B21] - Block
Predecessors: [B20]
Statements (1)
IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B23]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R10}
Next (Regular) Block[B22]
Block[B22] - Block
Predecessors: [B21]
Statements (1)
IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B24]
Leaving: {R10}
}
Block[B23] - Block
Predecessors: [B21]
Statements (1)
IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B24]
Block[B24] - Block
Predecessors: [B22] [B23]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Left:
IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: '-2')
Left:
IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Right:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: -2, IsImplicit) (Syntax: '-2')
Next (Regular) Block[B12]
Leaving: {R7}
Entering: {R5} {R6}
}
}
Block[B25] - Exit
Predecessors: [B15]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub ForToFlow_16()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(c1 As C, c2 As C, bInit As Boolean, init1 As Integer, init2 As Integer, bLimit As Boolean, limit1 As Integer, limit2 As Integer, bStep As Boolean, step1 As Integer, step2 As Integer, result As Boolean) 'BIND:"Sub M"
For If(c1, c2).i = If(bInit, init1, init2) To If(bLimit, limit1, limit2) Step If(bStep, step1, step2)
result = true
Next
End Sub
Public i As Integer
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2} {R3} {R4}
.locals {R1}
{
CaptureIds: [4] [5]
.locals {R2}
{
CaptureIds: [2] [3]
.locals {R3}
{
CaptureIds: [1]
.locals {R4}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R4}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B4]
Leaving: {R4}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B5] - Block
Predecessors: [B4]
Statements (0)
Jump if False (Regular) to Block[B7]
IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1')
Value:
IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'init1')
Next (Regular) Block[B8]
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2')
Value:
IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'init2')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (0)
Jump if False (Regular) to Block[B10]
IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit')
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1')
Value:
IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'limit1')
Next (Regular) Block[B11]
Block[B10] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2')
Value:
IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'limit2')
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B9] [B10]
Statements (0)
Jump if False (Regular) to Block[B13]
IParameterReferenceOperation: bStep (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bStep')
Next (Regular) Block[B12]
Block[B12] - Block
Predecessors: [B11]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step1')
Value:
IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'step1')
Next (Regular) Block[B14]
Block[B13] - Block
Predecessors: [B11]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step2')
Value:
IParameterReferenceOperation: step2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'step2')
Next (Regular) Block[B14]
Block[B14] - Block
Predecessors: [B12] [B13]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)')
Left:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bInit, init1, init2)')
Next (Regular) Block[B15]
Leaving: {R2}
Entering: {R5} {R6}
}
.locals {R5}
{
CaptureIds: [7]
.locals {R6}
{
CaptureIds: [6]
Block[B15] - Block
Predecessors: [B14] [B27]
Statements (1)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B17]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R6}
Next (Regular) Block[B16]
Block[B16] - Block
Predecessors: [B15]
Statements (1)
IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B18]
Leaving: {R6}
}
Block[B17] - Block
Predecessors: [B15]
Statements (1)
IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B18]
Block[B18] - Block
Predecessors: [B16] [B17]
Statements (0)
Jump if False (Regular) to Block[B28]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Left:
IBinaryOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Left:
IBinaryOperation (BinaryOperatorKind.RightShift) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 31, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Right:
IBinaryOperation (BinaryOperatorKind.ExclusiveOr) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Left:
IBinaryOperation (BinaryOperatorKind.RightShift) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 31, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Right:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Leaving: {R5} {R1}
Next (Regular) Block[B19]
Leaving: {R5}
}
Block[B19] - Block
Predecessors: [B18]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B20]
Entering: {R7} {R8} {R9}
.locals {R7}
{
CaptureIds: [10] [12]
.locals {R8}
{
CaptureIds: [9]
.locals {R9}
{
CaptureIds: [8]
Block[B20] - Block
Predecessors: [B19]
Statements (1)
IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B22]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R9}
Next (Regular) Block[B21]
Block[B21] - Block
Predecessors: [B20]
Statements (1)
IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B23]
Leaving: {R9}
}
Block[B22] - Block
Predecessors: [B20]
Statements (1)
IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B23]
Block[B23] - Block
Predecessors: [B21] [B22]
Statements (1)
IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B24]
Leaving: {R8}
Entering: {R10}
}
.locals {R10}
{
CaptureIds: [11]
Block[B24] - Block
Predecessors: [B23]
Statements (1)
IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B26]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R10}
Next (Regular) Block[B25]
Block[B25] - Block
Predecessors: [B24]
Statements (1)
IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B27]
Leaving: {R10}
}
Block[B26] - Block
Predecessors: [B24]
Statements (1)
IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B27]
Block[B27] - Block
Predecessors: [B25] [B26]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Left:
IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Left:
IFieldReferenceOperation: C.i As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Right:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Next (Regular) Block[B15]
Leaving: {R7}
Entering: {R5} {R6}
}
}
Block[B28] - Exit
Predecessors: [B18]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub ForToFlow_17()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(c1 As C, c2 As C, bInit As Boolean, init1 As Double, init2 As Double, bLimit As Boolean, limit1 As Double, limit2 As Double, bStep As Boolean, step1 As Double, step2 As Double, result As Boolean) 'BIND:"Sub M"
For If(c1, c2).i = If(bInit, init1, init2) To If(bLimit, limit1, limit2) Step If(bStep, step1, step2)
result = true
Next
End Sub
Public i As Double
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2} {R3} {R4}
.locals {R1}
{
CaptureIds: [4] [5] [6]
.locals {R2}
{
CaptureIds: [2] [3]
.locals {R3}
{
CaptureIds: [1]
.locals {R4}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R4}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B4]
Leaving: {R4}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As System.Double (OperationKind.FieldReference, Type: System.Double) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B5] - Block
Predecessors: [B4]
Statements (0)
Jump if False (Regular) to Block[B7]
IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1')
Value:
IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Double) (Syntax: 'init1')
Next (Regular) Block[B8]
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2')
Value:
IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: System.Double) (Syntax: 'init2')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (0)
Jump if False (Regular) to Block[B10]
IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit')
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1')
Value:
IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Double) (Syntax: 'limit1')
Next (Regular) Block[B11]
Block[B10] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2')
Value:
IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: System.Double) (Syntax: 'limit2')
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B9] [B10]
Statements (0)
Jump if False (Regular) to Block[B13]
IParameterReferenceOperation: bStep (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bStep')
Next (Regular) Block[B12]
Block[B12] - Block
Predecessors: [B11]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step1')
Value:
IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Double) (Syntax: 'step1')
Next (Regular) Block[B14]
Block[B13] - Block
Predecessors: [B11]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step2')
Value:
IParameterReferenceOperation: step2 (OperationKind.ParameterReference, Type: System.Double) (Syntax: 'step2')
Next (Regular) Block[B14]
Block[B14] - Block
Predecessors: [B12] [B13]
Statements (2)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Value:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 0, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)')
Left:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(bInit, init1, init2)')
Next (Regular) Block[B15]
Leaving: {R2}
Entering: {R5} {R6} {R7}
}
.locals {R5}
{
CaptureIds: [9]
.locals {R6}
{
CaptureIds: [8]
.locals {R7}
{
CaptureIds: [7]
Block[B15] - Block
Predecessors: [B14] [B30]
Statements (1)
IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B17]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R7}
Next (Regular) Block[B16]
Block[B16] - Block
Predecessors: [B15]
Statements (1)
IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B18]
Leaving: {R7}
}
Block[B17] - Block
Predecessors: [B15]
Statements (1)
IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B18]
Block[B18] - Block
Predecessors: [B16] [B17]
Statements (1)
IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As System.Double (OperationKind.FieldReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B19]
Leaving: {R6}
}
Block[B19] - Block
Predecessors: [B18]
Statements (0)
Jump if False (Regular) to Block[B21]
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Next (Regular) Block[B20]
Block[B20] - Block
Predecessors: [B19]
Statements (0)
Jump if False (Regular) to Block[B31]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Left:
IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Leaving: {R5} {R1}
Next (Regular) Block[B22]
Leaving: {R5}
Block[B21] - Block
Predecessors: [B19]
Statements (0)
Jump if False (Regular) to Block[B31]
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Left:
IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Leaving: {R5} {R1}
Next (Regular) Block[B22]
Leaving: {R5}
}
Block[B22] - Block
Predecessors: [B20] [B21]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B23]
Entering: {R8} {R9} {R10}
.locals {R8}
{
CaptureIds: [12] [14]
.locals {R9}
{
CaptureIds: [11]
.locals {R10}
{
CaptureIds: [10]
Block[B23] - Block
Predecessors: [B22]
Statements (1)
IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B25]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R10}
Next (Regular) Block[B24]
Block[B24] - Block
Predecessors: [B23]
Statements (1)
IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B26]
Leaving: {R10}
}
Block[B25] - Block
Predecessors: [B23]
Statements (1)
IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B26]
Block[B26] - Block
Predecessors: [B24] [B25]
Statements (1)
IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As System.Double (OperationKind.FieldReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B27]
Leaving: {R9}
Entering: {R11}
}
.locals {R11}
{
CaptureIds: [13]
Block[B27] - Block
Predecessors: [B26]
Statements (1)
IFlowCaptureOperation: 13 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B29]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 13 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R11}
Next (Regular) Block[B28]
Block[B28] - Block
Predecessors: [B27]
Statements (1)
IFlowCaptureOperation: 14 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 13 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B30]
Leaving: {R11}
}
Block[B29] - Block
Predecessors: [B27]
Statements (1)
IFlowCaptureOperation: 14 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B30]
Block[B30] - Block
Predecessors: [B28] [B29]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Left:
IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Double, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Left:
IFieldReferenceOperation: C.i As System.Double (OperationKind.FieldReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 14 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Right:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Next (Regular) Block[B15]
Leaving: {R8}
Entering: {R5} {R6} {R7}
}
}
Block[B31] - Exit
Predecessors: [B20] [B21]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub ForToFlow_18()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(c1 As C, c2 As C, bInit As Boolean, init1 As Double?, init2 As Double?, bLimit As Boolean, limit1 As Double?, limit2 As Double?, bStep As Boolean, step1 As Double?, step2 As Double?, result As Boolean) 'BIND:"Sub M"
For If(c1, c2).i = If(bInit, init1, init2) To If(bLimit, limit1, limit2) Step If(bStep, step1, step2)
result = true
Next
End Sub
Public i As Double?
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2} {R3} {R4}
.locals {R1}
{
CaptureIds: [4] [5] [6]
.locals {R2}
{
CaptureIds: [2] [3]
.locals {R3}
{
CaptureIds: [1]
.locals {R4}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R4}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B4]
Leaving: {R4}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As System.Nullable(Of System.Double) (OperationKind.FieldReference, Type: System.Nullable(Of System.Double)) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B5] - Block
Predecessors: [B4]
Statements (0)
Jump if False (Regular) to Block[B7]
IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1')
Value:
IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Double)) (Syntax: 'init1')
Next (Regular) Block[B8]
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2')
Value:
IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Double)) (Syntax: 'init2')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (0)
Jump if False (Regular) to Block[B10]
IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit')
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1')
Value:
IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Double)) (Syntax: 'limit1')
Next (Regular) Block[B11]
Block[B10] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2')
Value:
IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Double)) (Syntax: 'limit2')
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B9] [B10]
Statements (0)
Jump if False (Regular) to Block[B13]
IParameterReferenceOperation: bStep (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bStep')
Next (Regular) Block[B12]
Block[B12] - Block
Predecessors: [B11]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step1')
Value:
IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Double)) (Syntax: 'step1')
Next (Regular) Block[B14]
Block[B13] - Block
Predecessors: [B11]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step2')
Value:
IParameterReferenceOperation: step2 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Double)) (Syntax: 'step2')
Next (Regular) Block[B14]
Block[B14] - Block
Predecessors: [B12] [B13]
Statements (0)
Jump if False (Regular) to Block[B16]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Operand:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Next (Regular) Block[B15]
Block[B15] - Block
Predecessors: [B14]
Statements (1)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Next (Regular) Block[B17]
Block[B16] - Block
Predecessors: [B14]
Statements (1)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Value:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Left:
IInvocationOperation ( Function System.Nullable(Of System.Double).GetValueOrDefault() As System.Double) (OperationKind.Invocation, Type: System.Double, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Instance Receiver:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Arguments(0)
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 0, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Next (Regular) Block[B17]
Block[B17] - Block
Predecessors: [B15] [B16]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)')
Left:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bInit, init1, init2)')
Next (Regular) Block[B18]
Leaving: {R2}
Entering: {R5} {R6}
}
.locals {R5}
{
CaptureIds: [8]
.locals {R6}
{
CaptureIds: [7]
Block[B18] - Block
Predecessors: [B17] [B38] [B42]
Statements (1)
IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B20]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R6}
Next (Regular) Block[B19]
Block[B19] - Block
Predecessors: [B18]
Statements (1)
IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B21]
Leaving: {R6}
}
Block[B20] - Block
Predecessors: [B18]
Statements (1)
IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B21]
Block[B21] - Block
Predecessors: [B19] [B20]
Statements (0)
Jump if False (Regular) to Block[B22]
IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Left:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Operand:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Right:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'If(c1, c2).i')
Operand:
IFieldReferenceOperation: C.i As System.Nullable(Of System.Double) (OperationKind.FieldReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Leaving: {R5}
Entering: {R7} {R8} {R9}
Next (Regular) Block[B43]
Leaving: {R5} {R1}
}
.locals {R7}
{
CaptureIds: [11]
.locals {R8}
{
CaptureIds: [10]
.locals {R9}
{
CaptureIds: [9]
Block[B22] - Block
Predecessors: [B21]
Statements (1)
IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B24]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R9}
Next (Regular) Block[B23]
Block[B23] - Block
Predecessors: [B22]
Statements (1)
IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B25]
Leaving: {R9}
}
Block[B24] - Block
Predecessors: [B22]
Statements (1)
IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B25]
Block[B25] - Block
Predecessors: [B23] [B24]
Statements (1)
IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Double).GetValueOrDefault() As System.Double) (OperationKind.Invocation, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFieldReferenceOperation: C.i As System.Nullable(Of System.Double) (OperationKind.FieldReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Arguments(0)
Next (Regular) Block[B26]
Leaving: {R8}
}
Block[B26] - Block
Predecessors: [B25]
Statements (0)
Jump if False (Regular) to Block[B28]
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Next (Regular) Block[B27]
Block[B27] - Block
Predecessors: [B26]
Statements (0)
Jump if False (Regular) to Block[B43]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Left:
IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IInvocationOperation ( Function System.Nullable(Of System.Double).GetValueOrDefault() As System.Double) (OperationKind.Invocation, Type: System.Double, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Instance Receiver:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Arguments(0)
Leaving: {R7} {R1}
Next (Regular) Block[B29]
Leaving: {R7}
Block[B28] - Block
Predecessors: [B26]
Statements (0)
Jump if False (Regular) to Block[B43]
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Left:
IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IInvocationOperation ( Function System.Nullable(Of System.Double).GetValueOrDefault() As System.Double) (OperationKind.Invocation, Type: System.Double, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Instance Receiver:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Arguments(0)
Leaving: {R7} {R1}
Next (Regular) Block[B29]
Leaving: {R7}
}
Block[B29] - Block
Predecessors: [B27] [B28]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B30]
Entering: {R10} {R11} {R12}
.locals {R10}
{
CaptureIds: [14]
.locals {R11}
{
CaptureIds: [13]
.locals {R12}
{
CaptureIds: [12]
Block[B30] - Block
Predecessors: [B29]
Statements (1)
IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B32]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R12}
Next (Regular) Block[B31]
Block[B31] - Block
Predecessors: [B30]
Statements (1)
IFlowCaptureOperation: 13 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B33]
Leaving: {R12}
}
Block[B32] - Block
Predecessors: [B30]
Statements (1)
IFlowCaptureOperation: 13 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B33]
Block[B33] - Block
Predecessors: [B31] [B32]
Statements (1)
IFlowCaptureOperation: 14 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As System.Nullable(Of System.Double) (OperationKind.FieldReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 13 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B34]
Leaving: {R11}
Entering: {R13} {R14}
}
.locals {R13}
{
CaptureIds: [16]
.locals {R14}
{
CaptureIds: [15]
Block[B34] - Block
Predecessors: [B33]
Statements (1)
IFlowCaptureOperation: 15 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B36]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 15 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R14}
Next (Regular) Block[B35]
Block[B35] - Block
Predecessors: [B34]
Statements (1)
IFlowCaptureOperation: 16 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 15 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B37]
Leaving: {R14}
}
Block[B36] - Block
Predecessors: [B34]
Statements (1)
IFlowCaptureOperation: 16 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B37]
Block[B37] - Block
Predecessors: [B35] [B36]
Statements (0)
Jump if False (Regular) to Block[B39]
IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Left:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Operand:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Right:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'If(c1, c2).i')
Operand:
IFieldReferenceOperation: C.i As System.Nullable(Of System.Double) (OperationKind.FieldReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 16 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Leaving: {R13}
Entering: {R15} {R16}
Next (Regular) Block[B38]
Leaving: {R13}
}
Block[B38] - Block
Predecessors: [B37]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Left:
IFlowCaptureReferenceOperation: 14 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i')
Next (Regular) Block[B18]
Leaving: {R10}
Entering: {R5} {R6}
.locals {R15}
{
CaptureIds: [18]
.locals {R16}
{
CaptureIds: [17]
Block[B39] - Block
Predecessors: [B37]
Statements (1)
IFlowCaptureOperation: 17 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B41]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 17 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R16}
Next (Regular) Block[B40]
Block[B40] - Block
Predecessors: [B39]
Statements (1)
IFlowCaptureOperation: 18 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 17 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B42]
Leaving: {R16}
}
Block[B41] - Block
Predecessors: [B39]
Statements (1)
IFlowCaptureOperation: 18 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B42]
Block[B42] - Block
Predecessors: [B40] [B41]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Left:
IFlowCaptureReferenceOperation: 14 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningNullable)
Operand:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Double, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Left:
IInvocationOperation ( Function System.Nullable(Of System.Double).GetValueOrDefault() As System.Double) (OperationKind.Invocation, Type: System.Double, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFieldReferenceOperation: C.i As System.Nullable(Of System.Double) (OperationKind.FieldReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 18 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Arguments(0)
Right:
IInvocationOperation ( Function System.Nullable(Of System.Double).GetValueOrDefault() As System.Double) (OperationKind.Invocation, Type: System.Double, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Instance Receiver:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Double), IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Arguments(0)
Next (Regular) Block[B18]
Leaving: {R15} {R10}
Entering: {R5} {R6}
}
}
}
Block[B43] - Exit
Predecessors: [B21] [B27] [B28]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_19()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As Integer, result As Integer) 'BIND:"Sub M"
For i = 0 To 4 Step 2
if result = i
Exit For
End If
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '0')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '4')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '0')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '0')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B4]
Statements (0)
Jump if False (Regular) to Block[B5]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '4')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 4, IsImplicit) (Syntax: '4')
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B4]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Next (Regular) Block[B5]
Leaving: {R1}
Block[B4] - Block
Predecessors: [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: '2')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '2')
Next (Regular) Block[B2]
}
Block[B5] - Exit
Predecessors: [B2] [B3]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseDll.WithOverflowChecks(False))
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_20()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As Integer, result As Integer) 'BIND:"Sub M"
For i = 0 To 4 Step 2
if result = i
Continue For
End If
result = i
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '0')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '4')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: '0')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '0')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B5]
Statements (0)
Jump if False (Regular) to Block[B6]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '4')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 4, IsImplicit) (Syntax: '4')
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B4]
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Next (Regular) Block[B5]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: '2')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: '2')
Next (Regular) Block[B2]
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, TestOptions.ReleaseDll.WithOverflowChecks(False))
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_21()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As C, init As C, limit As C, [step] As C, result As C) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
Public Shared Operator <=(x As C, y As C) As Boolean
Return False
End Operator
Public Shared Operator -(x As C, y As C) As C
Return Nothing
End Operator
Public Shared Operator +(x As C, y As C) As C
Return Nothing
End Operator
End Class
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC33038: Type 'C' must define operator '>=' to be used in a 'For' statement.
For i = init To limit Step [step]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC33033: Matching '>=' operator is required for 'Public Shared Operator <=(x As C, y As C) As Boolean'.
Public Shared Operator <=(x As C, y As C) As Boolean
~~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'init')
Value:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'limit')
Value:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: '[step]')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'init')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'limit')
Children(2):
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'limit')
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_22()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As C, init As C, limit As C, [step] As C, result As C) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
Public Shared Operator >=(x As C, y As C) As Boolean
Return False
End Operator
Public Shared Operator -(x As C, y As C) As C
Return Nothing
End Operator
Public Shared Operator +(x As C, y As C) As C
Return Nothing
End Operator
End Class
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC33038: Type 'C' must define operator '<=' to be used in a 'For' statement.
For i = init To limit Step [step]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC33033: Matching '<=' operator is required for 'Public Shared Operator >=(x As C, y As C) As Boolean'.
Public Shared Operator >=(x As C, y As C) As Boolean
~~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'init')
Value:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'limit')
Value:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: '[step]')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'init')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'limit')
Children(2):
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'limit')
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_23()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As C, init As C, limit As C, [step] As C, result As C) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
Public Shared Operator >=(x As C, y As C) As Boolean
Return False
End Operator
Public Shared Operator <=(x As C, y As C) As Boolean
Return False
End Operator
Public Shared Operator +(x As C, y As C) As C
Return Nothing
End Operator
End Class
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC33038: Type 'C' must define operator '-' to be used in a 'For' statement.
For i = init To limit Step [step]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'init')
Value:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'limit')
Value:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: '[step]')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'init')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'limit')
Children(2):
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'limit')
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_24()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As C, init As C, limit As C, [step] As C, result As C) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
Public Shared Operator >=(x As C, y As C) As Boolean
Return False
End Operator
Public Shared Operator <=(x As C, y As C) As Boolean
Return False
End Operator
Public Shared Operator -(x As C, y As C) As C
Return Nothing
End Operator
End Class
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC33038: Type 'C' must define operator '+' to be used in a 'For' statement.
For i = init To limit Step [step]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'init')
Value:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'limit')
Value:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: '[step]')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'init')
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'limit')
Children(2):
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'limit')
Leaving: {R1}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_25()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As C, init As C, limit As C, [step] As C, result As C) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
Public Shared Operator >=(x As C, y As C) As Boolean
Return False
End Operator
Public Shared Operator <=(x As C, y As C) As Boolean
Return False
End Operator
Public Shared Operator -(x As C, y As C) As C
Return Nothing
End Operator
Public Shared Operator +(x As C, y As C) As C
Return Nothing
End Operator
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3] [4]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (6)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init')
Value:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit')
Value:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C) (Syntax: '[step]')
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Value:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: '[step]')
Right:
IBinaryOperation (BinaryOperatorKind.Subtract, Checked) (OperatorMethod: Function C.op_Subtraction(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: '[step]')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: '[step]')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'init')
Next (Regular) Block[B2]
Leaving: {R2}
Entering: {R3}
}
.locals {R3}
{
CaptureIds: [5]
Block[B2] - Block
Predecessors: [B1] [B5]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'i')
Jump if False (Regular) to Block[B4]
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B6]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual, Checked) (OperatorMethod: Function C.op_LessThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'limit')
Leaving: {R3} {R1}
Next (Regular) Block[B5]
Leaving: {R3}
Block[B4] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B6]
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'limit')
Leaving: {R3} {R1}
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperatorMethod: Function C.op_Addition(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
Entering: {R3}
}
Block[B6] - Exit
Predecessors: [B3] [B4]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_26()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As C, init As C, limit As C, [step] As C, result As C) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
Public Shared Operator >=(x As C, y As C) As C
Return Nothing
End Operator
Public Shared Operator <=(x As C, y As C) As C
Return Nothing
End Operator
Public Shared Operator -(x As C, y As C) As C
Return Nothing
End Operator
Public Shared Operator +(x As C, y As C) As C
Return Nothing
End Operator
End Class
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30311: Value of type 'C' cannot be converted to 'Boolean'.
For i = init To limit Step [step]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3] [4]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (6)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'init')
Value:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'limit')
Value:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: '[step]')
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(DelegateRelaxationLevelNone)
Operand:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]')
Right:
IBinaryOperation (BinaryOperatorKind.Subtract, Checked) (OperatorMethod: Function C.op_Subtraction(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'init')
Next (Regular) Block[B2]
Leaving: {R2}
Entering: {R3}
}
.locals {R3}
{
CaptureIds: [5]
Block[B2] - Block
Predecessors: [B1] [B5]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Jump if False (Regular) to Block[B4]
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B6]
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(DelegateRelaxationLevelNone)
Operand:
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual, Checked) (OperatorMethod: Function C.op_LessThanOrEqual(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'limit')
Leaving: {R3} {R1}
Next (Regular) Block[B5]
Leaving: {R3}
Block[B4] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B6]
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(DelegateRelaxationLevelNone)
Operand:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'limit')
Leaving: {R3} {R1}
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperatorMethod: Function C.op_Addition(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsInvalid, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
Entering: {R3}
}
Block[B6] - Exit
Predecessors: [B3] [B4]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_27()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As C, init As C, limit As C, [step] As C, result As C) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
Public Shared Operator >=(x As C, y As C) As C
Return Nothing
End Operator
Public Shared Operator <=(x As C, y As C) As C
Return Nothing
End Operator
Public Shared Operator -(x As C, y As C) As C
Return Nothing
End Operator
Public Shared Operator +(x As C, y As C) As C
Return Nothing
End Operator
Public Shared Operator IsTrue(x As C) As Boolean
Return Nothing
End Operator
Public Shared Operator IsFalse(x As C) As Boolean
Return Nothing
End Operator
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3] [4]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (6)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init')
Value:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: C) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit')
Value:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: C) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: C) (Syntax: '[step]')
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Value:
IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: Function C.op_True(x As C) As System.Boolean) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Operand:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: '[step]')
Right:
IBinaryOperation (BinaryOperatorKind.Subtract, Checked) (OperatorMethod: Function C.op_Subtraction(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: '[step]')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: '[step]')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'init')
Next (Regular) Block[B2]
Leaving: {R2}
Entering: {R3}
}
.locals {R3}
{
CaptureIds: [5]
Block[B2] - Block
Predecessors: [B1] [B5]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'i')
Jump if False (Regular) to Block[B4]
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B6]
IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: Function C.op_True(x As C) As System.Boolean) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Operand:
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual, Checked) (OperatorMethod: Function C.op_LessThanOrEqual(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'limit')
Leaving: {R3} {R1}
Next (Regular) Block[B5]
Leaving: {R3}
Block[B4] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B6]
IUnaryOperation (UnaryOperatorKind.True) (OperatorMethod: Function C.op_True(x As C) As System.Boolean) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Operand:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'limit')
Leaving: {R3} {R1}
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperatorMethod: Function C.op_Addition(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
Entering: {R3}
}
Block[B6] - Exit
Predecessors: [B3] [B4]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_28()
Dim source = <![CDATA[
Imports System
Public Structure C
Sub M(i As C?, init As C?, limit As C?, [step] As C?, result As C?) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
Public Shared Operator >=(x As C, y As C) As Boolean
Return False
End Operator
Public Shared Operator <=(x As C, y As C) As Boolean
Return False
End Operator
Public Shared Operator -(x As C, y As C) As C
Return Nothing
End Operator
Public Shared Operator +(x As C, y As C) As C
Return Nothing
End Operator
End Structure
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3] [4]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (6)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init')
Value:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit')
Value:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: '[step]')
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Boolean).GetValueOrDefault() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Instance Receiver:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, IsLifted, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Nullable(Of System.Boolean), IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: '[step]')
Right:
IBinaryOperation (BinaryOperatorKind.Subtract, IsLifted, Checked) (OperatorMethod: Function C.op_Subtraction(x As C, y As C) As C) (OperationKind.Binary, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: '[step]')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: '[step]')
Arguments(0)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'init')
Next (Regular) Block[B2]
Leaving: {R2}
Entering: {R3}
}
.locals {R3}
{
CaptureIds: [5]
Block[B2] - Block
Predecessors: [B1] [B5]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'i')
Jump if False (Regular) to Block[B4]
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B6]
IInvocationOperation ( Function System.Nullable(Of System.Boolean).GetValueOrDefault() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Instance Receiver:
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual, IsLifted, Checked) (OperatorMethod: Function C.op_LessThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Nullable(Of System.Boolean), IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'limit')
Arguments(0)
Leaving: {R3} {R1}
Next (Regular) Block[B5]
Leaving: {R3}
Block[B4] - Block
Predecessors: [B2]
Statements (0)
Jump if False (Regular) to Block[B6]
IInvocationOperation ( Function System.Nullable(Of System.Boolean).GetValueOrDefault() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Instance Receiver:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, IsLifted, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Nullable(Of System.Boolean), IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'limit')
Arguments(0)
Leaving: {R3} {R1}
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (2)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'i')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, IsLifted, Checked) (OperatorMethod: Function C.op_Addition(x As C, y As C) As C) (OperationKind.Binary, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'For i = ini ... Step [step]')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
Entering: {R3}
}
Block[B6] - Exit
Predecessors: [B3] [B4]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_29()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(c1 As C, c2 As C, bInit As Boolean, init1 As C, init2 As C, bLimit As Boolean, limit1 As C, limit2 As C, bStep As Boolean, step1 As C, step2 As C, result As Boolean) 'BIND:"Sub M"
For If(c1, c2).i = If(bInit, init1, init2) To If(bLimit, limit1, limit2) Step If(bStep, step1, step2)
result = true
Next
End Sub
Public i As C
Public Shared Operator >=(x As C, y As C) As Boolean
Return False
End Operator
Public Shared Operator <=(x As C, y As C) As Boolean
Return False
End Operator
Public Shared Operator -(x As C, y As C) As C
Return Nothing
End Operator
Public Shared Operator +(x As C, y As C) As C
Return Nothing
End Operator
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2} {R3} {R4}
.locals {R1}
{
CaptureIds: [4] [5] [6]
.locals {R2}
{
CaptureIds: [2] [3]
.locals {R3}
{
CaptureIds: [1]
.locals {R4}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R4}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B4]
Leaving: {R4}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As C (OperationKind.FieldReference, Type: C) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B5] - Block
Predecessors: [B4]
Statements (0)
Jump if False (Regular) to Block[B7]
IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1')
Value:
IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: C) (Syntax: 'init1')
Next (Regular) Block[B8]
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2')
Value:
IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: C) (Syntax: 'init2')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (0)
Jump if False (Regular) to Block[B10]
IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit')
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1')
Value:
IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: C) (Syntax: 'limit1')
Next (Regular) Block[B11]
Block[B10] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2')
Value:
IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: C) (Syntax: 'limit2')
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B9] [B10]
Statements (0)
Jump if False (Regular) to Block[B13]
IParameterReferenceOperation: bStep (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bStep')
Next (Regular) Block[B12]
Block[B12] - Block
Predecessors: [B11]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step1')
Value:
IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: C) (Syntax: 'step1')
Next (Regular) Block[B14]
Block[B13] - Block
Predecessors: [B11]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step2')
Value:
IParameterReferenceOperation: step2 (OperationKind.ParameterReference, Type: C) (Syntax: 'step2')
Next (Regular) Block[B14]
Block[B14] - Block
Predecessors: [B12] [B13]
Statements (2)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Value:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Right:
IBinaryOperation (BinaryOperatorKind.Subtract, Checked) (OperatorMethod: Function C.op_Subtraction(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Right:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)')
Left:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(bInit, init1, init2)')
Next (Regular) Block[B15]
Leaving: {R2}
Entering: {R5} {R6} {R7}
}
.locals {R5}
{
CaptureIds: [9]
.locals {R6}
{
CaptureIds: [8]
.locals {R7}
{
CaptureIds: [7]
Block[B15] - Block
Predecessors: [B14] [B30]
Statements (1)
IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B17]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R7}
Next (Regular) Block[B16]
Block[B16] - Block
Predecessors: [B15]
Statements (1)
IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B18]
Leaving: {R7}
}
Block[B17] - Block
Predecessors: [B15]
Statements (1)
IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B18]
Block[B18] - Block
Predecessors: [B16] [B17]
Statements (1)
IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As C (OperationKind.FieldReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B19]
Leaving: {R6}
}
Block[B19] - Block
Predecessors: [B18]
Statements (0)
Jump if False (Regular) to Block[B21]
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Next (Regular) Block[B20]
Block[B20] - Block
Predecessors: [B19]
Statements (0)
Jump if False (Regular) to Block[B31]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual, Checked) (OperatorMethod: Function C.op_LessThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Left:
IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Leaving: {R5} {R1}
Next (Regular) Block[B22]
Leaving: {R5}
Block[B21] - Block
Predecessors: [B19]
Statements (0)
Jump if False (Regular) to Block[B31]
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Left:
IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Leaving: {R5} {R1}
Next (Regular) Block[B22]
Leaving: {R5}
}
Block[B22] - Block
Predecessors: [B20] [B21]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B23]
Entering: {R8} {R9} {R10}
.locals {R8}
{
CaptureIds: [12] [14]
.locals {R9}
{
CaptureIds: [11]
.locals {R10}
{
CaptureIds: [10]
Block[B23] - Block
Predecessors: [B22]
Statements (1)
IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B25]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R10}
Next (Regular) Block[B24]
Block[B24] - Block
Predecessors: [B23]
Statements (1)
IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B26]
Leaving: {R10}
}
Block[B25] - Block
Predecessors: [B23]
Statements (1)
IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B26]
Block[B26] - Block
Predecessors: [B24] [B25]
Statements (1)
IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As C (OperationKind.FieldReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B27]
Leaving: {R9}
Entering: {R11}
}
.locals {R11}
{
CaptureIds: [13]
Block[B27] - Block
Predecessors: [B26]
Statements (1)
IFlowCaptureOperation: 13 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B29]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 13 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R11}
Next (Regular) Block[B28]
Block[B28] - Block
Predecessors: [B27]
Statements (1)
IFlowCaptureOperation: 14 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 13 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B30]
Leaving: {R11}
}
Block[B29] - Block
Predecessors: [B27]
Statements (1)
IFlowCaptureOperation: 14 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B30]
Block[B30] - Block
Predecessors: [B28] [B29]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Left:
IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperatorMethod: Function C.op_Addition(x As C, y As C) As C) (OperationKind.Binary, Type: C, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Left:
IFieldReferenceOperation: C.i As C (OperationKind.FieldReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 14 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Right:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Next (Regular) Block[B15]
Leaving: {R8}
Entering: {R5} {R6} {R7}
}
}
Block[B31] - Exit
Predecessors: [B20] [B21]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_30()
Dim source = <![CDATA[
Imports System
Public Class C1
Sub M(c1 As C1, c2 As C1, bInit As Boolean, init1 As C?, init2 As C?, bLimit As Boolean, limit1 As C?, limit2 As C?, bStep As Boolean, step1 As C?, step2 As C?, result As Boolean) 'BIND:"Sub M"
For If(c1, c2).i = If(bInit, init1, init2) To If(bLimit, limit1, limit2) Step If(bStep, step1, step2)
result = true
Next
End Sub
Public i As C?
End Class
Public Structure C
Public Shared Operator >=(x As C, y As C) As Boolean
Return False
End Operator
Public Shared Operator <=(x As C, y As C) As Boolean
Return False
End Operator
Public Shared Operator -(x As C, y As C) As C
Return Nothing
End Operator
Public Shared Operator +(x As C, y As C) As C
Return Nothing
End Operator
End Structure
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2} {R3} {R4}
.locals {R1}
{
CaptureIds: [4] [5] [6]
.locals {R2}
{
CaptureIds: [2] [3]
.locals {R3}
{
CaptureIds: [1]
.locals {R4}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C1) (Syntax: 'c1')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1')
Leaving: {R4}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B4]
Leaving: {R4}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C1) (Syntax: 'c2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C1.i As System.Nullable(Of C) (OperationKind.FieldReference, Type: System.Nullable(Of C)) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B5] - Block
Predecessors: [B4]
Statements (0)
Jump if False (Regular) to Block[B7]
IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1')
Value:
IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'init1')
Next (Regular) Block[B8]
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2')
Value:
IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'init2')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (0)
Jump if False (Regular) to Block[B10]
IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit')
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1')
Value:
IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'limit1')
Next (Regular) Block[B11]
Block[B10] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2')
Value:
IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'limit2')
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B9] [B10]
Statements (0)
Jump if False (Regular) to Block[B13]
IParameterReferenceOperation: bStep (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bStep')
Next (Regular) Block[B12]
Block[B12] - Block
Predecessors: [B11]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step1')
Value:
IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'step1')
Next (Regular) Block[B14]
Block[B13] - Block
Predecessors: [B11]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step2')
Value:
IParameterReferenceOperation: step2 (OperationKind.ParameterReference, Type: System.Nullable(Of C)) (Syntax: 'step2')
Next (Regular) Block[B14]
Block[B14] - Block
Predecessors: [B12] [B13]
Statements (2)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Boolean).GetValueOrDefault() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Instance Receiver:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, IsLifted, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Nullable(Of System.Boolean), IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Right:
IBinaryOperation (BinaryOperatorKind.Subtract, IsLifted, Checked) (OperatorMethod: Function C.op_Subtraction(x As C, y As C) As C) (OperationKind.Binary, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Right:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Arguments(0)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)')
Left:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(bInit, init1, init2)')
Next (Regular) Block[B15]
Leaving: {R2}
Entering: {R5} {R6} {R7}
}
.locals {R5}
{
CaptureIds: [9]
.locals {R6}
{
CaptureIds: [8]
.locals {R7}
{
CaptureIds: [7]
Block[B15] - Block
Predecessors: [B14] [B30]
Statements (1)
IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B17]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1')
Leaving: {R7}
Next (Regular) Block[B16]
Block[B16] - Block
Predecessors: [B15]
Statements (1)
IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B18]
Leaving: {R7}
}
Block[B17] - Block
Predecessors: [B15]
Statements (1)
IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B18]
Block[B18] - Block
Predecessors: [B16] [B17]
Statements (1)
IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C1.i As System.Nullable(Of C) (OperationKind.FieldReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B19]
Leaving: {R6}
}
Block[B19] - Block
Predecessors: [B18]
Statements (0)
Jump if False (Regular) to Block[B21]
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Next (Regular) Block[B20]
Block[B20] - Block
Predecessors: [B19]
Statements (0)
Jump if False (Regular) to Block[B31]
IInvocationOperation ( Function System.Nullable(Of System.Boolean).GetValueOrDefault() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Instance Receiver:
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual, IsLifted, Checked) (OperatorMethod: Function C.op_LessThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Nullable(Of System.Boolean), IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Left:
IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Arguments(0)
Leaving: {R5} {R1}
Next (Regular) Block[B22]
Leaving: {R5}
Block[B21] - Block
Predecessors: [B19]
Statements (0)
Jump if False (Regular) to Block[B31]
IInvocationOperation ( Function System.Nullable(Of System.Boolean).GetValueOrDefault() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Instance Receiver:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual, IsLifted, Checked) (OperatorMethod: Function C.op_GreaterThanOrEqual(x As C, y As C) As System.Boolean) (OperationKind.Binary, Type: System.Nullable(Of System.Boolean), IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Left:
IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Arguments(0)
Leaving: {R5} {R1}
Next (Regular) Block[B22]
Leaving: {R5}
}
Block[B22] - Block
Predecessors: [B20] [B21]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B23]
Entering: {R8} {R9} {R10}
.locals {R8}
{
CaptureIds: [12] [14]
.locals {R9}
{
CaptureIds: [11]
.locals {R10}
{
CaptureIds: [10]
Block[B23] - Block
Predecessors: [B22]
Statements (1)
IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B25]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1')
Leaving: {R10}
Next (Regular) Block[B24]
Block[B24] - Block
Predecessors: [B23]
Statements (1)
IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B26]
Leaving: {R10}
}
Block[B25] - Block
Predecessors: [B23]
Statements (1)
IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B26]
Block[B26] - Block
Predecessors: [B24] [B25]
Statements (1)
IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C1.i As System.Nullable(Of C) (OperationKind.FieldReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B27]
Leaving: {R9}
Entering: {R11}
}
.locals {R11}
{
CaptureIds: [13]
Block[B27] - Block
Predecessors: [B26]
Statements (1)
IFlowCaptureOperation: 13 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B29]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 13 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1')
Leaving: {R11}
Next (Regular) Block[B28]
Block[B28] - Block
Predecessors: [B27]
Statements (1)
IFlowCaptureOperation: 14 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 13 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B30]
Leaving: {R11}
}
Block[B29] - Block
Predecessors: [B27]
Statements (1)
IFlowCaptureOperation: 14 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C1, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B30]
Block[B30] - Block
Predecessors: [B28] [B29]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Left:
IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(c1, c2).i')
Right:
IBinaryOperation (BinaryOperatorKind.Add, IsLifted, Checked) (OperatorMethod: Function C.op_Addition(x As C, y As C) As C) (OperationKind.Binary, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'For If(c1, ... ep1, step2)')
Left:
IFieldReferenceOperation: C1.i As System.Nullable(Of C) (OperationKind.FieldReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 14 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'If(c1, c2)')
Right:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of C), IsImplicit) (Syntax: 'If(bStep, step1, step2)')
Next (Regular) Block[B15]
Leaving: {R8}
Entering: {R5} {R6} {R7}
}
}
Block[B31] - Exit
Predecessors: [B20] [B21]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_31()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As Object, init As Object, limit As Object, result As Object) 'BIND:"Sub M"
For i = init To limit
result = i
Next
End Sub
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [<anonymous local> As System.Object]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Counter As System.Object, Start As System.Object, Limit As System.Object, StepValue As System.Object, ByRef LoopForResult As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Instance Receiver:
null
Arguments(6):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Start) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'init')
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Limit) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit')
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: StepValue) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'For i = ini ... Next')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'For i = ini ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningValue)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i = ini ... Next')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopForResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1] [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'i')
Jump if False (Regular) to Block[B3]
IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Counter As System.Object, LoopObj As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Instance Receiver:
null
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit')
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopObj) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit')
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit')
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R1}
Next (Regular) Block[B2]
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_32()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(init As Object, limit As Object, [step] as Object, result As Object) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [<anonymous local> As System.Object] [i As System.Object]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Counter As System.Object, Start As System.Object, Limit As System.Object, StepValue As System.Object, ByRef LoopForResult As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Instance Receiver:
null
Arguments(6):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Start) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'init')
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Limit) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit')
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: StepValue) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '[step]')
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: System.Object) (Syntax: '[step]')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopForResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1] [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result')
Right:
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Object) (Syntax: 'i')
Jump if False (Regular) to Block[B3]
IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Counter As System.Object, LoopObj As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Instance Receiver:
null
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit')
ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopObj) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit')
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit')
ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R1}
Next (Regular) Block[B2]
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_33()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(c1 As C, c2 As C, bInit As Boolean, init1 As Object, init2 As Object, bLimit As Boolean, limit1 As Object, limit2 As Object, bStep As Boolean, step1 As Object, step2 As Object, result As Boolean) 'BIND:"Sub M"
For If(c1, c2).i = If(bInit, init1, init2) To If(bLimit, limit1, limit2) Step If(bStep, step1, step2)
result = true
Next
End Sub
Public i As Object
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2} {R3} {R4}
.locals {R1}
{
Locals: [<anonymous local> As System.Object]
.locals {R2}
{
CaptureIds: [2] [3] [4] [5] [7]
.locals {R3}
{
CaptureIds: [1]
.locals {R4}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R4}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B4]
Leaving: {R4}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As System.Object (OperationKind.FieldReference, Type: System.Object) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B5] - Block
Predecessors: [B4]
Statements (0)
Jump if False (Regular) to Block[B7]
IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1')
Value:
IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init1')
Next (Regular) Block[B8]
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2')
Value:
IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init2')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (0)
Jump if False (Regular) to Block[B10]
IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit')
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1')
Value:
IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit1')
Next (Regular) Block[B11]
Block[B10] - Block
Predecessors: [B8]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2')
Value:
IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit2')
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B9] [B10]
Statements (0)
Jump if False (Regular) to Block[B13]
IParameterReferenceOperation: bStep (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bStep')
Next (Regular) Block[B12]
Block[B12] - Block
Predecessors: [B11]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step1')
Value:
IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'step1')
Next (Regular) Block[B14]
Entering: {R5}
Block[B13] - Block
Predecessors: [B11]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step2')
Value:
IParameterReferenceOperation: step2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'step2')
Next (Regular) Block[B14]
Entering: {R5}
.locals {R5}
{
CaptureIds: [6]
Block[B14] - Block
Predecessors: [B12] [B13]
Statements (1)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B16]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R5}
Next (Regular) Block[B15]
Block[B15] - Block
Predecessors: [B14]
Statements (1)
IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B17]
Leaving: {R5}
}
Block[B16] - Block
Predecessors: [B14]
Statements (1)
IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B17]
Block[B17] - Block
Predecessors: [B15] [B16]
Statements (0)
Jump if False (Regular) to Block[B27]
IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Counter As System.Object, Start As System.Object, Limit As System.Object, StepValue As System.Object, ByRef LoopForResult As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Instance Receiver:
null
Arguments(6):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Start) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)')
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(bInit, init1, init2)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Limit) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: StepValue) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopForResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
IFieldReferenceOperation: C.i As System.Object (OperationKind.FieldReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R2} {R1}
Next (Regular) Block[B26]
Leaving: {R2}
}
.locals {R6}
{
CaptureIds: [10] [12]
.locals {R7}
{
CaptureIds: [9]
.locals {R8}
{
CaptureIds: [8]
Block[B18] - Block
Predecessors: [B26]
Statements (1)
IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B20]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R8}
Next (Regular) Block[B19]
Block[B19] - Block
Predecessors: [B18]
Statements (1)
IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B21]
Leaving: {R8}
}
Block[B20] - Block
Predecessors: [B18]
Statements (1)
IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B21]
Block[B21] - Block
Predecessors: [B19] [B20]
Statements (1)
IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As System.Object (OperationKind.FieldReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B22]
Leaving: {R7}
Entering: {R9}
}
.locals {R9}
{
CaptureIds: [11]
Block[B22] - Block
Predecessors: [B21]
Statements (1)
IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B24]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R9}
Next (Regular) Block[B23]
Block[B23] - Block
Predecessors: [B22]
Statements (1)
IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B25]
Leaving: {R9}
}
Block[B24] - Block
Predecessors: [B22]
Statements (1)
IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B25]
Block[B25] - Block
Predecessors: [B23] [B24]
Statements (0)
Jump if False (Regular) to Block[B27]
IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Counter As System.Object, LoopObj As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Instance Receiver:
null
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopObj) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
IFieldReferenceOperation: C.i As System.Object (OperationKind.FieldReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R6} {R1}
Next (Regular) Block[B26]
Leaving: {R6}
}
Block[B26] - Block
Predecessors: [B17] [B25]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B18]
Entering: {R6} {R7} {R8}
}
Block[B27] - Exit
Predecessors: [B17] [B25]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_34()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(c1 As C, c2 As C, init1 As Object, limit1 As Object, step1 As Object, result As Boolean) 'BIND:"Sub M"
For If(c1, c2).i = init1 To limit1 Step step1
result = true
Next
End Sub
Public i As Object
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2} {R3} {R4}
.locals {R1}
{
Locals: [<anonymous local> As System.Object]
.locals {R2}
{
CaptureIds: [2] [3] [4] [5] [7]
.locals {R3}
{
CaptureIds: [1]
.locals {R4}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R4}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B4]
Leaving: {R4}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As System.Object (OperationKind.FieldReference, Type: System.Object) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B5] - Block
Predecessors: [B4]
Statements (3)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1')
Value:
IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init1')
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1')
Value:
IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit1')
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step1')
Value:
IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'step1')
Next (Regular) Block[B6]
Entering: {R5}
.locals {R5}
{
CaptureIds: [6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B8]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R5}
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B6]
Statements (1)
IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B9]
Leaving: {R5}
}
Block[B8] - Block
Predecessors: [B6]
Statements (1)
IFlowCaptureOperation: 7 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B9]
Block[B9] - Block
Predecessors: [B7] [B8]
Statements (0)
Jump if False (Regular) to Block[B19]
IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Counter As System.Object, Start As System.Object, Limit As System.Object, StepValue As System.Object, ByRef LoopForResult As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit1')
Instance Receiver:
null
Arguments(6):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Start) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'init1')
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'init1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Limit) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1')
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'limit1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: StepValue) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'step1')
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'step1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopForResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
IFieldReferenceOperation: C.i As System.Object (OperationKind.FieldReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 7 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R2} {R1}
Next (Regular) Block[B18]
Leaving: {R2}
}
.locals {R6}
{
CaptureIds: [10] [12]
.locals {R7}
{
CaptureIds: [9]
.locals {R8}
{
CaptureIds: [8]
Block[B10] - Block
Predecessors: [B18]
Statements (1)
IFlowCaptureOperation: 8 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B12]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R8}
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B10]
Statements (1)
IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 8 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B13]
Leaving: {R8}
}
Block[B12] - Block
Predecessors: [B10]
Statements (1)
IFlowCaptureOperation: 9 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B13]
Block[B13] - Block
Predecessors: [B11] [B12]
Statements (1)
IFlowCaptureOperation: 10 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(c1, c2).i')
Value:
IFieldReferenceOperation: C.i As System.Object (OperationKind.FieldReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 9 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
Next (Regular) Block[B14]
Leaving: {R7}
Entering: {R9}
}
.locals {R9}
{
CaptureIds: [11]
Block[B14] - Block
Predecessors: [B13]
Statements (1)
IFlowCaptureOperation: 11 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c1')
Jump if True (Regular) to Block[B16]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Leaving: {R9}
Next (Regular) Block[B15]
Block[B15] - Block
Predecessors: [B14]
Statements (1)
IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IFlowCaptureReferenceOperation: 11 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B17]
Leaving: {R9}
}
Block[B16] - Block
Predecessors: [B14]
Statements (1)
IFlowCaptureOperation: 12 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2')
Value:
IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C, IsImplicit) (Syntax: 'c2')
Next (Regular) Block[B17]
Block[B17] - Block
Predecessors: [B15] [B16]
Statements (0)
Jump if False (Regular) to Block[B19]
IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Counter As System.Object, LoopObj As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit1')
Instance Receiver:
null
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1')
IFlowCaptureReferenceOperation: 10 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopObj) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1')
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1')
IFieldReferenceOperation: C.i As System.Object (OperationKind.FieldReference, Type: System.Object, IsImplicit) (Syntax: 'If(c1, c2).i')
Instance Receiver:
IFlowCaptureReferenceOperation: 12 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R6} {R1}
Next (Regular) Block[B18]
Leaving: {R6}
}
Block[B18] - Block
Predecessors: [B9] [B17]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Next (Regular) Block[B10]
Entering: {R6} {R7} {R8}
}
Block[B19] - Exit
Predecessors: [B9] [B17]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_35()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As Object, bInit As Boolean, init1 As Object, init2 As Object, limit1 As Object, step1 As Object, result As Boolean) 'BIND:"Sub M"
For i = If(bInit, init1, init2) To limit1 Step step1
result = true
Next
End Sub
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
Locals: [<anonymous local> As System.Object]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'i')
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: bInit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bInit')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1')
Value:
IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init1')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init2')
Value:
IParameterReferenceOperation: init2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (0)
Jump if False (Regular) to Block[B6]
IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Counter As System.Object, Start As System.Object, Limit As System.Object, StepValue As System.Object, ByRef LoopForResult As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit1')
Instance Receiver:
null
Arguments(6):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Start) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bInit, init1, init2)')
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(bInit, init1, init2)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Limit) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1')
IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: StepValue) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'step1')
IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'step1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopForResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R2} {R1}
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B5] - Block
Predecessors: [B4] [B5]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Jump if False (Regular) to Block[B6]
IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Counter As System.Object, LoopObj As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit1')
Instance Receiver:
null
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1')
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopObj) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1')
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1')
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R1}
Next (Regular) Block[B5]
}
Block[B6] - Exit
Predecessors: [B4] [B5]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_36()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As Object, init1 As Object, bLimit As Boolean, limit1 As Object, limit2 As Object, step1 As Object, result As Boolean) 'BIND:"Sub M"
For i = init1 To If(bLimit, limit1, limit2) Step step1
result = true
Next
End Sub
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
Locals: [<anonymous local> As System.Object]
.locals {R2}
{
CaptureIds: [0] [1] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1')
Value:
IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init1')
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: bLimit (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bLimit')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1')
Value:
IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit1')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit2')
Value:
IParameterReferenceOperation: limit2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (0)
Jump if False (Regular) to Block[B6]
IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Counter As System.Object, Start As System.Object, Limit As System.Object, StepValue As System.Object, ByRef LoopForResult As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Instance Receiver:
null
Arguments(6):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Start) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'init1')
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'init1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Limit) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: StepValue) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'step1')
IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'step1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopForResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R2} {R1}
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B5] - Block
Predecessors: [B4] [B5]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Jump if False (Regular) to Block[B6]
IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Counter As System.Object, LoopObj As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
Instance Receiver:
null
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopObj) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bLimit, ... t1, limit2)')
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R1}
Next (Regular) Block[B5]
}
Block[B6] - Exit
Predecessors: [B4] [B5]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_37()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As Object, init1 As Object, limit1 As Object, bStep As Boolean, step1 As Object, step2 As Object, result As Boolean) 'BIND:"Sub M"
For i = init1 To limit1 Step If(bStep, step1, step2)
result = true
Next
End Sub
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
Locals: [<anonymous local> As System.Object]
.locals {R2}
{
CaptureIds: [0] [1] [2] [3]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init1')
Value:
IParameterReferenceOperation: init1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init1')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit1')
Value:
IParameterReferenceOperation: limit1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit1')
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: bStep (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'bStep')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step1')
Value:
IParameterReferenceOperation: step1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'step1')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'step2')
Value:
IParameterReferenceOperation: step2 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'step2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (0)
Jump if False (Regular) to Block[B6]
IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Counter As System.Object, Start As System.Object, Limit As System.Object, StepValue As System.Object, ByRef LoopForResult As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit1')
Instance Receiver:
null
Arguments(6):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Start) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'init1')
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'init1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Limit) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'limit1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: StepValue) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'If(bStep, step1, step2)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopForResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R2} {R1}
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B5] - Block
Predecessors: [B4] [B5]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = true')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
Jump if False (Regular) to Block[B6]
IInvocationOperation (Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Counter As System.Object, LoopObj As System.Object, ByRef CounterResult As System.Object) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'limit1')
Instance Receiver:
null
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Counter) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1')
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: LoopObj) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1')
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: CounterResult) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'limit1')
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Leaving: {R1}
Next (Regular) Block[B5]
}
Block[B6] - Exit
Predecessors: [B4] [B5]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_38()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As Object, init As Object, limit As Object, result As Object) 'BIND:"Sub M"
For i = init To limit
result = i
Next
End Sub
End Class
]]>.Value
Dim compilation = CreateCompilationWithMscorlib45(source, options:=TestOptions.ReleaseDebugDll)
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [<anonymous local> As System.Object]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Children(5):
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'i')
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'init')
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'limit')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'For i = ini ... Next')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningValue)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'For i = ini ... Next')
ILocalReferenceOperation: (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i')
Leaving: {R1}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1] [B2]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'i')
Jump if False (Regular) to Block[B3]
IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Children(2):
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Object, IsImplicit) (Syntax: 'i')
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'i')
Leaving: {R1}
Next (Regular) Block[B2]
}
Block[B3] - Exit
Predecessors: [B1] [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(compilation, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForToFlow_39()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(i As Integer?, init As Integer?, limit As Integer?, [step] As Integer?, result As Integer?) 'BIND:"Sub M"
For i = init To limit Step [step]
result = i
Next
End Sub
End Class
]]>.Value
Dim compilation = CreateCompilationWithMscorlib45(source, options:=TestOptions.ReleaseDebugDll)
compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault)
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [2] [3] [4]
.locals {R2}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (4)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'init')
Value:
IParameterReferenceOperation: init (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'init')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'limit')
Value:
IParameterReferenceOperation: limit (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'limit')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
IParameterReferenceOperation: step (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: '[step]')
Jump if False (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Operand:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '[step]')
Value:
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Left:
IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: '[step]')
Children(1):
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'init')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'init')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B5] - Block
Predecessors: [B4] [B11] [B12]
Statements (0)
Jump if False (Regular) to Block[B6]
IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Left:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'limit')
Right:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i')
Operand:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Entering: {R3}
Next (Regular) Block[B13]
Leaving: {R1}
.locals {R3}
{
CaptureIds: [5]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: 'i')
Children(1):
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Jump if False (Regular) to Block[B8]
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B6]
Statements (0)
Jump if False (Regular) to Block[B13]
IBinaryOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: 'limit')
Children(1):
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'limit')
Leaving: {R3} {R1}
Next (Regular) Block[B9]
Leaving: {R3}
Block[B8] - Block
Predecessors: [B6]
Statements (0)
Jump if False (Regular) to Block[B13]
IBinaryOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'limit')
Left:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i')
Right:
IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: 'limit')
Children(1):
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'limit')
Leaving: {R3} {R1}
Next (Regular) Block[B9]
Leaving: {R3}
}
Block[B9] - Block
Predecessors: [B7] [B8]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'result = i')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'result')
Right:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i')
Next (Regular) Block[B10]
Entering: {R4}
.locals {R4}
{
CaptureIds: [6]
Block[B10] - Block
Predecessors: [B9]
Statements (1)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Jump if False (Regular) to Block[B12]
IBinaryOperation (BinaryOperatorKind.Or) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Left:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: '[step]')
Operand:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]')
Right:
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i')
Operand:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Next (Regular) Block[B11]
Block[B11] - Block
Predecessors: [B10]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Right:
IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Next (Regular) Block[B5]
Leaving: {R4}
Block[B12] - Block
Predecessors: [B10]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'i')
Left:
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningNullable)
Operand:
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, IsImplicit) (Syntax: '[step]')
Left:
IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: 'i')
Children(1):
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i')
Right:
IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: '[step]')
Children(1):
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: '[step]')
Next (Regular) Block[B5]
Leaving: {R4}
}
}
Block[B13] - Exit
Predecessors: [B5] [B7] [B8]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(compilation, expectedFlowGraph, expectedDiagnostics)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/CSharp/Portable/Organizing/Organizers/StructDeclarationOrganizer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Organizing.Organizers;
namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers
{
[ExportSyntaxNodeOrganizer(LanguageNames.CSharp), Shared]
internal class StructDeclarationOrganizer : AbstractSyntaxNodeOrganizer<StructDeclarationSyntax>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public StructDeclarationOrganizer()
{
}
protected override StructDeclarationSyntax Organize(
StructDeclarationSyntax syntax,
CancellationToken cancellationToken)
{
return syntax.Update(
syntax.AttributeLists,
ModifiersOrganizer.Organize(syntax.Modifiers),
syntax.Keyword,
syntax.Identifier,
syntax.TypeParameterList,
syntax.BaseList,
syntax.ConstraintClauses,
syntax.OpenBraceToken,
MemberDeclarationsOrganizer.Organize(syntax.Members, cancellationToken),
syntax.CloseBraceToken,
syntax.SemicolonToken);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Organizing.Organizers;
namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers
{
[ExportSyntaxNodeOrganizer(LanguageNames.CSharp), Shared]
internal class StructDeclarationOrganizer : AbstractSyntaxNodeOrganizer<StructDeclarationSyntax>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public StructDeclarationOrganizer()
{
}
protected override StructDeclarationSyntax Organize(
StructDeclarationSyntax syntax,
CancellationToken cancellationToken)
{
return syntax.Update(
syntax.AttributeLists,
ModifiersOrganizer.Organize(syntax.Modifiers),
syntax.Keyword,
syntax.Identifier,
syntax.TypeParameterList,
syntax.BaseList,
syntax.ConstraintClauses,
syntax.OpenBraceToken,
MemberDeclarationsOrganizer.Organize(syntax.Members, cancellationToken),
syntax.CloseBraceToken,
syntax.SemicolonToken);
}
}
}
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Impl/CodeModel/MethodXml/AbstractMethodXmlBuilder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Globalization;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.MethodXml
{
internal abstract partial class AbstractMethodXmlBuilder
{
private const string ArgumentElementName = "Argument";
private const string ArrayElementName = "Array";
private const string ArrayElementAccessElementName = "ArrayElementAccess";
private const string ArrayTypeElementName = "ArrayType";
private const string AssignmentElementName = "Assignment";
private const string BaseReferenceElementName = "BaseReference";
private const string BinaryOperationElementName = "BinaryOperation";
private const string BlockElementName = "Block";
private const string BooleanElementName = "Boolean";
private const string BoundElementName = "Bound";
private const string CastElementName = "Cast";
private const string CharElementName = "Char";
private const string CommentElementName = "Comment";
private const string ExpressionElementName = "Expression";
private const string ExpressionStatementElementName = "ExpressionStatement";
private const string LiteralElementName = "Literal";
private const string LocalElementName = "Local";
private const string MethodCallElementName = "MethodCall";
private const string NameElementName = "Name";
private const string NameRefElementName = "NameRef";
private const string NewArrayElementName = "NewArray";
private const string NewClassElementName = "NewClass";
private const string NewDelegateElementName = "NewDelegate";
private const string NullElementName = "Null";
private const string NumberElementName = "Number";
private const string ParenthesesElementName = "Parentheses";
private const string QuoteElementName = "Quote";
private const string StringElementName = "String";
private const string ThisReferenceElementName = "ThisReference";
private const string TypeElementName = "Type";
private const string BinaryOperatorAttributeName = "binaryoperator";
private const string DirectCastAttributeName = "directcast";
private const string FullNameAttributeName = "fullname";
private const string ImplicitAttributeName = "implicit";
private const string LineAttributeName = "line";
private const string NameAttributeName = "name";
private const string RankAttributeName = "rank";
private const string TryCastAttributeName = "trycast";
private const string TypeAttributeName = "type";
private const string VariableKindAttributeName = "variablekind";
private static readonly char[] s_encodedChars = new[] { '<', '>', '&' };
private static readonly string[] s_encodings = new[] { "<", ">", "&" };
private readonly StringBuilder _builder;
protected readonly IMethodSymbol Symbol;
protected readonly SemanticModel SemanticModel;
protected readonly SourceText Text;
protected AbstractMethodXmlBuilder(IMethodSymbol symbol, SemanticModel semanticModel)
{
_builder = new StringBuilder();
this.Symbol = symbol;
this.SemanticModel = semanticModel;
this.Text = semanticModel.SyntaxTree.GetText();
}
public override string ToString()
=> _builder.ToString();
private void AppendEncoded(string text)
{
var length = text.Length;
var startIndex = 0;
int index;
for (index = 0; index < length; index++)
{
var encodingIndex = Array.IndexOf(s_encodedChars, text[index]);
if (encodingIndex >= 0)
{
if (index > startIndex)
{
_builder.Append(text, startIndex, index - startIndex);
}
_builder.Append(s_encodings[encodingIndex]);
startIndex = index + 1;
}
}
if (index > startIndex)
{
_builder.Append(text, startIndex, index - startIndex);
}
}
private void AppendOpenTag(string name, AttributeInfo[] attributes)
{
_builder.Append('<');
_builder.Append(name);
foreach (var attribute in attributes.Where(a => !a.IsEmpty))
{
_builder.Append(' ');
_builder.Append(attribute.Name);
_builder.Append("=\"");
AppendEncoded(attribute.Value);
_builder.Append('"');
}
_builder.Append('>');
}
private void AppendCloseTag(string name)
{
_builder.Append("</");
_builder.Append(name);
_builder.Append('>');
}
private void AppendLeafTag(string name)
{
_builder.Append('<');
_builder.Append(name);
_builder.Append("/>");
}
private static string GetBinaryOperatorKindText(BinaryOperatorKind kind)
=> kind switch
{
BinaryOperatorKind.Plus => "plus",
BinaryOperatorKind.BitwiseOr => "bitor",
BinaryOperatorKind.BitwiseAnd => "bitand",
BinaryOperatorKind.Concatenate => "concatenate",
BinaryOperatorKind.AddDelegate => "adddelegate",
_ => throw new InvalidOperationException("Invalid BinaryOperatorKind: " + kind.ToString()),
};
private static string GetVariableKindText(VariableKind kind)
=> kind switch
{
VariableKind.Property => "property",
VariableKind.Method => "method",
VariableKind.Field => "field",
VariableKind.Local => "local",
VariableKind.Unknown => "unknown",
_ => throw new InvalidOperationException("Invalid SymbolKind: " + kind.ToString()),
};
private IDisposable Tag(string name, params AttributeInfo[] attributes)
=> new AutoTag(this, name, attributes);
private AttributeInfo BinaryOperatorAttribute(BinaryOperatorKind kind)
{
if (kind == BinaryOperatorKind.None)
{
return AttributeInfo.Empty;
}
return new AttributeInfo(BinaryOperatorAttributeName, GetBinaryOperatorKindText(kind));
}
private AttributeInfo FullNameAttribute(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return AttributeInfo.Empty;
}
return new AttributeInfo(FullNameAttributeName, name);
}
private AttributeInfo ImplicitAttribute(bool? @implicit)
{
if (@implicit == null)
{
return AttributeInfo.Empty;
}
return new AttributeInfo(ImplicitAttributeName, @implicit.Value ? "yes" : "no");
}
private AttributeInfo LineNumberAttribute(int lineNumber)
=> new AttributeInfo(LineAttributeName, lineNumber.ToString());
private AttributeInfo NameAttribute(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return AttributeInfo.Empty;
}
return new AttributeInfo(NameAttributeName, name);
}
private AttributeInfo RankAttribute(int rank)
=> new AttributeInfo(RankAttributeName, rank.ToString());
private AttributeInfo SpecialCastKindAttribute(SpecialCastKind? specialCastKind = null)
=> specialCastKind switch
{
SpecialCastKind.DirectCast => new AttributeInfo(DirectCastAttributeName, "yes"),
SpecialCastKind.TryCast => new AttributeInfo(TryCastAttributeName, "yes"),
_ => AttributeInfo.Empty,
};
private AttributeInfo TypeAttribute(string typeName)
{
if (string.IsNullOrWhiteSpace(typeName))
{
return AttributeInfo.Empty;
}
return new AttributeInfo(TypeAttributeName, typeName);
}
private AttributeInfo VariableKindAttribute(VariableKind kind)
{
if (kind == VariableKind.None)
{
return AttributeInfo.Empty;
}
return new AttributeInfo(VariableKindAttributeName, GetVariableKindText(kind));
}
protected IDisposable ArgumentTag()
=> Tag(ArgumentElementName);
protected IDisposable ArrayElementAccessTag()
=> Tag(ArrayElementAccessElementName);
protected IDisposable ArrayTag()
=> Tag(ArrayElementName);
protected IDisposable ArrayTypeTag(int rank)
=> Tag(ArrayTypeElementName, RankAttribute(rank));
protected IDisposable AssignmentTag(BinaryOperatorKind kind = BinaryOperatorKind.None)
=> Tag(AssignmentElementName, BinaryOperatorAttribute(kind));
protected void BaseReferenceTag()
=> AppendLeafTag(BaseReferenceElementName);
protected IDisposable BinaryOperationTag(BinaryOperatorKind kind)
=> Tag(BinaryOperationElementName, BinaryOperatorAttribute(kind));
protected IDisposable BlockTag()
=> Tag(BlockElementName);
protected IDisposable BooleanTag()
=> Tag(BooleanElementName);
protected IDisposable BoundTag()
=> Tag(BoundElementName);
protected IDisposable CastTag(SpecialCastKind? specialCastKind = null)
=> Tag(CastElementName, SpecialCastKindAttribute(specialCastKind));
protected IDisposable CharTag()
=> Tag(CharElementName);
protected IDisposable CommentTag()
=> Tag(CommentElementName);
protected IDisposable ExpressionTag()
=> Tag(ExpressionElementName);
protected IDisposable ExpressionStatementTag(int lineNumber)
=> Tag(ExpressionStatementElementName, LineNumberAttribute(lineNumber));
protected IDisposable LiteralTag()
=> Tag(LiteralElementName);
protected IDisposable LocalTag(int lineNumber)
=> Tag(LocalElementName, LineNumberAttribute(lineNumber));
protected IDisposable MethodCallTag()
=> Tag(MethodCallElementName);
protected IDisposable NameTag()
=> Tag(NameElementName);
protected IDisposable NameRefTag(VariableKind kind, string name = null, string fullName = null)
=> Tag(NameRefElementName, VariableKindAttribute(kind), NameAttribute(name), FullNameAttribute(fullName));
protected IDisposable NewArrayTag()
=> Tag(NewArrayElementName);
protected IDisposable NewClassTag()
=> Tag(NewClassElementName);
protected IDisposable NewDelegateTag(string name)
=> Tag(NewDelegateElementName, NameAttribute(name));
protected void NullTag()
=> AppendLeafTag(NullElementName);
protected IDisposable NumberTag(string typeName = null)
=> Tag(NumberElementName, TypeAttribute(typeName));
protected IDisposable ParenthesesTag()
=> Tag(ParenthesesElementName);
protected IDisposable QuoteTag(int lineNumber)
=> Tag(QuoteElementName, LineNumberAttribute(lineNumber));
protected IDisposable StringTag()
=> Tag(StringElementName);
protected void ThisReferenceTag()
=> AppendLeafTag(ThisReferenceElementName);
protected IDisposable TypeTag(bool? @implicit = null)
=> Tag(TypeElementName, ImplicitAttribute(@implicit));
protected void LineBreak()
=> _builder.AppendLine();
protected void EncodedText(string text)
=> AppendEncoded(text);
protected int GetMark()
=> _builder.Length;
protected void Rewind(int mark)
=> _builder.Length = mark;
protected virtual VariableKind GetVariableKind(ISymbol symbol)
{
if (symbol == null)
{
return VariableKind.Unknown;
}
switch (symbol.Kind)
{
case SymbolKind.Event:
case SymbolKind.Field:
return VariableKind.Field;
case SymbolKind.Local:
case SymbolKind.Parameter:
return VariableKind.Local;
case SymbolKind.Method:
return VariableKind.Method;
case SymbolKind.Property:
return VariableKind.Property;
default:
throw new InvalidOperationException("Invalid symbol kind: " + symbol.Kind.ToString());
}
}
protected string GetTypeName(ITypeSymbol typeSymbol)
=> MetadataNameHelpers.GetMetadataName(typeSymbol);
protected int GetLineNumber(SyntaxNode node)
=> Text.Lines.IndexOf(node.SpanStart);
protected void GenerateUnknown(SyntaxNode node)
{
using (QuoteTag(GetLineNumber(node)))
{
EncodedText(node.ToString());
}
}
protected void GenerateName(string name)
{
using (NameTag())
{
EncodedText(name);
}
}
protected void GenerateType(ITypeSymbol type, bool? @implicit = null, bool assemblyQualify = false)
{
if (type.TypeKind == TypeKind.Array)
{
var arrayType = (IArrayTypeSymbol)type;
using var tag = ArrayTypeTag(arrayType.Rank);
GenerateType(arrayType.ElementType, @implicit, assemblyQualify);
}
else
{
using (TypeTag(@implicit))
{
var typeName = assemblyQualify
? GetTypeName(type) + ", " + type.ContainingAssembly.ToDisplayString()
: GetTypeName(type);
EncodedText(typeName);
}
}
}
protected void GenerateType(SpecialType specialType)
=> GenerateType(SemanticModel.Compilation.GetSpecialType(specialType));
protected void GenerateNullLiteral()
{
using (LiteralTag())
{
NullTag();
}
}
protected void GenerateNumber(object value, ITypeSymbol type)
{
using (NumberTag(GetTypeName(type)))
{
if (value is double d)
{
// Note: use G17 for doubles to ensure that we roundtrip properly on 64-bit
EncodedText(d.ToString("G17", CultureInfo.InvariantCulture));
}
else if (value is float f)
{
EncodedText(f.ToString("R", CultureInfo.InvariantCulture));
}
else
{
EncodedText(Convert.ToString(value, CultureInfo.InvariantCulture));
}
}
}
protected void GenerateNumber(object value, SpecialType specialType)
=> GenerateNumber(value, SemanticModel.Compilation.GetSpecialType(specialType));
protected void GenerateChar(char value)
{
using (CharTag())
{
EncodedText(value.ToString());
}
}
protected void GenerateString(string value)
{
using (StringTag())
{
EncodedText(value);
}
}
protected void GenerateBoolean(bool value)
{
using (BooleanTag())
{
EncodedText(value.ToString().ToLower());
}
}
protected void GenerateThisReference()
=> ThisReferenceTag();
protected void GenerateBaseReference()
=> BaseReferenceTag();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Globalization;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.MethodXml
{
internal abstract partial class AbstractMethodXmlBuilder
{
private const string ArgumentElementName = "Argument";
private const string ArrayElementName = "Array";
private const string ArrayElementAccessElementName = "ArrayElementAccess";
private const string ArrayTypeElementName = "ArrayType";
private const string AssignmentElementName = "Assignment";
private const string BaseReferenceElementName = "BaseReference";
private const string BinaryOperationElementName = "BinaryOperation";
private const string BlockElementName = "Block";
private const string BooleanElementName = "Boolean";
private const string BoundElementName = "Bound";
private const string CastElementName = "Cast";
private const string CharElementName = "Char";
private const string CommentElementName = "Comment";
private const string ExpressionElementName = "Expression";
private const string ExpressionStatementElementName = "ExpressionStatement";
private const string LiteralElementName = "Literal";
private const string LocalElementName = "Local";
private const string MethodCallElementName = "MethodCall";
private const string NameElementName = "Name";
private const string NameRefElementName = "NameRef";
private const string NewArrayElementName = "NewArray";
private const string NewClassElementName = "NewClass";
private const string NewDelegateElementName = "NewDelegate";
private const string NullElementName = "Null";
private const string NumberElementName = "Number";
private const string ParenthesesElementName = "Parentheses";
private const string QuoteElementName = "Quote";
private const string StringElementName = "String";
private const string ThisReferenceElementName = "ThisReference";
private const string TypeElementName = "Type";
private const string BinaryOperatorAttributeName = "binaryoperator";
private const string DirectCastAttributeName = "directcast";
private const string FullNameAttributeName = "fullname";
private const string ImplicitAttributeName = "implicit";
private const string LineAttributeName = "line";
private const string NameAttributeName = "name";
private const string RankAttributeName = "rank";
private const string TryCastAttributeName = "trycast";
private const string TypeAttributeName = "type";
private const string VariableKindAttributeName = "variablekind";
private static readonly char[] s_encodedChars = new[] { '<', '>', '&' };
private static readonly string[] s_encodings = new[] { "<", ">", "&" };
private readonly StringBuilder _builder;
protected readonly IMethodSymbol Symbol;
protected readonly SemanticModel SemanticModel;
protected readonly SourceText Text;
protected AbstractMethodXmlBuilder(IMethodSymbol symbol, SemanticModel semanticModel)
{
_builder = new StringBuilder();
this.Symbol = symbol;
this.SemanticModel = semanticModel;
this.Text = semanticModel.SyntaxTree.GetText();
}
public override string ToString()
=> _builder.ToString();
private void AppendEncoded(string text)
{
var length = text.Length;
var startIndex = 0;
int index;
for (index = 0; index < length; index++)
{
var encodingIndex = Array.IndexOf(s_encodedChars, text[index]);
if (encodingIndex >= 0)
{
if (index > startIndex)
{
_builder.Append(text, startIndex, index - startIndex);
}
_builder.Append(s_encodings[encodingIndex]);
startIndex = index + 1;
}
}
if (index > startIndex)
{
_builder.Append(text, startIndex, index - startIndex);
}
}
private void AppendOpenTag(string name, AttributeInfo[] attributes)
{
_builder.Append('<');
_builder.Append(name);
foreach (var attribute in attributes.Where(a => !a.IsEmpty))
{
_builder.Append(' ');
_builder.Append(attribute.Name);
_builder.Append("=\"");
AppendEncoded(attribute.Value);
_builder.Append('"');
}
_builder.Append('>');
}
private void AppendCloseTag(string name)
{
_builder.Append("</");
_builder.Append(name);
_builder.Append('>');
}
private void AppendLeafTag(string name)
{
_builder.Append('<');
_builder.Append(name);
_builder.Append("/>");
}
private static string GetBinaryOperatorKindText(BinaryOperatorKind kind)
=> kind switch
{
BinaryOperatorKind.Plus => "plus",
BinaryOperatorKind.BitwiseOr => "bitor",
BinaryOperatorKind.BitwiseAnd => "bitand",
BinaryOperatorKind.Concatenate => "concatenate",
BinaryOperatorKind.AddDelegate => "adddelegate",
_ => throw new InvalidOperationException("Invalid BinaryOperatorKind: " + kind.ToString()),
};
private static string GetVariableKindText(VariableKind kind)
=> kind switch
{
VariableKind.Property => "property",
VariableKind.Method => "method",
VariableKind.Field => "field",
VariableKind.Local => "local",
VariableKind.Unknown => "unknown",
_ => throw new InvalidOperationException("Invalid SymbolKind: " + kind.ToString()),
};
private IDisposable Tag(string name, params AttributeInfo[] attributes)
=> new AutoTag(this, name, attributes);
private AttributeInfo BinaryOperatorAttribute(BinaryOperatorKind kind)
{
if (kind == BinaryOperatorKind.None)
{
return AttributeInfo.Empty;
}
return new AttributeInfo(BinaryOperatorAttributeName, GetBinaryOperatorKindText(kind));
}
private AttributeInfo FullNameAttribute(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return AttributeInfo.Empty;
}
return new AttributeInfo(FullNameAttributeName, name);
}
private AttributeInfo ImplicitAttribute(bool? @implicit)
{
if (@implicit == null)
{
return AttributeInfo.Empty;
}
return new AttributeInfo(ImplicitAttributeName, @implicit.Value ? "yes" : "no");
}
private AttributeInfo LineNumberAttribute(int lineNumber)
=> new AttributeInfo(LineAttributeName, lineNumber.ToString());
private AttributeInfo NameAttribute(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return AttributeInfo.Empty;
}
return new AttributeInfo(NameAttributeName, name);
}
private AttributeInfo RankAttribute(int rank)
=> new AttributeInfo(RankAttributeName, rank.ToString());
private AttributeInfo SpecialCastKindAttribute(SpecialCastKind? specialCastKind = null)
=> specialCastKind switch
{
SpecialCastKind.DirectCast => new AttributeInfo(DirectCastAttributeName, "yes"),
SpecialCastKind.TryCast => new AttributeInfo(TryCastAttributeName, "yes"),
_ => AttributeInfo.Empty,
};
private AttributeInfo TypeAttribute(string typeName)
{
if (string.IsNullOrWhiteSpace(typeName))
{
return AttributeInfo.Empty;
}
return new AttributeInfo(TypeAttributeName, typeName);
}
private AttributeInfo VariableKindAttribute(VariableKind kind)
{
if (kind == VariableKind.None)
{
return AttributeInfo.Empty;
}
return new AttributeInfo(VariableKindAttributeName, GetVariableKindText(kind));
}
protected IDisposable ArgumentTag()
=> Tag(ArgumentElementName);
protected IDisposable ArrayElementAccessTag()
=> Tag(ArrayElementAccessElementName);
protected IDisposable ArrayTag()
=> Tag(ArrayElementName);
protected IDisposable ArrayTypeTag(int rank)
=> Tag(ArrayTypeElementName, RankAttribute(rank));
protected IDisposable AssignmentTag(BinaryOperatorKind kind = BinaryOperatorKind.None)
=> Tag(AssignmentElementName, BinaryOperatorAttribute(kind));
protected void BaseReferenceTag()
=> AppendLeafTag(BaseReferenceElementName);
protected IDisposable BinaryOperationTag(BinaryOperatorKind kind)
=> Tag(BinaryOperationElementName, BinaryOperatorAttribute(kind));
protected IDisposable BlockTag()
=> Tag(BlockElementName);
protected IDisposable BooleanTag()
=> Tag(BooleanElementName);
protected IDisposable BoundTag()
=> Tag(BoundElementName);
protected IDisposable CastTag(SpecialCastKind? specialCastKind = null)
=> Tag(CastElementName, SpecialCastKindAttribute(specialCastKind));
protected IDisposable CharTag()
=> Tag(CharElementName);
protected IDisposable CommentTag()
=> Tag(CommentElementName);
protected IDisposable ExpressionTag()
=> Tag(ExpressionElementName);
protected IDisposable ExpressionStatementTag(int lineNumber)
=> Tag(ExpressionStatementElementName, LineNumberAttribute(lineNumber));
protected IDisposable LiteralTag()
=> Tag(LiteralElementName);
protected IDisposable LocalTag(int lineNumber)
=> Tag(LocalElementName, LineNumberAttribute(lineNumber));
protected IDisposable MethodCallTag()
=> Tag(MethodCallElementName);
protected IDisposable NameTag()
=> Tag(NameElementName);
protected IDisposable NameRefTag(VariableKind kind, string name = null, string fullName = null)
=> Tag(NameRefElementName, VariableKindAttribute(kind), NameAttribute(name), FullNameAttribute(fullName));
protected IDisposable NewArrayTag()
=> Tag(NewArrayElementName);
protected IDisposable NewClassTag()
=> Tag(NewClassElementName);
protected IDisposable NewDelegateTag(string name)
=> Tag(NewDelegateElementName, NameAttribute(name));
protected void NullTag()
=> AppendLeafTag(NullElementName);
protected IDisposable NumberTag(string typeName = null)
=> Tag(NumberElementName, TypeAttribute(typeName));
protected IDisposable ParenthesesTag()
=> Tag(ParenthesesElementName);
protected IDisposable QuoteTag(int lineNumber)
=> Tag(QuoteElementName, LineNumberAttribute(lineNumber));
protected IDisposable StringTag()
=> Tag(StringElementName);
protected void ThisReferenceTag()
=> AppendLeafTag(ThisReferenceElementName);
protected IDisposable TypeTag(bool? @implicit = null)
=> Tag(TypeElementName, ImplicitAttribute(@implicit));
protected void LineBreak()
=> _builder.AppendLine();
protected void EncodedText(string text)
=> AppendEncoded(text);
protected int GetMark()
=> _builder.Length;
protected void Rewind(int mark)
=> _builder.Length = mark;
protected virtual VariableKind GetVariableKind(ISymbol symbol)
{
if (symbol == null)
{
return VariableKind.Unknown;
}
switch (symbol.Kind)
{
case SymbolKind.Event:
case SymbolKind.Field:
return VariableKind.Field;
case SymbolKind.Local:
case SymbolKind.Parameter:
return VariableKind.Local;
case SymbolKind.Method:
return VariableKind.Method;
case SymbolKind.Property:
return VariableKind.Property;
default:
throw new InvalidOperationException("Invalid symbol kind: " + symbol.Kind.ToString());
}
}
protected string GetTypeName(ITypeSymbol typeSymbol)
=> MetadataNameHelpers.GetMetadataName(typeSymbol);
protected int GetLineNumber(SyntaxNode node)
=> Text.Lines.IndexOf(node.SpanStart);
protected void GenerateUnknown(SyntaxNode node)
{
using (QuoteTag(GetLineNumber(node)))
{
EncodedText(node.ToString());
}
}
protected void GenerateName(string name)
{
using (NameTag())
{
EncodedText(name);
}
}
protected void GenerateType(ITypeSymbol type, bool? @implicit = null, bool assemblyQualify = false)
{
if (type.TypeKind == TypeKind.Array)
{
var arrayType = (IArrayTypeSymbol)type;
using var tag = ArrayTypeTag(arrayType.Rank);
GenerateType(arrayType.ElementType, @implicit, assemblyQualify);
}
else
{
using (TypeTag(@implicit))
{
var typeName = assemblyQualify
? GetTypeName(type) + ", " + type.ContainingAssembly.ToDisplayString()
: GetTypeName(type);
EncodedText(typeName);
}
}
}
protected void GenerateType(SpecialType specialType)
=> GenerateType(SemanticModel.Compilation.GetSpecialType(specialType));
protected void GenerateNullLiteral()
{
using (LiteralTag())
{
NullTag();
}
}
protected void GenerateNumber(object value, ITypeSymbol type)
{
using (NumberTag(GetTypeName(type)))
{
if (value is double d)
{
// Note: use G17 for doubles to ensure that we roundtrip properly on 64-bit
EncodedText(d.ToString("G17", CultureInfo.InvariantCulture));
}
else if (value is float f)
{
EncodedText(f.ToString("R", CultureInfo.InvariantCulture));
}
else
{
EncodedText(Convert.ToString(value, CultureInfo.InvariantCulture));
}
}
}
protected void GenerateNumber(object value, SpecialType specialType)
=> GenerateNumber(value, SemanticModel.Compilation.GetSpecialType(specialType));
protected void GenerateChar(char value)
{
using (CharTag())
{
EncodedText(value.ToString());
}
}
protected void GenerateString(string value)
{
using (StringTag())
{
EncodedText(value);
}
}
protected void GenerateBoolean(bool value)
{
using (BooleanTag())
{
EncodedText(value.ToString().ToLower());
}
}
protected void GenerateThisReference()
=> ThisReferenceTag();
protected void GenerateBaseReference()
=> BaseReferenceTag();
}
}
| -1 |
dotnet/roslyn | 54,989 | Fix 'add extern alias' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:17:20Z | 2021-07-20T23:56:59Z | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | 6c7e5b2437b149e8d8ca42aa5e79e721060b3dae | Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Test/Resources/Core/SymbolsTests/MultiModule/Consumer.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.
'vbc /t:library /vbruntime- Consumer.vb /r:MultiModule.dll
Public Class Derived1
Inherits Class1
End Class
Public Class Derived2
Inherits Class2
End Class
Public Class Derived3
Inherits Class3
End Class
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
'vbc /t:library /vbruntime- Consumer.vb /r:MultiModule.dll
Public Class Derived1
Inherits Class1
End Class
Public Class Derived2
Inherits Class2
End Class
Public Class Derived3
Inherits Class3
End Class
| -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.